-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathmnist_models.py
60 lines (51 loc) · 2 KB
/
mnist_models.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
"""ReBias
Copyright (c) 2020-present NAVER Corp.
MIT license
Implementation for simple statcked convolutional networks.
"""
import torch
import torch.nn as nn
class SimpleConvNet(nn.Module):
def __init__(self, num_classes=None, kernel_size=7, feature_pos='post'):
super(SimpleConvNet, self).__init__()
padding = kernel_size // 2
layers = [
nn.Conv2d(3, 16, kernel_size=kernel_size, padding=padding),
nn.BatchNorm2d(16),
nn.ReLU(inplace=True),
nn.Conv2d(16, 32, kernel_size=kernel_size, padding=padding),
nn.BatchNorm2d(32),
nn.ReLU(inplace=True),
nn.Conv2d(32, 64, kernel_size=kernel_size, padding=padding),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.Conv2d(64, 128, kernel_size=kernel_size, padding=padding),
nn.BatchNorm2d(128),
nn.ReLU(inplace=True),
]
self.extracter = nn.Sequential(*layers)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(128, 10)
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.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
if feature_pos not in ['pre', 'post', 'logits']:
raise ValueError(feature_pos)
self.feature_pos = feature_pos
def forward(self, x, logits_only=False):
pre_gap_feats = self.extracter(x)
post_gap_feats = self.avgpool(pre_gap_feats)
post_gap_feats = torch.flatten(post_gap_feats, 1)
logits = self.fc(post_gap_feats)
if logits_only:
return logits
elif self.feature_pos == 'pre':
feats = pre_gap_feats
elif self.feature_pos == 'post':
feats = post_gap_feats
else:
feats = logits
return logits, feats