-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcbam.py
177 lines (165 loc) · 6.98 KB
/
cbam.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
# offical
# 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 = F.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 = F.sigmoid(x_out) # broadcasting
# return x * scale
#
# class CBAM(nn.Module):
# def __init__(self, gate_channels=None, 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
# gpt
# class CBAM(nn.Module):
# def __init__(self, channels, reduction=16):
# super(CBAM, self).__init__()
# self.avg_pool = nn.AdaptiveAvgPool2d(1)
# self.max_pool = nn.AdaptiveMaxPool2d(1)
#
# # Channel attention
# self.fc1 = nn.Conv2d(channels, channels // reduction, kernel_size=1, padding=0)
# self.relu = nn.ReLU(inplace=True)
# self.fc2 = nn.Conv2d(channels // reduction, channels, kernel_size=1, padding=0)
#
# # Spatial attention
# self.conv1 = nn.Conv2d(2, 1, kernel_size=7, padding=3)
# self.sigmoid = nn.Sigmoid()
#
# def forward(self, x):
# # Channel attention
# avg_pool = self.avg_pool(x)
# max_pool = self.max_pool(x)
# avg_out = self.fc2(self.relu(self.fc1(avg_pool)))
# max_out = self.fc2(self.relu(self.fc1(max_pool)))
# channel_attention = torch.sigmoid(avg_out + max_out)
#
# # Spatial attention
# max_pool, _ = torch.max(x, dim=1, keepdim=True)
# avg_pool = torch.mean(x, dim=1, keepdim=True)
# spatial_attention = self.sigmoid(self.conv1(torch.cat([max_pool, avg_pool], dim=1)))
#
# # Combine channel and spatial attention
# x = x * channel_attention + x * spatial_attention
#
# return x
class ChannelAttentionModule(nn.Module):
def __init__(self, channel, ratio=16):
super(ChannelAttentionModule, self).__init__()
# 使用自适应池化缩减map的大小,保持通道不变
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.max_pool = nn.AdaptiveMaxPool2d(1)
self.shared_MLP = nn.Sequential(
nn.Conv2d(channel, channel // ratio, 1, bias=False),
nn.ReLU(),
nn.Conv2d(channel // ratio, channel, 1, bias=False)
)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
avgout = self.shared_MLP(self.avg_pool(x))
maxout = self.shared_MLP(self.max_pool(x))
return self.sigmoid(avgout + maxout)
class SpatialAttentionModule(nn.Module):
def __init__(self):
super(SpatialAttentionModule, self).__init__()
self.conv2d = nn.Conv2d(in_channels=2, out_channels=1, kernel_size=7, stride=1, padding=3)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
# map尺寸不变,缩减通道
avgout = torch.mean(x, dim=1, keepdim=True)
maxout, _ = torch.max(x, dim=1, keepdim=True)
out = torch.cat([avgout, maxout], dim=1)
out = self.sigmoid(self.conv2d(out))
return out
class CBAM(nn.Module):
def __init__(self, channel):
super(CBAM, self).__init__()
self.channel_attention = ChannelAttentionModule(channel)
self.spatial_attention = SpatialAttentionModule()
def forward(self, x):
out = self.channel_attention(x) * x
out = self.spatial_attention(out) * out
return out