-
Notifications
You must be signed in to change notification settings - Fork 0
/
resnet.py
304 lines (223 loc) · 8.11 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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import numpy as np
import torch
from torch import nn
class BasicBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride=1) -> None:
super().__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1)
self.bn1 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU()
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.bn2 = nn.BatchNorm2d(out_channels)
self.downsample = None
if stride != 1 or in_channels != out_channels:
self.downsample = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, padding=0),
nn.BatchNorm2d(out_channels)
)
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):
def __init__(self, in_channels, out_channels, stride=1) -> None:
super().__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels//4, kernel_size=1, stride=stride, padding=0)
self.bn1 = nn.BatchNorm2d(out_channels//4)
self.relu = nn.ReLU()
self.conv2 = nn.Conv2d(out_channels//4, out_channels//4, kernel_size=3, stride=1, padding=1)
self.bn2 = nn.BatchNorm2d(out_channels//4)
self.conv3 = nn.Conv2d(out_channels//4, out_channels, kernel_size=1, stride=1, padding=0)
self.bn3 = nn.BatchNorm2d(out_channels)
self.downsample = None
if stride != 1 or in_channels != out_channels:
self.downsample = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, padding=0),
nn.BatchNorm2d(out_channels)
)
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 ResNet(nn.Module):
def __init__(self, block_type, layers, large_mode=False) -> None:
super().__init__()
self.block_type = block_type
# Initial convolutional layer
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3)
# Batch normalization after the initial convolutional layer
self.bn1 = nn.BatchNorm2d(64)
# Max pooling after the batch normalization layer
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
# Output channels
if large_mode:
output_channels = [256, 512, 1024, 2048]
else:
output_channels = [64, 128, 256, 512]
# ResNet layers
self.layer1 = self.make_layer(64, output_channels[0], layers[0])
self.layer2 = self.make_layer(output_channels[0], output_channels[1], layers[1])
self.layer3 = self.make_layer(output_channels[1], output_channels[2], layers[2])
self.layer4 = self.make_layer(output_channels[2], output_channels[3], layers[3])
# Prediction head
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
if large_mode:
self.fc = nn.Linear(2048, 100)
else:
self.fc = nn.Linear(512, 100)
self.softmax = nn.Softmax(dim=-1)
def forward(self, x):
# Initial convolutional layer
out = self.conv1(x)
out = self.bn1(out)
out = self.maxpool(out)
# ResNet layers
out = self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = self.layer4(out)
# Prediction head
out = self.avgpool(out)
out = torch.flatten(out, 1)
out = self.fc(out)
out = self.softmax(out)
# Return learned features
return out
def make_layer(self, in_channels, out_channels, num_blocks):
blocks = []
# Create the first block separately to perform downsampling
if in_channels != out_channels:
blocks.append(self.block_type(in_channels, out_channels, stride=2))
else:
blocks.append(self.block_type(in_channels, out_channels, stride=1))
# Create the rest of the blocks
for i in range(1, num_blocks):
blocks.append(self.block_type(out_channels, out_channels, stride=1))
return nn.Sequential(*blocks)
# Plain ResNets
def resnet18():
return ResNet(BasicBlock, [2, 2, 2, 2])
def resnet34():
return ResNet(BasicBlock, [3, 4, 6, 3])
def resnet50():
return ResNet(BasicBlock, [3, 4, 6, 3])
def resnet101():
return ResNet(BasicBlock, [3, 4, 23, 3])
def resnet152():
return ResNet(BasicBlock, [3, 8, 36, 3])
# ResNets with bottleneck blocks
def resnet18_bottleneck():
return ResNet(Bottleneck, [2, 2, 2, 2])
def resnet34_bottleneck():
return ResNet(Bottleneck, [3, 4, 6, 3])
def resnet50_bottleneck(large_mode=False):
return ResNet(Bottleneck, [3, 4, 6, 3], large_mode=large_mode)
def resnet101_bottleneck(large_mode=False):
return ResNet(Bottleneck, [3, 4, 23, 3], large_mode=large_mode)
def resnet152_bottleneck(large_mode=False):
return ResNet(Bottleneck, [3, 8, 36, 3], large_mode=large_mode)
# Test the network
def test_plain_resnet_models_forward():
net = resnet18()
x = torch.randn(2, 3, 224, 224)
y = net(x)
print(f'ResNet18 network = {net}')
net = resnet34()
y = net(x)
print(f'ResNet34 network = {net}')
net = resnet50()
y = net(x)
print(f'ResNet50 network = {net}')
net = resnet101()
y = net(x)
print(f'ResNet101 network = {net}')
net = resnet152()
y = net(x)
print(f'ResNet152 network = {net}')
def test_bottleneck_resnet_models_forward():
net = resnet18_bottleneck()
x = torch.randn(2, 3, 224, 224)
y = net(x)
print(f'ResNet18 network = {net}')
net = resnet34_bottleneck()
y = net(x)
print(f'ResNet34 network = {net}')
net = resnet50_bottleneck()
y = net(x)
print(f'ResNet50 network = {net}')
net = resnet101_bottleneck()
y = net(x)
print(f'ResNet101 network = {net}')
net = resnet152_bottleneck()
y = net(x)
print(f'ResNet152 network = {net}')
def test_plain_resnet_models_shapes():
net = resnet18()
x = torch.randn(2, 3, 224, 224)
y = net(x)
print(f'ResNet18 shapes = {y.shape}')
assert y.shape == (2, 1000)
net = resnet34()
y = net(x)
print(f'ResNet34 shapes = {y.shape}')
assert y.shape == (2, 1000)
net = resnet50()
y = net(x)
print(f'ResNet50 shapes = {y.shape}')
assert y.shape == (2, 1000)
net = resnet101()
y = net(x)
print(f'ResNet101 shapes = {y.shape}')
assert y.shape == (2, 1000)
net = resnet152()
y = net(x)
print(f'ResNet152 shapes = {y.shape}')
assert y.shape == (2, 1000)
def test_bottleneck_resnet_models_shapes():
net = resnet18_bottleneck()
x = torch.randn(2, 3, 224, 224)
y = net(x)
print(f'ResNet18 shapes = {y.shape}')
assert y.shape == (2, 1000)
net = resnet34_bottleneck()
y = net(x)
print(f'ResNet34 shapes = {y.shape}')
assert y.shape == (2, 1000)
net = resnet50_bottleneck()
y = net(x)
print(f'ResNet50 shapes = {y.shape}')
assert y.shape == (2, 1000)
net = resnet101_bottleneck()
y = net(x)
print(f'ResNet101 shapes = {y.shape}')
assert y.shape == (2, 1000)
net = resnet152_bottleneck()
y = net(x)
print(f'ResNet152 shapes = {y.shape}')
assert y.shape == (2, 1000)
def main():
test_plain_resnet_models_forward()
test_bottleneck_resnet_models_forward()
test_plain_resnet_models_shapes()
test_bottleneck_resnet_models_shapes()
if __name__ == '__main__':
main()