pytorch 搭建网络结构

pytorch 搭建 ResNet网络结构

网络结构图

a-fistful-of-dollars.png◎ ResNet网络结构图

实现代码

参考 [1]

  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
import torch.nn as nn
from torch.nn import functional as F

class ResNetModel(nn.Module):
    """
    实现通用的ResNet模块,可根据需要定义
    """
    def __init__(self, num_classes=1000, layer_num=[],bottleneck = False):
        super(ResNetModel, self).__init__()

        #conv1
        self.pre = nn.Sequential(
            #in 224*224*3
            nn.Conv2d(3,64,7,2,3,bias=False),   #输入通道3,输出通道64,卷积核7*7*64,步长2,根据以上计算出padding=3
            #out 112*112*64
            nn.BatchNorm2d(64),     #输入通道C = 64

            nn.ReLU(inplace=True),   #inplace=True, 进行覆盖操作
            # out 112*112*64
            nn.MaxPool2d(3,2,1),    #池化核3*3,步长2,计算得出padding=1;
            # out 56*56*64
        )

        if bottleneck:  #resnet50以上使用BottleNeckBlock
            self.residualBlocks1 = self.add_layers(64, 256, layer_num[0], 64, bottleneck=bottleneck)
            self.residualBlocks2 = self.add_layers(128, 512, layer_num[1], 256, 2,bottleneck)
            self.residualBlocks3 = self.add_layers(256, 1024, layer_num[2], 512, 2,bottleneck)
            self.residualBlocks4 = self.add_layers(512, 2048, layer_num[3], 1024, 2,bottleneck)

            self.fc = nn.Linear(2048, num_classes)
        else:   #resnet34使用普通ResidualBlock
            self.residualBlocks1 = self.add_layers(64,64,layer_num[0])
            self.residualBlocks2 = self.add_layers(64,128,layer_num[1])
            self.residualBlocks3 = self.add_layers(128,256,layer_num[2])
            self.residualBlocks4 = self.add_layers(256,512,layer_num[3])
            self.fc = nn.Linear(512, num_classes)

    def add_layers(self, inchannel, outchannel, nums, pre_channel=64, stride=1, bottleneck=False):
        layers = []
        if bottleneck is False:

            #添加大模块首层, 首层需要判断inchannel == outchannel ?
            #跨维度需要stride=2,shortcut也需要1*1卷积扩维

            layers.append(ResidualBlock(inchannel,outchannel))

            #添加剩余nums-1层
            for i in range(1,nums):
                layers.append(ResidualBlock(outchannel,outchannel))
            return nn.Sequential(*layers)
        else:   #resnet50使用bottleneck
            #传递每个block的shortcut,shortcut可以根据是否传递pre_channel进行推断

            #添加首层,首层需要传递上一批blocks的channel
            layers.append(BottleNeckBlock(inchannel,outchannel,pre_channel,stride))
            for i in range(1,nums): #添加n-1个剩余blocks,正常通道转换,不传递pre_channel
                layers.append(BottleNeckBlock(inchannel,outchannel))
            return nn.Sequential(*layers)

    def forward(self, x):
        x = self.pre(x)
        x = self.residualBlocks1(x)
        x = self.residualBlocks2(x)
        x = self.residualBlocks3(x)
        x = self.residualBlocks4(x)

        x = F.avg_pool2d(x, 7)
        x = x.view(x.size(0), -1)
        return self.fc(x)


class ResidualBlock(nn.Module):
    '''
    定义普通残差模块
    resnet34为普通残差块,resnet50为瓶颈结构
    '''
    def __init__(self, inchannel, outchannel, stride=1, padding=1, shortcut=None):
        super(ResidualBlock, self).__init__()
        #resblock的首层,首层如果跨维度,卷积stride=2,shortcut需要1*1卷积扩维
        if inchannel != outchannel:
            stride= 2
            shortcut=nn.Sequential(
                nn.Conv2d(inchannel,outchannel,1,stride,bias=False),
                nn.BatchNorm2d(outchannel)
            )

        # 定义残差块的左部分
        self.left = nn.Sequential(
            nn.Conv2d(inchannel, outchannel, 3, stride, padding, bias=False),
            nn.BatchNorm2d(outchannel),
            nn.ReLU(inplace=True),

            nn.Conv2d(outchannel, outchannel, 3, 1, padding, bias=False),
            nn.BatchNorm2d(outchannel),

        )

        #定义右部分
        self.right = shortcut

    def forward(self, x):
        out = self.left(x)
        residual = x if self.right is None else self.right(x)
        out = out + residual
        return F.relu(out)

