vgg.py 9.1 KB
Newer Older
L
LielinJiang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

L
LielinJiang 已提交
15 16
import paddle
import paddle.nn as nn
L
LielinJiang 已提交
17

18
from paddle.utils.download import get_weights_path_from_url
L
LielinJiang 已提交
19

20
__all__ = []
L
LielinJiang 已提交
21 22 23

model_urls = {
    'vgg16': ('https://paddle-hapi.bj.bcebos.com/models/vgg16.pdparams',
24 25 26
              '89bbffc0f87d260be9b8cdc169c991c4'),
    'vgg19': ('https://paddle-hapi.bj.bcebos.com/models/vgg19.pdparams',
              '23b18bb13d8894f60f54e642be79a0dd')
L
LielinJiang 已提交
27 28 29
}


L
LielinJiang 已提交
30
class VGG(nn.Layer):
L
LielinJiang 已提交
31
    """VGG model from
32
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
L
LielinJiang 已提交
33 34

    Args:
L
LielinJiang 已提交
35
        features (nn.Layer): Vgg features create by function make_layers.
36
        num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer 
L
LielinJiang 已提交
37
                            will not be defined. Default: 1000.
38
        with_pool (bool, optional): Use pool before the last three fc layer or not. Default: True.
L
LielinJiang 已提交
39

40 41 42
    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of VGG model.

L
LielinJiang 已提交
43 44 45
    Examples:
        .. code-block:: python

46
            import paddle
47 48
            from paddle.vision.models import VGG
            from paddle.vision.models.vgg import make_layers
L
LielinJiang 已提交
49 50 51 52 53 54 55

            vgg11_cfg = [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M']

            features = make_layers(vgg11_cfg)

            vgg11 = VGG(features)

56 57 58 59 60
            x = paddle.rand([1, 3, 224, 224])
            out = vgg11(x)

            print(out.shape)
            # [1, 1000]
L
LielinJiang 已提交
61 62
    """

L
LielinJiang 已提交
63
    def __init__(self, features, num_classes=1000, with_pool=True):
L
LielinJiang 已提交
64 65
        super(VGG, self).__init__()
        self.features = features
L
LielinJiang 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79
        self.num_classes = num_classes
        self.with_pool = with_pool

        if with_pool:
            self.avgpool = nn.AdaptiveAvgPool2D((7, 7))

        if num_classes > 0:
            self.classifier = nn.Sequential(
                nn.Linear(512 * 7 * 7, 4096),
                nn.ReLU(),
                nn.Dropout(),
                nn.Linear(4096, 4096),
                nn.ReLU(),
                nn.Dropout(),
80 81
                nn.Linear(4096, num_classes),
            )
L
LielinJiang 已提交
82 83 84

    def forward(self, x):
        x = self.features(x)
L
LielinJiang 已提交
85 86 87 88 89 90 91 92

        if self.with_pool:
            x = self.avgpool(x)

        if self.num_classes > 0:
            x = paddle.flatten(x, 1)
            x = self.classifier(x)

L
LielinJiang 已提交
93 94 95 96 97 98 99 100
        return x


def make_layers(cfg, batch_norm=False):
    layers = []
    in_channels = 3
    for v in cfg:
        if v == 'M':
C
cnn 已提交
101
            layers += [nn.MaxPool2D(kernel_size=2, stride=2)]
L
LielinJiang 已提交
102
        else:
C
cnn 已提交
103
            conv2d = nn.Conv2D(in_channels, v, kernel_size=3, padding=1)
L
LielinJiang 已提交
104
            if batch_norm:
C
cnn 已提交
105
                layers += [conv2d, nn.BatchNorm2D(v), nn.ReLU()]
L
LielinJiang 已提交
106
            else:
L
LielinJiang 已提交
107
                layers += [conv2d, nn.ReLU()]
L
LielinJiang 已提交
108
            in_channels = v
L
LielinJiang 已提交
109
    return nn.Sequential(*layers)
L
LielinJiang 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127


cfgs = {
    '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'
    ],
}


def _vgg(arch, cfg, batch_norm, pretrained, **kwargs):
128
    model = VGG(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs)
L
LielinJiang 已提交
129 130 131 132 133 134

    if pretrained:
        assert arch in model_urls, "{} model do not have a pretrained model now, you should set pretrained=False".format(
            arch)
        weight_path = get_weights_path_from_url(model_urls[arch][0],
                                                model_urls[arch][1])
135 136

        param = paddle.load(weight_path)
137
        model.load_dict(param)
L
LielinJiang 已提交
138 139 140 141 142

    return model


