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


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


12
model_urls = {
13
14
15
16
    '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',
17
18
19
20
    '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',
21
22
23
}


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

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

    def forward(self, x):
        x = self.features(x)
44
        x = self.avgpool(x)
45
        x = torch.flatten(x, 1)
46
47
48
        x = self.classifier(x)
        return x

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

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

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)


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


87
88
89
90
91
92
93
94
95
96
97
98
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):
99
    r"""VGG 11-layer model (configuration "A") from
100
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_
101
102
103

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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