-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresnet.py
251 lines (204 loc) · 9.08 KB
/
resnet.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
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import torch
import torch.nn as nn
# 分类数目
num_class = 5
# 各层数目
resnet18_params = [2, 2, 2, 2]
resnet34_params = [3, 4, 6, 3]
resnet50_params = [3, 4, 6, 3]
resnet101_params = [3, 4, 23, 3]
resnet152_params = [3, 8, 36, 3]
# 定义Conv1层
def Conv1(in_planes, places, stride=2):
return nn.Sequential(
nn.Conv2d(in_channels=in_planes,out_channels=places,kernel_size=7,stride=stride,padding=3, bias=False),
nn.BatchNorm2d(places),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
)
# 浅层的残差结构
class BasicBlock(nn.Module):
def __init__(self,in_places,places, stride=1,downsampling=False, expansion = 1):
super(BasicBlock,self).__init__()
self.expansion = expansion
self.downsampling = downsampling
# torch.Size([1, 64, 56, 56]), stride = 1
# torch.Size([1, 128, 28, 28]), stride = 2
# torch.Size([1, 256, 14, 14]), stride = 2
# torch.Size([1, 512, 7, 7]), stride = 2
self.basicblock = nn.Sequential(
nn.Conv2d(in_channels=in_places, out_channels=places, kernel_size=3, stride=stride, padding=1, bias=False),
nn.BatchNorm2d(places),
nn.ReLU(inplace=True),
nn.Conv2d(in_channels=places, out_channels=places, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(places * self.expansion),
)
# torch.Size([1, 64, 56, 56])
# torch.Size([1, 128, 28, 28])
# torch.Size([1, 256, 14, 14])
# torch.Size([1, 512, 7, 7])
# 每个大模块的第一个残差结构需要改变步长
if self.downsampling:
self.downsample = nn.Sequential(
nn.Conv2d(in_channels=in_places, out_channels=places*self.expansion, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(places*self.expansion)
)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
# 实线分支
residual = x
out = self.basicblock(x)
# 虚线分支
if self.downsampling:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
# 深层的残差结构
class Bottleneck(nn.Module):
# 注意:默认 downsampling=False
def __init__(self,in_places,places, stride=1,downsampling=False, expansion = 4):
super(Bottleneck,self).__init__()
self.expansion = expansion
self.downsampling = downsampling
self.bottleneck = nn.Sequential(
# torch.Size([1, 64, 56, 56]),stride=1
# torch.Size([1, 128, 56, 56]),stride=1
# torch.Size([1, 256, 28, 28]), stride=1
# torch.Size([1, 512, 14, 14]), stride=1
nn.Conv2d(in_channels=in_places,out_channels=places,kernel_size=1,stride=1, bias=False),
nn.BatchNorm2d(places),
nn.ReLU(inplace=True),
# torch.Size([1, 64, 56, 56]),stride=1
# torch.Size([1, 128, 28, 28]), stride=2
# torch.Size([1, 256, 14, 14]), stride=2
# torch.Size([1, 512, 7, 7]), stride=2
nn.Conv2d(in_channels=places, out_channels=places, kernel_size=3, stride=stride, padding=1, bias=False),
nn.BatchNorm2d(places),
nn.ReLU(inplace=True),
# torch.Size([1, 256, 56, 56]),stride=1
# torch.Size([1, 512, 28, 28]), stride=1
# torch.Size([1, 1024, 14, 14]), stride=1
# torch.Size([1, 2048, 7, 7]), stride=1
nn.Conv2d(in_channels=places, out_channels=places * self.expansion, kernel_size=1, stride=1, bias=False),
nn.BatchNorm2d(places * self.expansion),
)
# torch.Size([1, 256, 56, 56])
# torch.Size([1, 512, 28, 28])
# torch.Size([1, 1024, 14, 14])
# torch.Size([1, 2048, 7, 7])
if self.downsampling:
self.downsample = nn.Sequential(
nn.Conv2d(in_channels=in_places, out_channels=places*self.expansion, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(places*self.expansion)
)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
# 实线分支
residual = x
out = self.bottleneck(x)
# 虚线分支
if self.downsampling:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self,blocks, blockkinds, num_classes=num_class):
super(ResNet,self).__init__()
self.blockkinds = blockkinds
self.conv1 = Conv1(in_planes = 16, places= 64)
# 对应浅层网络结构
if self.blockkinds == BasicBlock:
self.expansion = 1
# 64 -> 64
self.layer1 = self.make_layer(in_places=64, places=64, block=blocks[0], stride=1)
# 64 -> 128
self.layer2 = self.make_layer(in_places=64, places=128, block=blocks[1], stride=2)
# 128 -> 256
self.layer3 = self.make_layer(in_places=128, places=256, block=blocks[2], stride=2)
# 256 -> 512
self.layer4 = self.make_layer(in_places=256, places=512, block=blocks[3], stride=2)
self.fc = nn.Linear(512, num_classes)
# 对应深层网络结构
if self.blockkinds == Bottleneck:
self.expansion = 4
# 64 -> 64
self.layer1 = self.make_layer(in_places = 64, places= 64, block=blocks[0], stride=1)
# 256 -> 128
self.layer2 = self.make_layer(in_places = 256,places=128, block=blocks[1], stride=2)
# 512 -> 256
self.layer3 = self.make_layer(in_places=512,places=256, block=blocks[2], stride=2)
# 1024 -> 512
self.layer4 = self.make_layer(in_places=1024,places=512, block=blocks[3], stride=2)
self.fc = nn.Linear(2048, num_classes)
self.avgpool = nn.AvgPool2d(7, stride=1)
# 初始化网络结构
for m in self.modules():
if isinstance(m, nn.Conv2d):
# 采用了何凯明的初始化方法
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def make_layer(self, in_places, places, block, stride):
layers = []
# torch.Size([1, 64, 56, 56]) -> torch.Size([1, 256, 56, 56]), stride=1 故w,h不变
# torch.Size([1, 256, 56, 56]) -> torch.Size([1, 512, 28, 28]), stride=2 故w,h变
# torch.Size([1, 512, 28, 28]) -> torch.Size([1, 1024, 14, 14]),stride=2 故w,h变
# torch.Size([1, 1024, 14, 14]) -> torch.Size([1, 2048, 7, 7]), stride=2 故w,h变
# 此步需要通过虚线分支,downsampling=True
layers.append(self.blockkinds(in_places, places, stride, downsampling =True))
# torch.Size([1, 256, 56, 56]) -> torch.Size([1, 256, 56, 56])
# torch.Size([1, 512, 28, 28]) -> torch.Size([1, 512, 28, 28])
# torch.Size([1, 1024, 14, 14]) -> torch.Size([1, 1024, 14, 14])
# torch.Size([1, 2048, 7, 7]) -> torch.Size([1, 2048, 7, 7])
# print("places*self.expansion:", places*self.expansion)
# print("block:", block)
# 此步需要通过实线分支,downsampling=False, 每个大模块的第一个残差结构需要改变步长
for i in range(1, block):
layers.append(self.blockkinds(places*self.expansion, places))
return nn.Sequential(*layers)
def forward(self, x):
# conv1层
x = self.conv1(x) # torch.Size([1, 64, 56, 56])
# print(x.shape)
# x = self.conv2(x)
# print(x.shape)
# conv2_x层
x = self.layer1(x) # torch.Size([1, 256, 56, 56])
# conv3_x层
x = self.layer2(x) # torch.Size([1, 512, 28, 28])
# conv4_x层
x = self.layer3(x) # torch.Size([1, 1024, 14, 14])
# conv5_x层
x = self.layer4(x) # torch.Size([1, 2048, 7, 7])
x = self.avgpool(x) # torch.Size([1, 2048, 1, 1]) / torch.Size([1, 512])
# print(x.shape)
x = x.view(x.size(0), -1) # torch.Size([1, 2048]) / torch.Size([1, 512])
# print(x.shape[-1])
x = self.fc(x) # torch.Size([1, 5])
return x
def ResNet18():
return ResNet(resnet18_params, BasicBlock, num_classes= 128)
def ResNet34(num_classes=256):
return ResNet(resnet34_params, BasicBlock, num_classes= num_classes)
def ResNet50():
return ResNet(resnet50_params, Bottleneck, num_classes= 128)
def ResNet101():
return ResNet(resnet101_params, Bottleneck, num_classes= 128)
def ResNet152():
return ResNet(resnet152_params, Bottleneck, num_classes= 128)
if __name__=='__main__':
# model = torchvision.models.resnet50()
# 模型测试
model = ResNet18()
# model = ResNet34()
# model = ResNet50()
# model = ResNet101()
# model = ResNet152()
# print(model)
input = torch.randn(1, 1, 800, 400)
# input = torch.randn(1, 1, 224, 224)
out = model(input)
print(out.shape)