-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
188 lines (160 loc) · 7.38 KB
/
model.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
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from loguru import logger
class CNN(nn.Module):
def __init__(self, in_channels=1, num_classes=10, img_size: int = 28, init_weights=True):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(in_channels, 64, kernel_size=3, stride=1, padding=1)
self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)
self.fc1 = nn.Linear(64 * (img_size // 4) * (img_size // 4), 64)
self.fc2 = nn.Linear(64, num_classes)
self.img_size = img_size
if init_weights:
self._initialize_weights()
def _initialize_weights(self, init_type="kaiming"):
logger.info("initialize weights with {}".format(init_type))
if init_type == "kaiming":
for module in self.modules():
if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):
nn.init.kaiming_normal_(module.weight)
if module.bias is not None:
nn.init.zeros_(module.bias)
elif init_type == "zeros":
for module in self.modules():
if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):
nn.init.zeros_(module.weight)
if module.bias is not None:
nn.init.zeros_(module.bias)
else:
raise ValueError("unknown init type: {}".format(init_type))
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2(x), 2))
x = x.view(-1, 64 * (self.img_size // 4) * (self.img_size // 4))
x = F.relu(self.fc1(x))
x = self.fc2(x)
return F.log_softmax(x, dim=1)
class CNN4(nn.Module):
def __init__(self, in_channels=1, num_classes=10, img_size: int = 28, init_weights=True):
super(CNN4, self).__init__()
self.conv1 = nn.Conv2d(in_channels, 64, kernel_size=3, stride=1, padding=1)
self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)
self.dropout1 = nn.Dropout2d(0.25)
self.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
self.conv4 = nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1)
self.dropout2 = nn.Dropout2d(0.25)
self.fc1 = nn.Linear(128 * (img_size // 4) * (img_size // 4), 512)
self.dropout3 = nn.Dropout2d(0.25)
self.fc2 = nn.Linear(512, num_classes)
self.img_size = img_size
if init_weights:
self._initialize_weights()
def _initialize_weights(self, init_type="kaiming"):
logger.info("initialize weights with {}".format(init_type))
if init_type == "kaiming":
for module in self.modules():
if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):
nn.init.kaiming_normal_(module.weight)
if module.bias is not None:
nn.init.zeros_(module.bias)
elif init_type == "zeros":
for module in self.modules():
if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):
nn.init.zeros_(module.weight)
if module.bias is not None:
nn.init.zeros_(module.bias)
else:
raise ValueError("unknown init type: {}".format(init_type))
def forward(self, x):
# 4 conv layers + 2 max pool
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = F.relu(self.conv3(x))
x = F.relu(self.conv4(x))
x = F.max_pool2d(x, 2)
x = self.dropout2(x)
x = x.view(-1, 128 * (self.img_size // 4) * (self.img_size // 4))
x = F.relu(self.fc1(x))
x = self.dropout3(x)
x = self.fc2(x)
return F.log_softmax(x, dim=1)
class ResNet18(nn.Module):
def __init__(self, in_channels=3, num_classes=10, img_size: int = 32, init_weights=True, pretrained=False, **kwargs):
super(ResNet18, self).__init__()
self.resnet18 = torchvision.models.resnet18(pretrained=pretrained)
self.resnet18.conv1 = nn.Conv2d(
in_channels, 64, kernel_size=7, stride=2, padding=3, bias=False
)
self.resnet18.fc = nn.Linear(512, num_classes)
self.img_size = img_size
if init_weights:
self._initialize_weights()
def _initialize_weights(self, init_type="kaiming"):
logger.info("initialize weights with {}".format(init_type))
if init_type == "kaiming":
for module in self.modules():
if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):
nn.init.kaiming_normal_(module.weight)
if module.bias is not None:
nn.init.zeros_(module.bias)
elif init_type == "zeros":
for module in self.modules():
if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):
nn.init.zeros_(module.weight)
if module.bias is not None:
nn.init.zeros_(module.bias)
else:
raise ValueError("unknown init type: {}".format(init_type))
def forward(self, x):
x = self.resnet18(x)
return F.log_softmax(x, dim=1)
def get_model(model_name, **kwargs):
if model_name == "cnn":
return CNN(**kwargs)
elif model_name == "cnn4":
return CNN4(**kwargs)
elif model_name == "resnet18":
return ResNet18(**kwargs)
else:
raise ValueError("Unknown model name: {}".format(model_name))
def build_optimizer(optimizer_name, model_params, optimizer_hyperparams):
if optimizer_name == "sgd":
return torch.optim.SGD(
model_params,
lr=optimizer_hyperparams["lr"],
momentum=optimizer_hyperparams["momentum"],
)
elif optimizer_name == "adam":
return torch.optim.Adam(model_params, lr=optimizer_hyperparams["lr"])
else:
raise ValueError("Unknown optimizer name: {}".format(optimizer_name))
def build_lr_scheduler(lr_scheduler_name, optimizer, lr_scheduler_hyperparams):
if lr_scheduler_name == "step_lr":
return torch.optim.lr_scheduler.StepLR(
optimizer,
step_size=lr_scheduler_hyperparams["step_size"],
gamma=lr_scheduler_hyperparams["gamma"],
)
elif lr_scheduler_name == "multi_step_lr":
return torch.optim.lr_scheduler.MultiStepLR(
optimizer,
milestones=lr_scheduler_hyperparams["milestones"],
gamma=lr_scheduler_hyperparams["gamma"],
)
elif lr_scheduler_name == "exponential_lr":
return torch.optim.lr_scheduler.ExponentialLR(
optimizer, gamma=lr_scheduler_hyperparams["gamma"]
)
else:
raise ValueError("Unknown lr scheduler name: {}".format(lr_scheduler_name))
def build_loss_function(loss_function_name):
if loss_function_name == "nll_loss":
return torch.nn.NLLLoss()
elif loss_function_name == "cross_entropy":
return torch.nn.CrossEntropyLoss()
else:
raise ValueError("Unknown loss function name: {}".format(loss_function_name))