vgg.py 7.05 KB
Newer Older
1
import torch.nn as nn
2
from .utils import load_state_dict_from_url
3
4
5
6
7
8
9
10


__all__ = [
    'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
    'vgg19_bn', 'vgg19',
]


11
model_urls = {
12
13
14
15
    'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
    'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth',
    'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',
    'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth',
16
17
18
19
    'vgg11_bn': 'https://download.pytorch.org/models/vgg11_bn-6002323d.pth',
    'vgg13_bn': 'https://download.pytorch.org/models/vgg13_bn-abd245e5.pth',
    'vgg16_bn': 'https://download.pytorch.org/models/vgg16_bn-6c64b313.pth',
    'vgg19_bn': 'https://download.pytorch.org/models/vgg19_bn-c79401a0.pth',
20
21
22
}


Soumith Chintala's avatar
Soumith Chintala committed
23
class VGG(nn.Module):
24

25
    def __init__(self, features, num_classes=1000, init_weights=True):
26
27
        super(VGG, self).__init__()
        self.features = features
28
        self.avgpool = nn.AdaptiveAvgPool2d((7, 7))
29
30
31
32
33
34
        self.classifier = nn.Sequential(
            nn.Linear(512 * 7 * 7, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(True),
35
            nn.Dropout(),
Karan Dwivedi's avatar
Karan Dwivedi committed
36
            nn.Linear(4096, num_classes),
37
        )
38
39
        if init_weights:
            self._initialize_weights()
40
41
42

    def forward(self, x):
        x = self.features(x)
43
        x = self.avgpool(x)
44
45
46
47
        x = x.view(x.size(0), -1)
        x = self.classifier(x)
        return x

48
49
50
    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
51
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
52
                if m.bias is not None:
53
                    nn.init.constant_(m.bias, 0)
54
            elif isinstance(m, nn.BatchNorm2d):
55
56
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
57
            elif isinstance(m, nn.Linear):
58
59
                nn.init.normal_(m.weight, 0, 0.01)
                nn.init.constant_(m.bias, 0)
60

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

def make_layers(cfg, batch_norm=False):
    layers = []
    in_channels = 3
    for v in cfg:
        if v == 'M':
            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
        else:
            conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
            if batch_norm:
                layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
            else:
                layers += [conv2d, nn.ReLU(inplace=True)]
            in_channels = v
    return nn.Sequential(*layers)


78
cfgs = {
79
80
81
82
83
84
85
    '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'],
}


86
87
88
89
90
91
92
93
94
95
96
97
def _vgg(arch, cfg, batch_norm, pretrained, progress, **kwargs):
    if pretrained:
        kwargs['init_weights'] = False
    model = VGG(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs)
    if pretrained:
        state_dict = load_state_dict_from_url(model_urls[arch],
                                              progress=progress)
        model.load_state_dict(state_dict)
    return model


def vgg11(pretrained=False, progress=True, **kwargs):
98
99
    r"""VGG 11-layer model (configuration "A") from
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>'_
100
101
102

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
103
        progress (bool): If True, displays a progress bar of the download to stderr
104
    """
105
    return _vgg('vgg11', 'A', False, pretrained, progress, **kwargs)
106
107


108
def vgg11_bn(pretrained=False, progress=True, **kwargs):
109
110
    r"""VGG 11-layer model (configuration "A") with batch normalization
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>'_
111
112
113

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
114
        progress (bool): If True, displays a progress bar of the download to stderr
115
    """
116
    return _vgg('vgg11_bn', 'A', True, pretrained, progress, **kwargs)
117
118


119
def vgg13(pretrained=False, progress=True, **kwargs):
120
121
    r"""VGG 13-layer model (configuration "B")
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>'_
122
123
124

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
125
        progress (bool): If True, displays a progress bar of the download to stderr
126
    """
127
    return _vgg('vgg13', 'B', False, pretrained, progress, **kwargs)
128
129


130
def vgg13_bn(pretrained=False, progress=True, **kwargs):
131
132
    r"""VGG 13-layer model (configuration "B") with batch normalization
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>'_
133
134
135

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
136
        progress (bool): If True, displays a progress bar of the download to stderr
137
    """
138
    return _vgg('vgg13_bn', 'B', True, pretrained, progress, **kwargs)
139
140


141
def vgg16(pretrained=False, progress=True, **kwargs):
142
143
    r"""VGG 16-layer model (configuration "D")
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>'_
144
145
146

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
147
        progress (bool): If True, displays a progress bar of the download to stderr
148
    """
149
    return _vgg('vgg16', 'D', False, pretrained, progress, **kwargs)
150
151


152
def vgg16_bn(pretrained=False, progress=True, **kwargs):
153
154
    r"""VGG 16-layer model (configuration "D") with batch normalization
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>'_
155
156
157

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
158
        progress (bool): If True, displays a progress bar of the download to stderr
159
    """
160
    return _vgg('vgg16_bn', 'D', True, pretrained, progress, **kwargs)
161
162


163
def vgg19(pretrained=False, progress=True, **kwargs):
164
165
    r"""VGG 19-layer model (configuration "E")
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>'_
166
167
168

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
169
        progress (bool): If True, displays a progress bar of the download to stderr
170
    """
171
    return _vgg('vgg19', 'E', False, pretrained, progress, **kwargs)
172
173


174
def vgg19_bn(pretrained=False, progress=True, **kwargs):
175
176
    r"""VGG 19-layer model (configuration 'E') with batch normalization
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>'_
177
178
179

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
180
        progress (bool): If True, displays a progress bar of the download to stderr
181
    """
182
    return _vgg('vgg19_bn', 'E', True, pretrained, progress, **kwargs)