|
a |
|
b/CellGraph/resnet_custom.py |
|
|
1 |
# modified from Pytorch official resnet.py |
|
|
2 |
# oops |
|
|
3 |
import torch.nn as nn |
|
|
4 |
import torch.utils.model_zoo as model_zoo |
|
|
5 |
import torch |
|
|
6 |
from torchsummary import summary |
|
|
7 |
import torch.nn.functional as F |
|
|
8 |
|
|
|
9 |
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', |
|
|
10 |
'resnet152'] |
|
|
11 |
|
|
|
12 |
|
|
|
13 |
model_urls = { |
|
|
14 |
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', |
|
|
15 |
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', |
|
|
16 |
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', |
|
|
17 |
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', |
|
|
18 |
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', |
|
|
19 |
} |
|
|
20 |
|
|
|
21 |
|
|
|
22 |
def conv3x3(in_planes, out_planes, stride=1): |
|
|
23 |
"""3x3 convolution with padding""" |
|
|
24 |
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, |
|
|
25 |
padding=1, bias=False) |
|
|
26 |
|
|
|
27 |
|
|
|
28 |
class BasicBlock(nn.Module): |
|
|
29 |
expansion = 1 |
|
|
30 |
|
|
|
31 |
def __init__(self, inplanes, planes, stride=1, downsample=None): |
|
|
32 |
super(BasicBlock, self).__init__() |
|
|
33 |
self.conv1 = conv3x3(inplanes, planes, stride) |
|
|
34 |
# self.bn1 = nn.BatchNorm2d(planes) |
|
|
35 |
self.relu = nn.ReLU(inplace=True) |
|
|
36 |
self.conv2 = conv3x3(planes, planes) |
|
|
37 |
# self.bn2 = nn.BatchNorm2d(planes) |
|
|
38 |
self.downsample = downsample |
|
|
39 |
self.stride = stride |
|
|
40 |
|
|
|
41 |
def forward(self, x): |
|
|
42 |
residual = x |
|
|
43 |
|
|
|
44 |
out = self.conv1(x) |
|
|
45 |
# out = self.bn1(out) |
|
|
46 |
out = self.relu(out) |
|
|
47 |
|
|
|
48 |
out = self.conv2(out) |
|
|
49 |
# out = self.bn2(out) |
|
|
50 |
|
|
|
51 |
if self.downsample is not None: |
|
|
52 |
residual = self.downsample(x) |
|
|
53 |
|
|
|
54 |
out += residual |
|
|
55 |
out = self.relu(out) |
|
|
56 |
|
|
|
57 |
return out |
|
|
58 |
|
|
|
59 |
|
|
|
60 |
class Bottleneck(nn.Module): |
|
|
61 |
expansion = 4 |
|
|
62 |
|
|
|
63 |
def __init__(self, inplanes, planes, stride=1, downsample=None): |
|
|
64 |
super(Bottleneck, self).__init__() |
|
|
65 |
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) |
|
|
66 |
# self.bn1 = nn.BatchNorm2d(planes) |
|
|
67 |
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, |
|
|
68 |
padding=1, bias=False) |
|
|
69 |
# self.bn2 = nn.BatchNorm2d(planes) |
|
|
70 |
self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False) |
|
|
71 |
# self.bn3 = nn.BatchNorm2d(planes * self.expansion) |
|
|
72 |
self.relu = nn.ReLU(inplace=True) |
|
|
73 |
self.downsample = downsample |
|
|
74 |
self.stride = stride |
|
|
75 |
|
|
|
76 |
def forward(self, x): |
|
|
77 |
residual = x |
|
|
78 |
|
|
|
79 |
out = self.conv1(x) |
|
|
80 |
# out = self.bn1(out) |
|
|
81 |
out = self.relu(out) |
|
|
82 |
|
|
|
83 |
out = self.conv2(out) |
|
|
84 |
# out = self.bn2(out) |
|
|
85 |
out = self.relu(out) |
|
|
86 |
|
|
|
87 |
out = self.conv3(out) |
|
|
88 |
# out = self.bn3(out) |
|
|
89 |
|
|
|
90 |
if self.downsample is not None: |
|
|
91 |
residual = self.downsample(x) |
|
|
92 |
|
|
|
93 |
out += residual |
|
|
94 |
out = self.relu(out) |
|
|
95 |
|
|
|
96 |
return out |
|
|
97 |
|
|
|
98 |
class LayerNorm(nn.Module): |
|
|
99 |
def __init__(self): |
|
|
100 |
super(LayerNorm, self).__init__() |
|
|
101 |
|
|
|
102 |
def forward(self, x): |
|
|
103 |
return F.layer_norm(x, x.size()[1:]) |
|
|
104 |
|
|
|
105 |
class Bottleneck_LN(nn.Module): |
|
|
106 |
expansion = 4 |
|
|
107 |
|
|
|
108 |
def __init__(self, inplanes, planes, stride=1, downsample=None): |
|
|
109 |
super(Bottleneck_LN, self).__init__() |
|
|
110 |
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) |
|
|
111 |
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, |
|
|
112 |
padding=1, bias=False) |
|
|
113 |
self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False) |
|
|
114 |
self.relu = nn.ReLU(inplace=True) |
|
|
115 |
self.ln = LayerNorm() |
|
|
116 |
self.downsample = downsample |
|
|
117 |
self.stride = stride |
|
|
118 |
|
|
|
119 |
def forward(self, x): |
|
|
120 |
residual = x |
|
|
121 |
|
|
|
122 |
out = self.conv1(x) |
|
|
123 |
# out = F.layer_norm(out, out.size()[1:]) |
|
|
124 |
out = self.ln(out) |
|
|
125 |
out = self.relu(out) |
|
|
126 |
|
|
|
127 |
out = self.conv2(out) |
|
|
128 |
# out = F.layer_norm(out, out.size()[1:]) |
|
|
129 |
out = self.ln(out) |
|
|
130 |
out = self.relu(out) |
|
|
131 |
|
|
|
132 |
out = self.conv3(out) |
|
|
133 |
# out = F.layer_norm(out, out.size()[1:]) |
|
|
134 |
out = self.ln(out) |
|
|
135 |
|
|
|
136 |
if self.downsample is not None: |
|
|
137 |
residual = self.downsample(x) |
|
|
138 |
# residual = F.layer_norm(residual, residual.size()[1:]) |
|
|
139 |
residual = self.ln(residual) |
|
|
140 |
|
|
|
141 |
out += residual |
|
|
142 |
out = self.relu(out) |
|
|
143 |
|
|
|
144 |
return out |
|
|
145 |
|
|
|
146 |
|
|
|
147 |
class ResNet(nn.Module): |
|
|
148 |
|
|
|
149 |
def __init__(self, block, layers |
|
|
150 |
# num_classes=1000 |
|
|
151 |
): |
|
|
152 |
self.inplanes = 64 |
|
|
153 |
super(ResNet, self).__init__() |
|
|
154 |
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, |
|
|
155 |
bias=False) |
|
|
156 |
# self.bn1 = nn.BatchNorm2d(64) |
|
|
157 |
self.relu = nn.ReLU(inplace=True) |
|
|
158 |
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) |
|
|
159 |
self.layer1 = self._make_layer(block, 64, layers[0]) |
|
|
160 |
self.layer2 = self._make_layer(block, 128, layers[1], stride=2) |
|
|
161 |
self.layer3 = self._make_layer(block, 256, layers[2], stride=2) |
|
|
162 |
# self.layer4 = self._make_layer(block, 512, layers[3], stride=2) |
|
|
163 |
self.avgpool = nn.AdaptiveAvgPool2d(1) # was 7, if have layer4 |
|
|
164 |
# remove the final fc |
|
|
165 |
# self.fc = nn.Linear(512 * block.expansion, num_classes) |
|
|
166 |
|
|
|
167 |
for m in self.modules(): |
|
|
168 |
if isinstance(m, nn.Conv2d): |
|
|
169 |
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') |
|
|
170 |
elif isinstance(m, nn.BatchNorm2d): |
|
|
171 |
nn.init.constant_(m.weight, 1) |
|
|
172 |
nn.init.constant_(m.bias, 0) |
|
|
173 |
|
|
|
174 |
def _make_layer(self, block, planes, blocks, stride=1): |
|
|
175 |
downsample = None |
|
|
176 |
if stride != 1 or self.inplanes != planes * block.expansion: |
|
|
177 |
downsample = nn.Sequential( |
|
|
178 |
nn.Conv2d(self.inplanes, planes * block.expansion, |
|
|
179 |
kernel_size=1, stride=stride, bias=False), |
|
|
180 |
# nn.BatchNorm2d(planes * block.expansion), |
|
|
181 |
) |
|
|
182 |
|
|
|
183 |
layers = [] |
|
|
184 |
layers.append(block(self.inplanes, planes, stride, downsample)) |
|
|
185 |
self.inplanes = planes * block.expansion |
|
|
186 |
for i in range(1, blocks): |
|
|
187 |
layers.append(block(self.inplanes, planes)) |
|
|
188 |
|
|
|
189 |
return nn.Sequential(*layers) |
|
|
190 |
|
|
|
191 |
def forward(self, x): |
|
|
192 |
x = self.conv1(x) |
|
|
193 |
# x = self.bn1(x) |
|
|
194 |
x = self.relu(x) |
|
|
195 |
x = self.maxpool(x) |
|
|
196 |
|
|
|
197 |
x = self.layer1(x) |
|
|
198 |
x = self.layer2(x) |
|
|
199 |
x = self.layer3(x) |
|
|
200 |
# x = self.layer4(x) |
|
|
201 |
|
|
|
202 |
x = self.avgpool(x) |
|
|
203 |
x = x.view(x.size(0), -1) |
|
|
204 |
# x = self.fc(x) |
|
|
205 |
|
|
|
206 |
return x |
|
|
207 |
|
|
|
208 |
|
|
|
209 |
def resnet18(pretrained=False, **kwargs): |
|
|
210 |
"""Constructs a ResNet-18 model. |
|
|
211 |
Args: |
|
|
212 |
pretrained (bool): If True, returns a model pre-trained on ImageNet |
|
|
213 |
""" |
|
|
214 |
model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) |
|
|
215 |
if pretrained: |
|
|
216 |
model = neq_load(model, 'resnet18') |
|
|
217 |
# model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) |
|
|
218 |
return model |
|
|
219 |
|
|
|
220 |
|
|
|
221 |
def resnet34(pretrained=False, **kwargs): |
|
|
222 |
"""Constructs a ResNet-34 model. |
|
|
223 |
Args: |
|
|
224 |
pretrained (bool): If True, returns a model pre-trained on ImageNet |
|
|
225 |
""" |
|
|
226 |
model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs) |
|
|
227 |
if pretrained: |
|
|
228 |
model = neq_load(model, 'resnet34') |
|
|
229 |
# model.load_state_dict(model_zoo.load_url(model_urls['resnet34'])) |
|
|
230 |
return model |
|
|
231 |
|
|
|
232 |
|
|
|
233 |
def resnet50(pretrained=False, **kwargs): |
|
|
234 |
"""Constructs a ResNet-50 model. |
|
|
235 |
Args: |
|
|
236 |
pretrained (bool): If True, returns a model pre-trained on ImageNet |
|
|
237 |
""" |
|
|
238 |
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) |
|
|
239 |
if pretrained: |
|
|
240 |
model = neq_load(model, 'resnet50') |
|
|
241 |
# model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) |
|
|
242 |
return model |
|
|
243 |
|
|
|
244 |
def resnet50_ln(pretrained=False): |
|
|
245 |
"""Constructs a ResNet-50 model. |
|
|
246 |
Args: |
|
|
247 |
pretrained (bool): If True, returns a model pre-trained on ImageNet |
|
|
248 |
""" |
|
|
249 |
model = ResNet(Bottleneck_LN, [3, 4, 6, 3], **kwargs) |
|
|
250 |
|
|
|
251 |
if pretrained: |
|
|
252 |
model = neq_load(model, 'resnet50') |
|
|
253 |
# model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) |
|
|
254 |
return model |
|
|
255 |
|
|
|
256 |
|
|
|
257 |
def resnet101(pretrained=False, **kwargs): |
|
|
258 |
"""Constructs a ResNet-101 model. |
|
|
259 |
Args: |
|
|
260 |
pretrained (bool): If True, returns a model pre-trained on ImageNet |
|
|
261 |
""" |
|
|
262 |
model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) |
|
|
263 |
if pretrained: |
|
|
264 |
model = neq_load(model, 'resnet101') |
|
|
265 |
# model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) |
|
|
266 |
return model |
|
|
267 |
|
|
|
268 |
def resnet101_wide(pretrained=False, ln=False): |
|
|
269 |
"""Constructs a ResNet-101 model. |
|
|
270 |
Args: |
|
|
271 |
pretrained (bool): If True, returns a model pre-trained on ImageNet |
|
|
272 |
""" |
|
|
273 |
if ln: |
|
|
274 |
model = ResNet_Wide_LN(Bottleneck_LN, Bottleneck_Wide_LN, [3, 4, 46, 3]) |
|
|
275 |
else: |
|
|
276 |
model = ResNet_Wide(Bottleneck, Bottleneck_Wide, [3, 4, 46, 3]) |
|
|
277 |
|
|
|
278 |
if pretrained: |
|
|
279 |
model = neq_load(model, 'resnet101') |
|
|
280 |
# model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) |
|
|
281 |
return model |
|
|
282 |
|
|
|
283 |
|
|
|
284 |
def resnet152(pretrained=False, **kwargs): |
|
|
285 |
"""Constructs a ResNet-152 model. |
|
|
286 |
Args: |
|
|
287 |
pretrained (bool): If True, returns a model pre-trained on ImageNet |
|
|
288 |
""" |
|
|
289 |
model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs) |
|
|
290 |
if pretrained: |
|
|
291 |
model = neq_load(model, 'resnet152') |
|
|
292 |
# model.load_state_dict(model_zoo.load_url(model_urls['resnet152'])) |
|
|
293 |
return model |
|
|
294 |
|
|
|
295 |
|
|
|
296 |
def neq_load(model, name): |
|
|
297 |
# load pre-trained model in a not-equal way |
|
|
298 |
# when new model has been modified |
|
|
299 |
pretrained_dict = model_zoo.load_url(model_urls[name]) |
|
|
300 |
model_dict = model.state_dict() |
|
|
301 |
pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict} |
|
|
302 |
model_dict.update(pretrained_dict) |
|
|
303 |
model.load_state_dict(model_dict) |
|
|
304 |
return model |
|
|
305 |
|
|
|
306 |
if __name__ == '__main__': |
|
|
307 |
# model = resnet50_wide(pretrained = False) |
|
|
308 |
model = resnet50_wide(ln=True) |
|
|
309 |
print(model) |
|
|
310 |
# summary(model, (3,64,64)) |
|
|
311 |
x = torch.rand(49, 3, 64, 64) |
|
|
312 |
x = model(x).squeeze() |
|
|
313 |
print(x.shape) |
|
|
314 |
print(len(x.shape)) |
|
|
315 |
|
|
|
316 |
|