class BottleNeckBlock(nn.Module):
    '''
    定义resnet50的瓶颈结构
    '''
    def __init__(self,inchannel,outchannel, pre_channel=None, stride=1,shortcut=None):
        super(BottleNeckBlock, self).__init__()
        #首个bottleneck需要承接上一批blocks的输出channel
        if pre_channel is None:     #为空则表示不是首个bottleneck,
            pre_channel = outchannel    #正常通道转换


        else:   # 传递了pre_channel,表示为首个block,需要shortcut
            shortcut = nn.Sequential(
                nn.Conv2d(pre_channel,outchannel,1,stride,0,bias=False),
                nn.BatchNorm2d(outchannel)
            )

        self.left = nn.Sequential(
            #1*1,inchannel
            nn.Conv2d(pre_channel, inchannel, 1, stride, 0, bias=False),
            nn.BatchNorm2d(inchannel),
            nn.ReLU(inplace=True),
            #3*3,inchannel
            nn.Conv2d(inchannel,inchannel,3,1,1,bias=False),
            nn.BatchNorm2d(inchannel),
            nn.ReLU(inplace=True),
            #1*1,outchannel
            nn.Conv2d(inchannel,outchannel,1,1,0,bias=False),
            nn.BatchNorm2d(outchannel),
            nn.ReLU(inplace=True),
        )
        self.right = shortcut

    def forward(self,x):
        out = self.left(x)
        residual = x if self.right is None else self.right(x)
        return F.relu(out+residual)


if __name__ == '__main__':
    # channel_nums = [64,128,256,512,1024,2048]

    num_classes = 6

    #layers = 18, 34, 50, 101, 152
    layer_nums = [[2,2,2,2],[3,4,6,3],[3,4,6,3],[3,4,23,3],[3,8,36,3]]
    #选择resnet版本,
    # resnet18 ——0;resnet34——1,resnet-50——2,resnet-101——3,resnet-152——4
    i = 3;
    bottleneck = i >= 2   #i<2, false,使用普通的ResidualBlock; i>=2,true,使用BottleNeckBlock

    model = ResNetModel(num_classes,layer_nums[i],bottleneck)
    print(model)

ResNet结构改写

看下图的结构,多模态的数据首先采用ResNet的conv1-11作特征提取,concat后再经过conv12-50,最后是一层全连接:

a-fistful-of-dollars.png◎ ResNet结构改写

  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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def conv3x3(in_planes, out_planes, stride=1):
    "3x3 convolution with padding"
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)

class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out