def vgg11(pretrained=False, batch_norm=False, **kwargs):
143 144
    """VGG 11-layer model from
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
L
LielinJiang 已提交
145 146
    
    Args:
147 148 149 150 151 152 153
        pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained
                            on ImageNet. Default: False.
        batch_norm (bool, optional): If True, returns a model with batch_norm layer. Default: False.
        **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`VGG <api_paddle_vision_VGG>`.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of VGG 11-layer model.
L
LielinJiang 已提交
154 155 156 157

    Examples:
        .. code-block:: python

158
            import paddle
159
            from paddle.vision.models import vgg11
L
LielinJiang 已提交
160 161 162 163 164 165

            # build model
            model = vgg11()

            # build vgg11 model with batch_norm
            model = vgg11(batch_norm=True)
166 167 168 169 170 171

            x = paddle.rand([1, 3, 224, 224])
            out = model(x)

            print(out.shape)
            # [1, 1000]
L
LielinJiang 已提交
172 173 174 175 176 177 178 179
    """
    model_name = 'vgg11'
    if batch_norm:
        model_name += ('_bn')
    return _vgg(model_name, 'A', batch_norm, pretrained, **kwargs)


def vgg13(pretrained=False, batch_norm=False, **kwargs):
180 181
    """VGG 13-layer model from
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
L
LielinJiang 已提交
182 183
    
    Args:
184 185
        pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained
                            on ImageNet. Default: False.
L
LielinJiang 已提交
186
        batch_norm (bool): If True, returns a model with batch_norm layer. Default: False.
187 188 189 190
        **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`VGG <api_paddle_vision_VGG>`.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of VGG 13-layer model.
L
LielinJiang 已提交
191 192 193 194

    Examples:
        .. code-block:: python

195
            import paddle
196
            from paddle.vision.models import vgg13
L
LielinJiang 已提交
197 198 199 200 201 202

            # build model
            model = vgg13()

            # build vgg13 model with batch_norm
            model = vgg13(batch_norm=True)
203 204 205 206 207 208

            x = paddle.rand([1, 3, 224, 224])
            out = model(x)

            print(out.shape)
            # [1, 1000]
L
LielinJiang 已提交
209 210 211 212 213 214 215 216
    """
    model_name = 'vgg13'
    if batch_norm:
        model_name += ('_bn')
    return _vgg(model_name, 'B', batch_norm, pretrained, **kwargs)


def vgg16(pretrained=False, batch_norm=False, **kwargs):
217 218
    """VGG 16-layer model from
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
L
LielinJiang 已提交
219 220
    
    Args:
221 222 223 224 225 226 227
        pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained
                            on ImageNet. Default: False.
        batch_norm (bool, optional): If True, returns a model with batch_norm layer. Default: False.
        **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`VGG <api_paddle_vision_VGG>`.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of VGG 16-layer model.
L
LielinJiang 已提交
228 229 230 231

    Examples:
        .. code-block:: python

232
            import paddle
233
            from paddle.vision.models import vgg16
L
LielinJiang 已提交
234 235 236 237 238 239

            # build model
            model = vgg16()

            # build vgg16 model with batch_norm
            model = vgg16(batch_norm=True)
240 241 242 243 244 245

            x = paddle.rand([1, 3, 224, 224])
            out = model(x)

            print(out.shape)
            # [1, 1000]
L
LielinJiang 已提交
246 247 248 249 250 251 252 253
    """
    model_name = 'vgg16'
    if batch_norm:
        model_name += ('_bn')
    return _vgg(model_name, 'D', batch_norm, pretrained, **kwargs)


def vgg19(pretrained=False, batch_norm=False, **kwargs):
254 255
    """VGG 19-layer model from
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
L
LielinJiang 已提交
256 257
    
    Args:
258 259 260 261 262 263 264
        pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained
                            on ImageNet. Default: False.
        batch_norm (bool, optional): If True, returns a model with batch_norm layer. Default: False.
        **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`VGG <api_paddle_vision_VGG>`.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of VGG 19-layer model.
L
LielinJiang 已提交
265 266 267 268

    Examples:
        .. code-block:: python

269
            import paddle
270
            from paddle.vision.models import vgg19
L
LielinJiang 已提交
271 272 273 274 275 276

            # build model
            model = vgg19()

            # build vgg19 model with batch_norm
            model = vgg19(batch_norm=True)
277 278 279 280 281 282

            x = paddle.rand([1, 3, 224, 224])
            out = model(x)

            print(out.shape)
            # [1, 1000]
L
LielinJiang 已提交
283 284 285 286 287
    """
    model_name = 'vgg19'
    if batch_norm:
        model_name += ('_bn')
    return _vgg(model_name, 'E', batch_norm, pretrained, **kwargs)