-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathmodels.py
73 lines (55 loc) · 1.85 KB
/
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
61
62
63
64
65
66
67
68
69
70
71
72
73
import torch.nn as nn
import torch.nn.functional as F
class _Encoder(nn.Module):
def __init__(self, layers):
super(_Encoder, self).__init__()
self.layers = nn.Sequential(*layers)
def forward(self, x):
x = self.layers(x)
x = x.view(x.size(0), -1)
return x
class _Decoder(nn.Module):
def __init__(self, output_size):
super(_Decoder, self).__init__()
self.layers = nn.Sequential(
nn.Linear(128*8*8, 512),
nn.BatchNorm1d(512),
nn.ReLU(),
nn.Linear(512, output_size)
)
def forward(self, x):
x = self.layers(x)
return x
class _Model(nn.Module):
def __init__(self, output_size, encoder):
super(_Model, self).__init__()
self.encoder = encoder
self.decoder = _Decoder(output_size=output_size)
def forward(self, x):
x = self.encoder(x)
x = self.decoder(x)
return x
def Model(num_classes, num_channels):
layers = [
nn.Conv2d(num_channels, 32, kernel_size=3, padding=1),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.Conv2d(32, 64, kernel_size=3, padding=1, stride=2),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Conv2d(64, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Conv2d(64, 128, kernel_size=3, padding=1, stride=2),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=3, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
]
if isinstance(num_classes, list):
encoders = [_Encoder(layers=layers) for _ in num_classes]
return [_Model(output_size=cls, encoder=encoder) for cls, encoder in zip(num_classes, encoders)]
else:
encoder = _Encoder(layers=layers)
return _Model(output_size=num_classes, encoder=encoder)