-
Notifications
You must be signed in to change notification settings - Fork 1
/
densenet.py
258 lines (225 loc) · 9.28 KB
/
densenet.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#!/usr/bin/env python
# type: ignore
"""Implementation of the pre-trained DenseNet architectures using PyTorch and torchvision.
Contains:
- DenseNet121
- DenseNet161
- DenseNet169
- DenseNet201
"""
from types import SimpleNamespace
import torch.nn as nn
from torchvision import models
from torchfl.compatibility import ACTIVATION_FUNCTIONS_BY_NAME
class DenseNet121(models.DenseNet):
"""DenseNet121 base definition."""
def __init__(
self,
pre_trained=True,
feature_extract=True,
num_classes=10,
num_channels=3,
act_fn_name="relu",
**kwargs
) -> None:
"""Constructor
Args:
- pre_trained (bool, optional): Use the model pre-trained on the ImageNet dataset. Defaults to True.
- feature_extract (bool, optional): Only trains the sequential layers of the pre-trained model. If False, the entire model is finetuned. Defaults to True.
- num_classes (int, optional): Number of classification outputs. Defaults to 10.
- num_channels (int, optional): Number of incoming channels. Defaults to 3.
- act_fn_name (str, optional): Activation function to be used. Defaults to "relu". Accepted: ["tanh", "relu", "leakyrelu", "gelu"].
"""
super().__init__(
growth_rate=32, block_config=(6, 12, 24, 16), num_init_features=64
)
self.hparams = SimpleNamespace(
model_name="densenet121",
pre_trained=pre_trained,
feature_extract=bool(pre_trained and feature_extract),
finetune=bool(not feature_extract),
quantized=False,
num_classes=num_classes,
num_channels=num_channels,
act_fn_name=act_fn_name,
act_fn=ACTIVATION_FUNCTIONS_BY_NAME[act_fn_name],
)
if pre_trained:
pretrained_model = models.densenet121(
pretrained=True, progress=True
)
self.load_state_dict(pretrained_model.state_dict())
if feature_extract:
for param in self.parameters():
param.requires_grad = False
if num_channels != 3:
out_channels = self.features[0].out_channels
self.features[0] = nn.Conv2d(
in_channels=num_channels,
out_channels=out_channels,
kernel_size=7,
stride=2,
padding=3,
bias=False,
)
in_features = self.classifier.in_features
self.classifier = nn.Linear(in_features, self.hparams.num_classes)
class DenseNet161(models.DenseNet):
"""DenseNet161 base definition."""
def __init__(
self,
pre_trained=True,
feature_extract=True,
num_classes=10,
num_channels=3,
act_fn_name="relu",
**kwargs
) -> None:
"""Constructor
Args:
- pre_trained (bool, optional): Use the model pre-trained on the ImageNet dataset. Defaults to True.
- feature_extract (bool, optional): Only trains the sequential layers of the pre-trained model. If False, the entire model is finetuned. Defaults to True.
- num_classes (int, optional): Number of classification outputs. Defaults to 10.
- num_channels (int, optional): Number of incoming channels. Defaults to 3.
- act_fn_name (str, optional): Activation function to be used. Defaults to "relu". Accepted: ["tanh", "relu", "leakyrelu", "gelu"].
"""
super().__init__(
growth_rate=48, block_config=(6, 12, 36, 24), num_init_features=96
)
self.hparams = SimpleNamespace(
model_name="densenet161",
pre_trained=pre_trained,
feature_extract=bool(pre_trained and feature_extract),
finetune=bool(not feature_extract),
quantized=False,
num_classes=num_classes,
num_channels=num_channels,
act_fn_name=act_fn_name,
act_fn=ACTIVATION_FUNCTIONS_BY_NAME[act_fn_name],
)
if pre_trained:
pretrained_model = models.densenet161(
pretrained=True, progress=True
)
self.load_state_dict(pretrained_model.state_dict())
if feature_extract:
for param in self.parameters():
param.requires_grad = False
if num_channels != 3:
out_channels = self.features[0].out_channels
self.features[0] = nn.Conv2d(
in_channels=num_channels,
out_channels=out_channels,
kernel_size=7,
stride=2,
padding=3,
bias=False,
)
in_features = self.classifier.in_features
self.classifier = nn.Linear(in_features, self.hparams.num_classes)
class DenseNet169(models.DenseNet):
"""DenseNet169 base definition."""
def __init__(
self,
pre_trained=True,
feature_extract=True,
num_classes=10,
num_channels=3,
act_fn_name="relu",
**kwargs
) -> None:
"""Constructor
Args:
- pre_trained (bool, optional): Use the model pre-trained on the ImageNet dataset. Defaults to True.
- feature_extract (bool, optional): Only trains the sequential layers of the pre-trained model. If False, the entire model is finetuned. Defaults to True.
- num_classes (int, optional): Number of classification outputs. Defaults to 10.
- num_channels (int, optional): Number of incoming channels. Defaults to 3.
- act_fn_name (str, optional): Activation function to be used. Defaults to "relu". Accepted: ["tanh", "relu", "leakyrelu", "gelu"].
"""
super().__init__(
growth_rate=32, block_config=(6, 12, 32, 32), num_init_features=64
)
self.hparams = SimpleNamespace(
model_name="densenet169",
pre_trained=pre_trained,
feature_extract=bool(pre_trained and feature_extract),
finetune=bool(not feature_extract),
quantized=False,
num_classes=num_classes,
num_channels=num_channels,
act_fn_name=act_fn_name,
act_fn=ACTIVATION_FUNCTIONS_BY_NAME[act_fn_name],
)
if pre_trained:
pretrained_model = models.densenet169(
pretrained=True, progress=True
)
self.load_state_dict(pretrained_model.state_dict())
if feature_extract:
for param in self.parameters():
param.requires_grad = False
if num_channels != 3:
out_channels = self.features[0].out_channels
self.features[0] = nn.Conv2d(
in_channels=num_channels,
out_channels=out_channels,
kernel_size=7,
stride=2,
padding=3,
bias=False,
)
in_features = self.classifier.in_features
self.classifier = nn.Linear(in_features, self.hparams.num_classes)
class DenseNet201(models.DenseNet):
"""DenseNet201 base definition."""
def __init__(
self,
pre_trained=True,
feature_extract=True,
num_classes=10,
num_channels=3,
act_fn_name="relu",
**kwargs
) -> None:
"""Constructor
Args:
- pre_trained (bool, optional): Use the model pre-trained on the ImageNet dataset. Defaults to True.
- feature_extract (bool, optional): Only trains the sequential layers of the pre-trained model. If False, the entire model is finetuned. Defaults to True.
- num_classes (int, optional): Number of classification outputs. Defaults to 10.
- num_channels (int, optional): Number of incoming channels. Defaults to 3.
- act_fn_name (str, optional): Activation function to be used. Defaults to "relu". Accepted: ["tanh", "relu", "leakyrelu", "gelu"].
"""
super().__init__(
growth_rate=32, block_config=(6, 12, 48, 32), num_init_features=64
)
self.hparams = SimpleNamespace(
model_name="densenet201",
pre_trained=pre_trained,
feature_extract=bool(pre_trained and feature_extract),
finetune=bool(not feature_extract),
quantized=False,
num_classes=num_classes,
num_channels=num_channels,
act_fn_name=act_fn_name,
act_fn=ACTIVATION_FUNCTIONS_BY_NAME[act_fn_name],
)
if pre_trained:
pretrained_model = models.densenet201(
pretrained=True, progress=True
)
self.load_state_dict(pretrained_model.state_dict())
if feature_extract:
for param in self.parameters():
param.requires_grad = False
if num_channels != 3:
out_channels = self.features[0].out_channels
self.features[0] = nn.Conv2d(
in_channels=num_channels,
out_channels=out_channels,
kernel_size=7,
stride=2,
padding=3,
bias=False,
)
in_features = self.classifier.in_features
self.classifier = nn.Linear(in_features, self.hparams.num_classes)