Skip to content

Commit ca4163c

Browse files
authored
Added VGG implementation (#2)
1 parent 718ad58 commit ca4163c

File tree

1 file changed

+134
-0
lines changed

1 file changed

+134
-0
lines changed

CNNs/vgg.py

+134
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
"""
2+
VGG Implementation in PyTorch
3+
4+
Paper Link: https://arxiv.org/pdf/1409.1556.pdf
5+
"""
6+
7+
import torch
8+
import torch.nn as nn
9+
from torch.autograd import Variable
10+
11+
12+
model_configs = {
13+
"VGG11": [
14+
64,
15+
"pooling",
16+
128,
17+
"pooling",
18+
256,
19+
256,
20+
"pooling",
21+
512,
22+
512,
23+
"pooling",
24+
512,
25+
512,
26+
"pooling",
27+
],
28+
"VGG13": [
29+
64,
30+
64,
31+
"pooling",
32+
128,
33+
128,
34+
"pooling",
35+
256,
36+
256,
37+
"pooling",
38+
512,
39+
512,
40+
"pooling",
41+
512,
42+
512,
43+
"pooling",
44+
],
45+
"VGG16": [
46+
64,
47+
64,
48+
"pooling",
49+
128,
50+
128,
51+
"pooling",
52+
256,
53+
256,
54+
256,
55+
"pooling",
56+
512,
57+
512,
58+
512,
59+
"pooling",
60+
512,
61+
512,
62+
512,
63+
"pooling",
64+
],
65+
"VGG19": [
66+
64,
67+
64,
68+
"pooling",
69+
128,
70+
128,
71+
"pooling",
72+
256,
73+
256,
74+
256,
75+
256,
76+
"pooling",
77+
512,
78+
512,
79+
512,
80+
512,
81+
"pooling",
82+
512,
83+
512,
84+
512,
85+
512,
86+
"pooling",
87+
],
88+
}
89+
90+
91+
class VGG(nn.Module):
92+
def __init__(self, model_name):
93+
super(VGG, self).__init__()
94+
self.features = self._make_layers(model_configs[model_name])
95+
self.classifier = nn.Linear(512, 10)
96+
97+
def forward(self, x):
98+
out = self.features(x)
99+
out = out.view(out.size(0), -1)
100+
out = self.classifier(out)
101+
return out
102+
103+
# Main model creation function
104+
def _make_layers(self, model_configs):
105+
106+
layers = []
107+
in_channels = 3
108+
109+
for x in model_configs:
110+
if x == "pooling":
111+
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
112+
else:
113+
layers += [
114+
nn.Conv2d(in_channels, x, kernel_size=3, padding=1),
115+
nn.BatchNorm2d(x),
116+
nn.ReLU(inplace=True),
117+
]
118+
in_channels = x
119+
120+
layers += [nn.AvgPool2d(kernel_size=1, stride=1)]
121+
122+
# Unpack layers for adding to the final Sequential container
123+
return nn.Sequential(*layers)
124+
125+
126+
# VGG16 creation using generic class
127+
def VGG16():
128+
return VGG("VGG16")
129+
130+
131+
# VGG19 creation using generic class
132+
def VGG19():
133+
return VGG("VGG19")
134+

0 commit comments

Comments
 (0)