网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
a
v
g
c
)
)
W
1
(
W
0
(
F
max
c
)
)
)
=\sigma\left(\mathbf{W}_{\mathbf{1}}\left(\mathbf{W}_{\mathbf{o}}\left(\mathbf{F}_{\mathbf{a v g}}^{\mathbf{c}}\right)\right)+\mathbf{W}_{\mathbf{1}}\left(\mathbf{W}_{\mathbf{0}}\left(\mathbf{F}_{\max }^{\mathbf{c}}\right)\right)\right)
=σ(W1(Wo(Favgc))+W1(W0(Fmaxc)))
通道注意力结构如下:
在通道维度上进行全局的pooling操作,再经过同一个MLP得到权重,相加作为最终的注意力向量(权重)。
这里非常像SENet,SENet在很多论文中都被证实对效果有提升,这里的区别是,SENet采用的是平均值的pooling,这篇论文又加入了最大值pooling。作者在论文中,通过对比实验,证实max pooling提高了效果。
注意这里的MLP的中间层较小,这个可能有助于信息的整合。
空间注意力
论文中,作者认为通道注意力关注的是:what,然而空间注意力关注的是:Where。
公式如下:
M
s
(
F
)
=
σ
(
f
7
×
7
(
[
Avg
P
o
o
l
(
F
)
;
MaxPool
(
F
)
]
)
)
\mathbf{M}_{\mathbf{s}}(\mathbf{F})=\sigma\left(f^{7 \times 7}([\operatorname{Avg} P o o l(\mathbf{F}) ; \operatorname{MaxPool}(\mathbf{F})])\right)
Ms(F)=σ(f7×7([AvgPool(F);MaxPool(F)]))
=
σ
(
f
7
×
7
(
[
F
a
v
g
s
;
F
m
a
x
s
]
)
)
=\sigma\left(f^{7 \times 7}\left(\left[\mathbf{F}_{\mathrm{avg}}^{\mathrm{s}} ; \mathbf{F}_{\mathrm{max}}^{\mathrm{s}}\right]\right)\right)
=σ(f7×7([Favgs;Fmaxs]))
空间注意力结构图如下:
同样使用了avg-pooling和max-pooling来对信息进行评估,使用一个7*7的卷积来进行提取。
注意权重都通过sigmoid来进行归一化。
下图是一个将论文的方法应用到ResNet的例子:
将模型应用到每一个ResNet block的输出上。
Pytorch实现CBAM
此处代码是将其应用到resnext,可以在github链接查看代码实现
# -\*-coding:utf-8-\*-
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = ['cbam\_resnext29\_8x64d', 'cbam\_resnext29\_16x64d']
class BasicConv(nn.Module):
def \_\_init\_\_(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, relu=True, bn=True, bias=False):
super(BasicConv, self).__init__()
self.out_channels = out_planes
self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size,
stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias)
self.bn = nn.BatchNorm2d(out_planes, eps=1e-5,
momentum=0.01, affine=True) if bn else None
self.relu = nn.ReLU() if relu else None
def forward(self, x):
x = self.conv(x)
if self.bn is not None:
x = self.bn(x)
if self.relu is not None:
x = self.relu(x)
return x
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size(0), -1)
class ChannelGate(nn.Module):
def \_\_init\_\_(self, gate_channels, reduction_ratio=16, pool_types=['avg', 'max']):
super(ChannelGate, self).__init__()
self.gate_channels = gate_channels
self.mlp = nn.Sequential(
Flatten(),
nn.Linear(gate_channels, gate_channels // reduction_ratio),
nn.ReLU(),
nn.Linear(gate_channels // reduction_ratio, gate_channels)
)
self.pool_types = pool_types
def forward(self, x):
channel_att_sum = None
for pool_type in self.pool_types:
if pool_type == 'avg':
avg_pool = F.avg_pool2d(
x, (x.size(2), x.size(3)), stride=(x.size(2), x.size(3)))
channel_att_raw = self.mlp(avg_pool)
elif pool_type == 'max':
max_pool = F.max_pool2d(
x, (x.size(2), x.size(3)), stride=(x.size(2), x.size(3)))
channel_att_raw = self.mlp(max_pool)
elif pool_type == 'lp':
lp_pool = F.lp_pool2d(
x, 2, (x.size(2), x.size(3)), stride=(x.size(2), x.size(3)))
channel_att_raw = self.mlp(lp_pool)
elif pool_type == 'lse':
# LSE pool only
lse_pool = logsumexp_2d(x)
channel_att_raw = self.mlp(lse_pool)
if channel_att_sum is None:
channel_att_sum = channel_att_raw
else:
channel_att_sum = channel_att_sum + channel_att_raw
scale = torch.sigmoid(channel_att_sum).unsqueeze(
2).unsqueeze(3).expand_as(x)
return x \* scale
def logsumexp\_2d(tensor):
tensor_flatten = tensor.view(tensor.size(0), tensor.size(1), -1)
s, _ = torch.max(tensor_flatten, dim=2, keepdim=True)
outputs = s + (tensor_flatten - s).exp().sum(dim=2, keepdim=True).log()
return outputs
class ChannelPool(nn.Module):
def forward(self, x):
return torch.cat((torch.max(x, 1)[0].unsqueeze(1), torch.mean(x, 1).unsqueeze(1)), dim=1)
class SpatialGate(nn.Module):
def \_\_init\_\_(self):
super(SpatialGate, self).__init__()
kernel_size = 7
self.compress = ChannelPool()
self.spatial = BasicConv(2, 1, kernel_size, stride=1, padding=(
kernel_size-1) // 2, relu=False)
def forward(self, x):
x_compress = self.compress(x)
x_out = self.spatial(x_compress)
scale = torch.sigmoid(x_out) # broadcasting
return x \* scale
class CBAM(nn.Module):
def \_\_init\_\_(self, gate_channels, reduction_ratio=16, pool_types=['avg', 'max'], no_spatial=False):
super(CBAM, self).__init__()
self.ChannelGate = ChannelGate(
gate_channels, reduction_ratio, pool_types)
self.no_spatial = no_spatial
if not no_spatial:
self.SpatialGate = SpatialGate()
def forward(self, x):
x_out = self.ChannelGate(x)
if not self.no_spatial:
x_out = self.SpatialGate(x_out)
return x_out
class Bottleneck(nn.Module):
![img](https://img-blog.csdnimg.cn/img_convert/36ecb032d59e288269718fd99aac8a5c.png)
![img](https://img-blog.csdnimg.cn/img_convert/126c7471fd00d5c0551a928c8f3174cc.png)
**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上C C++开发知识点,真正体系化!**
**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**
**[如果你需要这些资料,可以戳这里获取](https://bbs.csdn.net/topics/618668825)**
x):
x_out = self.ChannelGate(x)
if not self.no_spatial:
x_out = self.SpatialGate(x_out)
return x_out
class Bottleneck(nn.Module):
[外链图片转存中...(img-4Pu8PSll-1715737754549)]
[外链图片转存中...(img-NHb58UQg-1715737754550)]
**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上C C++开发知识点,真正体系化!**
**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**
**[如果你需要这些资料,可以戳这里获取](https://bbs.csdn.net/topics/618668825)**