class EnhancedResidual(nn.Module): def init(self,in_c,out_c,fm_sz,net_type = 'ta'): super(EnhancedResidual,self).init() self.net_type = net_type self.conv1 = nn.Sequential( nn.Conv2d(in_channels = in_c,out_channels = in_c,kernel_size = 3,padding = 1), nn.BatchNorm2d(in_c), nn.ReLU(), ) self.conv2 = nn.Sequential( nn.Conv2d(in_channels = in_c,out_channels = out_c,kernel_size = 3,padding = 1), nn.BatchNorm2d(out_c), nn.ReLU(), ) self.botneck = nn.Conv2d(in_channels = in_c,out_channels = out_c,kernel_size = 1) self.pool = nn.MaxPool2d(kernel_size = 2,stride = 2) if net_type == 'ta': self.spa = SpatialAttention() self.ca = ChannelAttention(in_planes = in_c,ratio = in_c) self.sa = MultiHeadSelfAttention(in_c = in_c,out_c = in_c // 4,head_n = 4,fm_sz = fm_sz) elif net_type == 'sa': self.sa = MultiHeadSelfAttention(in_c = in_c,out_c = out_c // 4,head_n = 4,fm_sz = fm_sz) elif net_type == 'cbam': self.spa = SpatialAttention() self.ca = ChannelAttention(in_planes = in_c,ratio = in_c) def forward(self,x): x0 = self.botneck(x) x = self.conv1(x) if self.net_type == 'sa': x = self.sa(x) #x = self.conv2(x) elif self.net_type == 'cbam': x = self.ca(x) * x x = self.spa(x) * x x = self.conv2(x) elif self.net_type == 'ta': x = self.ca(x) * x x = self.spa(x) * x x = self.sa(x) x = self.conv2(x) x = x + x0 x = self.pool(x) return x 改写为tensorflow形式
时间: 2024-01-12 07:03:53 浏览: 96
python使用 __init__初始化操作简单示例
5星 · 资源好评率100%
import tensorflow as tf
class EnhancedResidual(tf.keras.layers.Layer):
def __init__(self, in_c, out_c, fm_sz, net_type='ta', **kwargs):
super(EnhancedResidual, self).__init__(**kwargs)
self.net_type = net_type
self.conv1 = tf.keras.Sequential([
tf.keras.layers.Conv2D(filters=in_c, kernel_size=3, padding='same'),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.ReLU()
])
self.conv2 = tf.keras.Sequential([
tf.keras.layers.Conv2D(filters=out_c, kernel_size=3, padding='same'),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.ReLU(),
])
self.botneck = tf.keras.layers.Conv2D(filters=out_c, kernel_size=1)
self.pool = tf.keras.layers.MaxPool2D(pool_size=2, strides=2)
if net_type == 'ta':
self.spa = SpatialAttention()
self.ca = ChannelAttention(in_planes=in_c, ratio=in_c)
self.sa = MultiHeadSelfAttention(in_c=in_c, out_c=in_c // 4, head_n=4, fm_sz=fm_sz)
elif net_type == 'sa':
self.sa = MultiHeadSelfAttention(in_c=in_c, out_c=out_c // 4, head_n=4, fm_sz=fm_sz)
elif net_type == 'cbam':
self.spa = SpatialAttention()
self.ca = ChannelAttention(in_planes=in_c, ratio=in_c)
def call(self, x):
x0 = self.botneck(x)
x = self.conv1(x)
if self.net_type == 'sa':
x = self.sa(x)
# x = self.conv2(x)
elif self.net_type == 'cbam':
x = self.ca(x) * x
x = self.spa(x) * x
x = self.conv2(x)
elif self.net_type == 'ta':
x = self.ca(x) * x
x = self.spa(x) * x
x = self.sa(x)
x = self.conv2(x)
x = x + x0
x = self.pool(x)
return x
阅读全文