-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathvgg.py
More file actions
222 lines (183 loc) · 6.56 KB
/
Copy pathvgg.py
File metadata and controls
222 lines (183 loc) · 6.56 KB
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
# -*- coding: utf-8 -*-
"""
Modified from https://github.com/pytorch/vision.git
"""
import math
import torch.nn as nn
import torch.nn.functional as F
from .modelBase import ModelBase
class VGG(ModelBase):
"""
VGG model
"""
def __init__(self, parameters: dict, configuration):
"""
Initializer function for the VGG model
Args:
parameters (dict) - overall parameters dictionary; parameters specific for DenseNet:
configuration (dict): A dictionary of configuration parameters for the model.
"""
super(VGG, self).__init__(parameters)
# amp is not supported for vgg
parameters["model"]["amp"] = False
# Setup the feature extractor
self.features = self.make_layers(configuration, self.n_channels)
# Setup the classifier
# Dev Note: number of input features for linear layer should be changed later,
# but works for all vgg right now
self.classifier = nn.Sequential(
nn.Dropout(),
self.GlobalAvgPool(),
nn.ReLU(True),
nn.Dropout(),
nn.Linear(512, self.n_classes),
)
# Initialize weights, if convolutional use He initialization, if linear use Xavier initialization
for m in self.modules():
if isinstance(m, self.Conv):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2.0 / n))
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
nn.init.xavier_uniform_(m.weight)
else:
pass
def forward(self, x):
"""
Forward pass function of the VGG model.
Args:
x (tensor): Input tensor of shape (batch_size, n_channels, height, width).
Returns:
tensor: Output tensor of shape (batch_size, n_classes).
"""
out = self.features(x)
out = self.classifier(out)
if not self.final_convolution_layer is None:
if self.final_convolution_layer == F.softmax:
# Apply softmax activation to the output tensor if specified in the configuration
out = self.final_convolution_layer(out, dim=1)
else:
# Apply whatever final layer specified in the configuration to the output tensor
out = self.final_convolution_layer(out)
return out
def make_layers(self, layer_config, input_channels):
"""
Function to create convolutional layers for the VGG model based on the given layer configuration
for VGG based models including VGG11, VGG13, VGG16, VGG19.
Args:
layer_config (list): A list containing the configuration of convolutional layers and max pooling layers
in_channels (int): The number of input channels
Returns:
nn.Sequential: A sequential module containing the convolutional layers
"""
layers = []
for layer in layer_config:
if layer == "M":
# If you found M, then add a maxpool layer
layers += [self.MaxPool(kernel_size=2, stride=2)]
else:
# Otherwise, add a convolutional layer with the number of channels
conv = self.Conv(input_channels, layer, kernel_size=3, padding=1)
if self.norm_type in ["batch", "instance"]:
layers += [conv, self.Norm(layer), nn.ReLU(inplace=True)]
else:
layers += [conv, nn.ReLU(inplace=True)]
input_channels = layer
return nn.Sequential(*layers)
# Layer configuration for VGG models, as per the paper and M represents maxpool
# and the integers represent the number of channels in the convolutional layers
cfg = {
"A": [64, "M", 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"],
"B": [64, 64, "M", 128, 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"],
"D": [
64,
64,
"M",
128,
128,
"M",
256,
256,
256,
"M",
512,
512,
512,
"M",
512,
512,
512,
"M",
],
"E": [
64,
64,
"M",
128,
128,
"M",
256,
256,
256,
256,
"M",
512,
512,
512,
512,
"M",
512,
512,
512,
512,
"M",
],
}
class vgg11(VGG):
"""
A class representing the VGG11 model, which is a variant of the VGG model architecture.
Inherits from the VGG class and specifies the configuration for the VGG11 architecture.
"""
def __init__(self, parameters):
"""
Initializes the VGG11 model with the given parameters.
Args:
parameters (dict): A dictionary containing the parameters for the VGG11 model.
"""
super(vgg11, self).__init__(parameters=parameters, configuration=cfg["A"])
class vgg13(VGG):
"""
A class representing the VGG13 model, which is a variant of the VGG model architecture.
Inherits from the VGG class and specifies the configuration for the VGG13 architecture.
"""
def __init__(self, parameters):
"""
Initializes the VGG13 model with the given parameters.
Args:
parameters (dict): A dictionary containing the parameters for the VGG13 model.
"""
super(vgg13, self).__init__(parameters=parameters, configuration=cfg["B"])
class vgg16(VGG):
"""
A class representing the VGG16 model, which is a variant of the VGG model architecture.
Inherits from the VGG class and specifies the configuration for the VGG16 architecture.
"""
def __init__(self, parameters):
"""
Initializes the VGG16 model with the given parameters.
Args:
parameters (dict): A dictionary containing the parameters for the VGG16 model.
"""
super(vgg16, self).__init__(parameters=parameters, configuration=cfg["D"])
class vgg19(VGG):
"""
A class representing the VGG19 model, which is a variant of the VGG model architecture.
Inherits from the VGG class and specifies the configuration for the VGG19 architecture.
"""
def __init__(self, parameters):
"""
Initializes the VGG19 model with the given parameters.
Args:
parameters (dict): A dictionary containing the parameters for the VGG19 model.
"""
super(vgg19, self).__init__(parameters=parameters, configuration=cfg["E"])