-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
88 lines (74 loc) · 2.42 KB
/
utils.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
import torch
import logging
logger = logging.getLogger(__name__)
class Vgg2D(torch.nn.Module):
def __init__(
self,
input_size,
fmaps=32,
downsample_factors=[(2, 2), (2, 2), (2, 2), (2, 2)],
output_classes=6,
input_fmaps=1):
super(Vgg2D, self).__init__()
current_fmaps = input_fmaps
current_size = tuple(input_size)
features = []
for i in range(len(downsample_factors)):
features += [
torch.nn.Conv2d(
current_fmaps,
fmaps,
kernel_size=3,
padding=1),
torch.nn.BatchNorm2d(fmaps),
torch.nn.ReLU(inplace=False),
torch.nn.Conv2d(
fmaps,
fmaps,
kernel_size=3,
padding=1),
torch.nn.BatchNorm2d(fmaps),
torch.nn.ReLU(inplace=False),
torch.nn.MaxPool2d(downsample_factors[i])
]
current_fmaps = fmaps
fmaps *= 2
size = tuple(
int(c/d)
for c, d in zip(current_size, downsample_factors[i]))
check = (
s*d == c
for s, d, c in zip(size, downsample_factors[i], current_size))
assert all(check), \
"Can not downsample %s by chosen downsample factor" % \
(current_size,)
current_size = size
logger.info(
"VGG level %d: (%s), %d fmaps",
i,
current_size,
current_fmaps)
self.features = torch.nn.Sequential(*features)
classifier = [
torch.nn.Linear(
current_size[0] *
current_size[1] *
current_fmaps,
4096),
torch.nn.ReLU(inplace=False),
torch.nn.Dropout(),
torch.nn.Linear(
4096,
4096),
torch.nn.ReLU(inplace=False),
torch.nn.Dropout(),
torch.nn.Linear(
4096,
output_classes)
]
self.classifier = torch.nn.Sequential(*classifier)
def forward(self, raw):
f = self.features(raw)
f = torch.reshape(f, (f.size(0), -1))
y = self.classifier(f)
return y