YOLOv9有效提點|加入MobileViT 、SK 、Double Attention Networks、CoTAttention等幾十種注意力機制(五)

?


專欄介紹:YOLOv9改進系列 | 包含深度學習最新創新,主力高效漲點!!!


一、本文介紹

?本文只有代碼及注意力模塊簡介,YOLOv9中的添加教程:可以看這篇文章。

YOLOv9有效提點|加入SE、CBAM、ECA、SimAM等幾十種注意力機制(一)


MobileViT:《MOBILEVIT: LIGHT-WEIGHT, GENERAL-PURPOSE, AND MOBILE-FRIENDLY VISION TRANSFORMER》

????????MobileViT是一種輕量級和通用視覺轉換器,用于移動設備上的視覺任務。MobileViT結合了CNN和ViT的優點,提供了一個不同的視角來進行全局信息處理。

from torch import nn
import torch
from einops import rearrangeclass PreNorm(nn.Module):def __init__(self, dim, fn):super().__init__()self.ln = nn.LayerNorm(dim)self.fn = fndef forward(self, x, **kwargs):return self.fn(self.ln(x), **kwargs)class FeedForward(nn.Module):def __init__(self, dim, mlp_dim, dropout):super().__init__()self.net = nn.Sequential(nn.Linear(dim, mlp_dim),nn.SiLU(),nn.Dropout(dropout),nn.Linear(mlp_dim, dim),nn.Dropout(dropout))def forward(self, x):return self.net(x)class Attention(nn.Module):def __init__(self, dim, heads, head_dim, dropout):super().__init__()inner_dim = heads * head_dimproject_out = not (heads == 1 and head_dim == dim)self.heads = headsself.scale = head_dim ** -0.5self.attend = nn.Softmax(dim=-1)self.to_qkv = nn.Linear(dim, inner_dim * 3, bias=False)self.to_out = nn.Sequential(nn.Linear(inner_dim, dim),nn.Dropout(dropout)) if project_out else nn.Identity()def forward(self, x):qkv = self.to_qkv(x).chunk(3, dim=-1)q, k, v = map(lambda t: rearrange(t, 'b p n (h d) -> b p h n d', h=self.heads), qkv)dots = torch.matmul(q, k.transpose(-1, -2)) * self.scaleattn = self.attend(dots)out = torch.matmul(attn, v)out = rearrange(out, 'b p h n d -> b p n (h d)')return self.to_out(out)class Transformer(nn.Module):def __init__(self, dim, depth, heads, head_dim, mlp_dim, dropout=0.):super().__init__()self.layers = nn.ModuleList([])for _ in range(depth):self.layers.append(nn.ModuleList([PreNorm(dim, Attention(dim, heads, head_dim, dropout)),PreNorm(dim, FeedForward(dim, mlp_dim, dropout))]))def forward(self, x):out = xfor att, ffn in self.layers:out = out + att(out)out = out + ffn(out)return outclass MobileViTAttention(nn.Module):def __init__(self, in_channel=3, dim=512, kernel_size=3, patch_size=7):super().__init__()self.ph, self.pw = patch_size, patch_sizeself.conv1 = nn.Conv2d(in_channel, in_channel, kernel_size=kernel_size, padding=kernel_size // 2)self.conv2 = nn.Conv2d(in_channel, dim, kernel_size=1)self.trans = Transformer(dim=dim, depth=3, heads=8, head_dim=64, mlp_dim=1024)self.conv3 = nn.Conv2d(dim, in_channel, kernel_size=1)self.conv4 = nn.Conv2d(2 * in_channel, in_channel, kernel_size=kernel_size, padding=kernel_size // 2)def forward(self, x):y = x.clone()  # bs,c,h,w## Local Representationy = self.conv2(self.conv1(x))  # bs,dim,h,w## Global Representation_, _, h, w = y.shapey = rearrange(y, 'bs dim (nh ph) (nw pw) -> bs (ph pw) (nh nw) dim', ph=self.ph, pw=self.pw)  # bs,h,w,dimy = self.trans(y)y = rearrange(y, 'bs (ph pw) (nh nw) dim -> bs dim (nh ph) (nw pw)', ph=self.ph, pw=self.pw, nh=h // self.ph,nw=w // self.pw)  # bs,dim,h,w## Fusiony = self.conv3(y)  # bs,dim,h,wy = torch.cat([x, y], 1)  # bs,2*dim,h,wy = self.conv4(y)  # bs,c,h,wreturn y

《Selective Kernel Networks》

? ? ? ? SK是一個動態選擇機制,允許每個神經元根據輸入信息動態調整其感受野大小。設計了選擇性核(SK)單元作為構建塊,其中不同核大小的多個分支通過由這些分支中的信息引導的softmax注意力進行融合。這些分支上的不同注意力會產生融合層中神經元的不同大小的有效的感受野。多個SK單元堆疊成一個稱為選擇性核網絡(SKNet)的深層網絡。?

import numpy as np
import torch
from torch import nn
from torch.nn import init
from collections import OrderedDictclass SKAttention(nn.Module):def __init__(self, channel=512, kernels=[1, 3, 5, 7], reduction=16, group=1, L=32):super().__init__()self.d = max(L, channel // reduction)self.convs = nn.ModuleList([])for k in kernels:self.convs.append(nn.Sequential(OrderedDict([('conv', nn.Conv2d(channel, channel, kernel_size=k, padding=k // 2, groups=group)),('bn', nn.BatchNorm2d(channel)),('relu', nn.ReLU())])))self.fc = nn.Linear(channel, self.d)self.fcs = nn.ModuleList([])for i in range(len(kernels)):self.fcs.append(nn.Linear(self.d, channel))self.softmax = nn.Softmax(dim=0)def forward(self, x):bs, c, _, _ = x.size()conv_outs = []### splitfor conv in self.convs:conv_outs.append(conv(x))feats = torch.stack(conv_outs, 0)  # k,bs,channel,h,w### fuseU = sum(conv_outs)  # bs,c,h,w### reduction channelS = U.mean(-1).mean(-1)  # bs,cZ = self.fc(S)  # bs,d### calculate attention weightweights = []for fc in self.fcs:weight = fc(Z)weights.append(weight.view(bs, c, 1, 1))  # bs,channelattention_weughts = torch.stack(weights, 0)  # k,bs,channel,1,1attention_weughts = self.softmax(attention_weughts)  # k,bs,channel,1,1### fuseV = (attention_weughts * feats).sum(0)return V

《A2 -Nets: Double Attention Networks》

????????A2Nets是一種新的神經網絡組件,名為“雙注意力塊”,它能夠從整個輸入圖像/視頻中提取重要的全局特征,并使神經網絡更有效地訪問整個空間的特征,從而提高識別任務的性能。實驗表明,配備雙注意力塊的神經網絡在圖像和動作識別任務上均優于現有的更大規模神經網絡,同時參數和計算量也減少。

import numpy as np
import torch
from torch import nn
from torch.nn import init
from torch.nn import functional as Fclass DoubleAttention(nn.Module):def __init__(self, in_channels,c_m=128,c_n=128,reconstruct = True):super().__init__()self.in_channels=in_channelsself.reconstruct = reconstructself.c_m=c_mself.c_n=c_nself.convA=nn.Conv2d(in_channels,c_m,1)self.convB=nn.Conv2d(in_channels,c_n,1)self.convV=nn.Conv2d(in_channels,c_n,1)if self.reconstruct:self.conv_reconstruct = nn.Conv2d(c_m, in_channels, kernel_size = 1)self.init_weights()def init_weights(self):for m in self.modules():if isinstance(m, nn.Conv2d):init.kaiming_normal_(m.weight, mode='fan_out')if m.bias is not None:init.constant_(m.bias, 0)elif isinstance(m, nn.BatchNorm2d):init.constant_(m.weight, 1)init.constant_(m.bias, 0)elif isinstance(m, nn.Linear):init.normal_(m.weight, std=0.001)if m.bias is not None:init.constant_(m.bias, 0)def forward(self, x):b, c, h,w=x.shapeassert c==self.in_channelsA=self.convA(x) #b,c_m,h,wB=self.convB(x) #b,c_n,h,wV=self.convV(x) #b,c_n,h,wtmpA=A.view(b,self.c_m,-1)attention_maps=F.softmax(B.view(b,self.c_n,-1))attention_vectors=F.softmax(V.view(b,self.c_n,-1))# step 1: feature gatingglobal_descriptors=torch.bmm(tmpA,attention_maps.permute(0,2,1)) #b.c_m,c_n# step 2: feature distributiontmpZ = global_descriptors.matmul(attention_vectors) #b,c_m,h*wtmpZ=tmpZ.view(b,self.c_m,h,w) #b,c_m,h,wif self.reconstruct:tmpZ=self.conv_reconstruct(tmpZ)return tmpZ 

《Large Selective Kernel Network for Remote Sensing Object Detection》

?????????CoTAttention網絡是一種用于多模態場景下的視覺問答(Visual Question Answering,VQA)任務的神經網絡模型。它是在經典的注意力機制(Attention Mechanism)上進行了改進,能夠自適應地對不同的視覺和語言輸入進行注意力分配,從而更好地完成VQA任務。CoTAttention網絡中的“CoT”代表“Cross-modal Transformer”,即跨模態Transformer。在該網絡中,視覺和語言輸入分別被編碼為一組特征向量,然后通過一個跨模態的Transformer模塊進行交互和整合。在這個跨模態的Transformer模塊中,Co-Attention機制被用來計算視覺和語言特征之間的交互注意力,從而實現更好的信息交換和整合。在計算機視覺和自然語言處理緊密結合的VQA任務中,CoTAttention取得了很好的效果。

此代碼暫沒調試,代碼地址:https://github.com/JDAI-CV/CoTNet/tree/master/cot_experiments

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/716960.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/716960.shtml
英文地址,請注明出處:http://en.pswp.cn/news/716960.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

ETH網絡中的區塊鏈

回顧BTC網絡的區塊鏈系統 什么是區塊鏈?BTC網絡是如何運行的?BTC交易模式 - UXTO ETH網絡中的區塊鏈 ETH網絡的基石依舊是 區塊鏈。上面 什么是區塊鏈? 的文章依舊適用。 相比BTC網絡,ETH網絡的賬戶系統就相對復雜,所…

ZJGSU 1199 表達式計算

題目描述 在數據結構課上,老師給大家布置了一個表達式計算的問題 3*21*5. Its so easy!!! csw同學做了很不過癮,他想求解更復雜的表達式: 比如(123456)/789. 但一時之間他想不出好的辦法,諸位就幫幫他吧. 輸入 輸入包括多組數據, 每組測試…

實用工具:實時監控服務器CPU負載狀態并郵件通知并啟用開機自啟

作用:在服務器CPU高負載時發送郵件通知 目錄 一、功能代碼 二、配置開機自啟動該監控腳本 1,配置自啟腳本 2,啟動 三、功能測試 一、功能代碼 功能:在CPU負載超過預設置的90%閾值時就發送郵件通知!郵件內容顯示…

【Spring連載】使用Spring Data訪問 MongoDB----對象映射之屬性轉換器

【Spring連載】使用Spring Data訪問 MongoDB----對象映射之屬性轉換器 一、聲明式值轉換器二、編程式值轉換器注冊三、MongoCustomConversions配置 雖然基于類型的轉換已經提供了影響目標存儲中某些類型的轉換和表示的方法,但當僅考慮特定類型的某些值或屬性進行轉換…

js中Generator函數詳解

定義: promise是為了解決回調地獄的難題出現的,那么 Generator 就是為了解決異步問題而出現的。 普通函數,如果調用它會立即執行完畢;Generator 函數,它可以暫停,不一定馬上把函數體中的所有代碼執行完畢…

Linux基本指令(下)

目錄 1. less指令 2. head與tail指令 3. find指令 示例 4. grep指令 示例 ?編輯 5. zip/unzip 打包與壓縮 示例 ?編輯 6. tar指令 7. find指令: -name 8. echo指令 9. 時間相關的指令 1.在顯示方面,使用者可以設定欲顯示的格式&#xff…

分布式ID(6):Redis實現分布式ID生成

Redis是一個高性能的鍵值數據庫,它可以用于生成分布式唯一標識符。需要注意的是Redis實現ID可以用,這也是很多公司的選擇。但是在redis服務器宕機的情況下,他也可能會出現重復生成ID的情況。 1 實現原理 利用Redis的原子操作:Redis提供了原子性的INCR和INCRBY命令,可用于…

使用python或AI自動分析數據關聯(簡介)

有一些Python庫可以幫助用戶自動發現數據集中的關聯關系。通常這類方法被稱為關聯分析或關聯規則挖掘,其中最著名的算法是Apriori和FP-Growth。 兩個算法 Apriori算法: 這是一個用于頻繁項集挖掘和關聯規則學習的經典算法。Python中的mlxtend庫提供了一…

【機器學習】有監督學習算法之:K最近鄰

K最近鄰 1、引言2、決策樹2.1 定義2.2 原理2.3 實現方式2.3.1 距離度量2.3.2 K值的選擇 2.4 算法公式2.5 代碼示例 3、總結 1、引言 小屌絲:魚哥, 這么長時間沒更新了,是不是得抓緊時間了。 小魚:最近可都是在忙的呢,…

已解決ResponseEntityException的Spring MVC異常響應實體異常的正確解決方法,親測有效!!!

由于ResponseEntityException并非Spring框架中明確定義的異常類,我推斷這里可能指的是在使用ResponseEntity時遇到的常見異常或錯誤。因此,我將根據這個假設,提供一個解決Spring MVC中與ResponseEntity相關異常的通用方法指南。 目錄 問題分…

線上歷史館藏系統 Java+SpringBoot+Vue+MySQL

??計算機編程指導師 ??個人介紹:自己非常喜歡研究技術問題!專業做Java、Python、微信小程序、安卓、大數據、爬蟲、Golang、大屏等實戰項目。 ??實戰項目:有源碼或者技術上的問題歡迎在評論區一起討論交流! ?? Java實戰 |…

day09_商品管理訂單管理SpringTaskEcharts

文章目錄 1 商品管理1.1 添加功能1.1.1 需求說明1.1.2 核心概念SPUSKU 1.1.3 加載品牌數據CategoryBrandControllerCategoryBrandServiceCategoryBrandMapperCategoryBrandMapper.xml 1.1.4 加載商品單元數據ProductUnitProductUnitControllerProductUnitServiceProductUnitMap…

詳解java中的Lambda表達式

Lambda表達式的前世今生(來歷與概述) Lambda表達式的前世------匿名類 以往,使用單一抽象方法的接口被用作函數類型。 它們的實例表示函數(functions)或行動(actions)。 自從 JDK 1.1 于 1997…

【MySQL】超詳細-基礎操作

數據庫定義 數據庫是一類軟件,用來管理數據,組織數據; 關系型數據庫MySQL(Oracle,SQL Server,SQLite)以表格形式組織數據,數據格式要求嚴格;非關系型數據庫Redis(MongoDB,HBase&…

數據結構與算法-冒泡排序

引言 在數據結構與算法的世界里,冒泡排序作為基礎排序算法之一,以其直觀易懂的原理和實現方式,為理解更復雜的數據處理邏輯提供了堅實的入門階梯。盡管在實際應用中由于其效率問題不常被用于大規模數據的排序任務,但它對于每一位初…

【C++】set、multiset與map、multimap的使用

目錄 一、關聯式容器二、鍵值對三、樹形結構的關聯式容器3.1 set3.1.1 模板參數列表3.1.2 構造3.1.3 迭代器3.1.4 容量3.1.5 修改操作 3.2 multiset3.3 map3.3.1 模板參數列表3.3.2 構造3.3.3 迭代器3.3.4 容量3.3.5 修改操作3.3.6 operator[] 3.4 multimap 一、關聯式容器 談…

Hololens 2應用開發系列(1)——使用MRTK在Unity中設置混合現實場景并進行程序模擬

Hololens 2應用開發系列(1)——使用MRTK在Unity中進行程序模擬 一、前言二、創建和設置MR場景三、MRTK輸入模擬的開啟 一、前言 在前面的文章中,我介紹了Hololens 2開發環境搭建和項目生成部署等相關內容,使我們能生成一個簡單Ho…

Redis 之九:Spring Data Redis -- Redis Template 用法

SpringData Redis Spring Data Redis 是 Spring Data 項目的一部分,它為 Java 應用程序提供了一種便捷的方式來與 Redis 數據庫進行交互。 Spring Data Redis 提供了對 Redis 的抽象封裝,使得開發者能夠以面向對象的方式操作 Redis,并簡化了 …

matlab 寫入格式化文本文件

目錄 一、save函數 二、fprintf函數 matlab 寫入文本文件可以使用save和fprintf函數 save輸出結果: fprintf輸出結果: 1.23, 2.34, 3.45 4.56, 5.67, 6.78 7.89, 8.90, 9.01 可以看出fprintf輸出結果更加人性化,符合要求,下面分別介紹。 一、save函數 …

linux系統Jenkins工具介紹

Jenkins概念介紹 Jenkins概念Jenkins目的特性產品發布流程 Jenkins概念 Jenkins是一個功能強大的應用程序,允許持續集成和持續交付項目,無論用的是什么平臺。這是一個免費的源代碼,可以處理任何類型的構建或持續集成。集成Jenkins可以用于一些…