class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
                               padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes)
        self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm2d(planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out

class ResNetMI(nn.Module):
    def __init__(self, block, layers, num_classes=256):
        super(ResNetMI, self).__init__()
        self.inplanes = 64
        self.inplanes_rgbdnm = 4
        super(ResNetMI, self).__init__()

        self.conv1 = nn.Conv2d(3, 4, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(4)
        self.conv2 = nn.Conv2d(1, 4, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn2 = nn.BatchNorm2d(4)
        self.conv3 = nn.Conv2d(3, 4, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn3 = nn.BatchNorm2d(4)
        self.conv4 = nn.Conv2d(1, 4, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn4 = nn.BatchNorm2d(4)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
      
        self.layer1_color = self._make_layer_rgbdnm(block, 4, layers[0])
        self.layer1_depth = self._make_layer_rgbdnm(block, 4, layers[0])
        self.layer1_normal = self._make_layer_rgbdnm(block, 4, layers[0])
        self.layer1_mask = self._make_layer_rgbdnm(block, 4, layers[0])

        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2)

        self.avgpool = nn.AvgPool2d(7)
        self.fc = nn.Linear(512 * block.expansion, num_classes)

        self.fcms = nn.Linear(1 * num_classes, num_classes)
        self.fcms_gl = nn.Linear(2 * num_classes, num_classes)
        #权重初始化
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

    def _make_layer_rgbdnm(self, block, planes, blocks, stride=1):
        downsample = None
        # 残差块通过1x1卷积提升通道维度
        if stride != 1 or self.inplanes_rgbdnm != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes_rgbdnm, planes * block.expansion,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes_rgbdnm, planes, stride, downsample))
        self.inplanes_rgbdnm = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes_rgbdnm, planes))

        self.inplanes_rgbdnm = 4
        return nn.Sequential(*layers)

    def _make_layer(self, block, planes, blocks, stride=1):
        downsample = None
        #添加大模块首层, 首层需要判断inchannel == outchannel ?
        #跨维度需要stride=2,shortcut也需要1*1卷积扩维
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes * block.expansion,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        return nn.Sequential(*layers)

    def forward(self, x1, x2, x3, x4, x5, x6, x7, x8):
        x2 = x2[:,None, :, :]
        x4 = x4[:,None, :, :]
        x6 = x6[:,None, :, :]
        x8 = x8[:,None, :, :]
        
        # global tower
        # conv1-11
        x1 = self.conv1(x1)
        x1 = self.bn1(x1)
        x1 = self.relu(x1)
        x1 = self.maxpool(x1)
        x1 = self.layer1_color(x1)
        x2 = self.conv2(x2)
        x2 = self.bn2(x2)
        x2 = self.relu(x2)
        x2 = self.maxpool(x2)
        x2 = self.layer1_depth(x2)
        x3 = self.conv3(x3)
        x3 = self.bn3(x3)
        x3 = self.relu(x3)
        x3 = self.maxpool(x3)
        x3 = self.layer1_normal(x3)
        x4 = self.conv4(x4)
        x4 = self.bn4(x4)
        x4 = self.relu(x4)
        x4 = self.maxpool(x4)
        x4 = self.layer1_mask(x4)
        x1 = torch.cat((x1, x2, x3, x4), 1)

        # conv12-50
        x1 = self.layer2(x1)
        x1 = self.layer3(x1)
        x1 = self.layer4(x1)
        x1 = self.avgpool(x1)
        x1 = x1.view(x1.size(0), -1)
        x1 = self.fc(x1)
        xms1 = self.fcms(x1)

        # local tower
        # conv1-11
        x5 = self.conv1(x5)
        x5 = self.bn1(x5)
        x5 = self.relu(x5)
        x5 = self.maxpool(x5)
        x5 = self.layer1_color(x5)
        x6 = self.conv2(x6)
        x6 = self.bn2(x6)
        x6 = self.relu(x6)
        x6 = self.maxpool(x6)
        x6 = self.layer1_depth(x6)
        x7 = self.conv3(x7)
        x7 = self.bn3(x7)
        x7 = self.relu(x7)
        x7 = self.maxpool(x7)
        x7 = self.layer1_normal(x7)
        x8 = self.conv4(x8)
        x8 = self.bn4(x8)
        x8 = self.relu(x8)
        x8 = self.maxpool(x8)
        x8 = self.layer1_mask(x8)
        x5 = torch.cat((x5, x6, x7, x8), 1)

        # conv12-50
        x5 = self.layer2(x5)
        x5 = self.layer3(x5)
        x5 = self.layer4(x5)
        x5 = self.avgpool(x5)
        x5 = x5.view(x5.size(0), -1)
        x5 = self.fc(x5)
        xms2 = self.fcms(x5)

        # concat global & local
        xms = torch.cat((xms1, xms2), 1)
        xms = self.fcms_gl(xms)
        return xms
        
updatedupdated2020-11-062020-11-06