AI Logic

Architectures

VGG

Updated:

Structure of VGG. The left shows the overall flow of VGG-16 (five stages of 3×3 convolutions and 2×2 max pooling, three fully connected layers) and the output shape of each stage; the right shows why 3×3 convolutions are stacked (three layers see a 7×7 region, and a comparison of the number of weights with a single 7×7 layer)

Background and overview

VGG is a convolutional neural network that stacks only small 3×3 convolutions, 16 to 19 layers deep. Simonyan and Zisserman of the Visual Geometry Group (VGG) at the University of Oxford published it in 2014. The number of layers is added to the name: the 16-layer version is called VGG-16 and the 19-layer version VGG-19.

At the time, CNNs usually used a large kernel in the first layer, such as the 11×11 (stride 4) kernel of AlexNet. To study what happens when only the depth changes while the rest of the design is kept the same, the VGG paper made every convolution 3×3 and compared five configurations (A–E) from 11 to 19 layers. It showed that accuracy improves as depth increases, with large gains at 16–19 layers.

The main results of the paper are as follows.

  • In ILSVRC-2014, it won first place in the localization track (25.3% error) and second place in the classification track (7.3% top-5 error).
  • After the competition, an ensemble of two models lowered the top-5 classification error to 6.8%. A single model reached 7.0%, the best single-model result at the time.
  • The authors released two trained models (16 and 19 layers) and showed that their features are also useful on other datasets.

Because of its simple structure and publicly available pretrained weights, VGG was used in many studies, such as object detection and style transfer, as a backbone for extracting image features.

Architecture

The structure of VGG is simple: repeat "stack a few 3×3 convolutions, then halve the spatial size with max pooling" five times, and finally put three fully connected layers. In the figure at the head of the article, the left shows the overall flow of VGG-16 and the right shows why 3×3 convolutions are stacked.

The rules shared by all configurations are as follows.

  • The input is a 224×224 RGB image. The only preprocessing is subtracting the mean RGB value, computed on the training set, from each pixel.
  • The convolution kernel is 3×3 (the smallest size that can capture left/right, up/down, and center), with stride 1 and padding 1, so the spatial size does not change.
  • Max pooling is 2×2 with stride 2, applied five times. It does not follow every convolution.
  • The number of channels starts at 64 and doubles after each pooling, stopping at 512.
  • Finally, three fully connected layers (4096, 4096, 1000) are followed by the softmax function to output class probabilities.
  • ReLU is applied to every hidden layer.

The five configurations compared in the paper are as follows (Tables 1 and 2 of the paper). conv3-64 means "a 3×3 convolution with 64 channels"; the table shows the number of convolutions in each stage.

ConfigurationWeight layers64 ch128 ch256 ch512 ch512 chParameters
A1111222133M
A-LRN111 (+LRN)1222133M
B1322222133M
C16223 (one is 1×1)3 (one is 1×1)3 (one is 1×1)134M
D (VGG-16)1622333138M
E (VGG-19)1922444144M

A-LRN adds AlexNet's local response normalization (LRN) after the first layer of A, and C replaces some convolutions with 1×1. The number of parameters barely grows with depth because most of the parameters are in the fully connected layers.

Why stack 3×3 convolutions

Stacking two 3×3 convolutions without pooling in between gives each output cell a view of a 5×5 region of the input (receptive field), and stacking three gives 7×7. So what is gained by stacking three 3×3 layers instead of using one 7×7 layer? The paper gives two reasons.

  1. More nonlinear layers: the signal passes through ReLU three times instead of once, which makes the decision function more discriminative.
  2. Fewer parameters: if both the input and output have CC channels, the number of weights is as follows.
3×(32C2)=27C2⏟three 3×3 layersvs.72C2=49C2⏟one 7×7 layer\underbrace{3 \times (3^2 C^2) = 27C^2}_{\text{three 3×3 layers}} \qquad \text{vs.} \qquad \underbrace{7^2 C^2 = 49C^2}_{\text{one 7×7 layer}}

A single 7×7 layer has 81% more weights. The paper also views this as a kind of regularization that forces the 7×7 kernels to be decomposed into stacks of 3×3 kernels.

The 1×1 convolutions in configuration C are a way to add nonlinear layers without changing the receptive field (an idea used in Network In Network). In the paper's experiments, however, D with only 3×3 convolutions did better than C with 1×1 convolutions at the same depth of 16 layers. This shows that capturing information from surrounding pixels (spatial context) matters, not just adding nonlinearity.

Training and inference

The training procedure largely follows AlexNet. The differences are that it trains with randomly varied image sizes, and that at test time it replaces the fully connected layers with convolutions and applies the network to the whole image.

Training settings

ItemValue
LossCross-entropy (multinomial logistic regression)
OptimizationMini-batch gradient descent, momentum 0.9, batch size 256
Weight Decay5×10−45 \times 10^{-4}
DropoutFirst two fully connected layers, ratio 0.5
Learning rateStarts at 10−210^{-2} and is divided by 10 when validation accuracy stops improving (3 times)
Training length370K iterations (74 epochs)
Compute2–3 weeks per model on 4 NVIDIA Titan Black GPUs

Weight initialization

With a bad initialization, gradients in a deep network become unstable and learning stalls. To avoid this, the paper took the following steps.

  1. First train the shallow configuration A (11 layers), which can be trained from random initialization (weights from a normal distribution with mean 0 and variance 10−210^{-2}, biases 0).
  2. When training deeper configurations, initialize the first four convolutional layers and the last three fully connected layers with the weights of A, and initialize the layers in between randomly.

The paper notes that after submission, the authors found that Xavier initialization makes it possible to initialize without this pre-training.

Image size (scale)

Training images are resized, keeping the aspect ratio, so that the shorter side is SS, and a 224×224 crop is taken at random. The crops are randomly flipped horizontally and their RGB colors are shifted (as in AlexNet). There are two ways to set SS.

  • Single scale: fix S=256S = 256 or S=384S = 384.
  • Multiple scales: for each image, choose SS at random from the range 256–512 (scale jittering). This data augmentation helps the network recognize objects of various sizes.

At test time (dense evaluation)

Test images are resized so that the shorter side is QQ and fed in whole, without cropping. To do so, the fully connected layers are replaced with convolutional layers (the first fully connected layer becomes a 7×7 convolution, and the remaining two become 1×1 convolutions). The output is then a class score map whose size depends on the input size, and it is averaged spatially into a single score. The result is also averaged with that of the horizontally flipped image.

Why depth helps

The central claim of the VGG paper is that simply increasing depth while keeping the rest of the design the same improves accuracy.

  • Deeper means lower error: under the same conditions, the error decreased with depth from the 11-layer A to the 19-layer E. It saturated at 19 layers, but the paper suggests that even deeper models might help with larger datasets.
  • Stacking small kernels is better than one large kernel: a shallower network in which each pair of 3×3 layers in configuration B was replaced by a single 5×5 layer (with the same receptive field) had a top-1 error 7 points higher than B.
  • LRN does not help: A-LRN, which adds local response normalization to A, was no better than A. Therefore, the deeper configurations (B–E) do not use normalization.

As an everyday analogy, one 7×7 layer is like "measuring all at once with a long ruler", while three 3×3 layers are like "measuring in three steps with a short ruler, making a judgment each time". The range measured is the same, but being able to insert judgments (nonlinearities) along the way makes it easier to capture fine shapes.

VGG saturated at 19 layers, but the reason was not a limit on depth itself but the difficulty of optimizing deep networks. The later ResNet solved this difficulty by adding shortcut connections to a VGG-inspired design, going as deep as 152 layers.

Experimental results

Single-scale testing (ILSVRC-2012 validation set, error %; SS is the shorter side of the training images, QQ that of the test images)

ConfigurationTrain SSTest QQtop-1top-5
A25625629.610.4
A-LRN25625629.710.5
B25625628.79.9
C25625628.19.4
D25625627.08.8
E25625627.39.0
D256–51238425.68.1
E256–51238425.58.0

The error decreased with depth and decreased further with scale jittering during training (choosing SS from 256–512). Averaging tests over multiple scales (QQ = 256, 384, 512) gave a top-1 error of 24.8% and a top-5 error of 7.5% for both D and E.

Comparison with other methods (ILSVRC classification, results without external data; error %)

Methodtop-1 (val)top-5 (val)top-5 (test)
VGG (2 models, post-competition)23.76.86.8
VGG (1 model)24.47.17.0
VGG (competition submission, 7 models)24.77.57.3
GoogLeNet (7 models)——6.7
GoogLeNet (1 model)——7.9
Zeiler & Fergus (6 models)36.014.714.8
AlexNet (5 models)38.116.416.4

As an ensemble it falls slightly short of GoogLeNet, the competition winner, but as a single model it is 0.9 points better than GoogLeNet. The single-model VGG figure combines multiple crops (multi-crop) and dense evaluation at test time.

In the appendix, the paper uses the output of the last hidden layer of VGG trained on ImageNet as features and shows that they match or exceed the state of the art at the time on image classification with PASCAL VOC and Caltech.

Practical notes

Keep the following points in mind when using VGG.

  • It is heavy and slow: VGG-16 has about 138 million parameters. The first fully connected layer alone (7×7×512 = 25088 dimensions → 4096 dimensions) accounts for about 100 million of them. The VGG-16 in PyTorch's torchvision requires 15.47 GFLOPS, more than ResNet-50.
  • VGG without batch normalization is hard to train: the paper started training deep models by initializing them with the weights of a shallow model. When training it yourself, use He initialization or similar, or use the version with batch normalization (vgg16_bn in torchvision).
  • Variable input sizes depend on an inference trick: the paper replaced the fully connected layers with convolutions to apply the network to entire large images. torchvision's VGG instead inserts an average pooling layer (AdaptiveAvgPool2d) that resizes the feature map to 7×7 before the fully connected layers.
  • Match the preprocessing to the weights: torchvision's VGG16_Weights.IMAGENET1K_V1 scales pixels to 0–1 and then normalizes them with a mean and standard deviation. On the other hand, IMAGENET1K_FEATURES, intended for feature extraction, was trained with the same preprocessing as the paper (subtracting the mean from pixel values on a 0–255 scale), and its classification layers cannot be used. Using weights.transforms() attached to the weights avoids mistakes.

Scale jittering during training and dense evaluation and multi-crop at test time contribute substantially to the numbers in the paper's tables. The accuracy of torchvision's pretrained VGG-16 (top-1 71.6%, top-5 90.4%) is for a single center 224×224 crop, which is not the same condition as the paper's tables. Align the evaluation methods when comparing.

Comparison with other models

Along with GoogLeNet, which appeared at ILSVRC-2014 at the same time, VGG showed that "deeper is better". Comparing them from the same viewpoints gives the following (error rates are top-5 on the ILSVRC test set from each paper).

ModelWeight layersConvolution kernelsParameters / computationDesign philosophytop-5 error
AlexNet811×11, 5×5, 3×3About 60MStart with large kernels, split across 2 GPUs15.3%
VGG-16/1916, 193×3 (one kind)138M, 144MRepeat stages of the same shape and increase only depth6.8% (2 models)
GoogLeNet221×1, 3×3, 5×5 in parallel1/12 of AlexNetGo deeper and wider while keeping computation low with Inception modules6.67% (7 models)
ResNetUp to 1523×3, 1×1ResNet-50 needs about 1/4 the computation of VGG-16Add shortcut connections to a VGG-inspired design3.57% (6 models)

VGG has the simplest structure and suits research that wants uniform layer shapes, or uses that extract features from intermediate layers. On the other hand, it has the most parameters and computation, and its efficiency per unit of accuracy is worse than GoogLeNet and ResNet.

Rough guidelines for choosing are as follows.

  • Extracting image features (style transfer, perceptual loss, etc.): VGG-16/19, whose intermediate layers are easy to interpret, is still widely used.
  • As a backbone for image classification or object detection: choose ResNet, which balances accuracy and computation well, or lightweight models such as MobileNet and EfficientNet.
  • Limited compute: avoid VGG and choose a lightweight model.

PyTorch example

Show code
python
import torch
import torch.nn as nn
from PIL import Image
from torchvision.models import vgg16, VGG16_Weights

"""
Examples of loading torchvision's pretrained VGG-16 to classify an image and to extract features from intermediate layers
"""

weights = VGG16_Weights.IMAGENET1K_V1        # same as VGG16_Weights.DEFAULT. weights=None gives random weights
model = vgg16(weights=weights)
model.eval()                                 # disable dropout in the fully connected layers

# Preprocessing comes with the weights: resize the shorter side to 256, center-crop 224x224, normalize with mean and std
preprocess = weights.transforms()
image = Image.open("cat.jpg").convert("RGB")
x = preprocess(image).unsqueeze(0)           # [1, 3, 224, 224]

with torch.no_grad():
  probs = model(x).softmax(dim=1)            # [1, 1000]
top5 = probs.topk(5, dim=1)
categories = weights.meta["categories"]
for p, i in zip(top5.values[0], top5.indices[0]):
  print(f"{categories[i]}: {p.item():.3f}")

# Contents: features (13 3x3 conv layers and 5 max poolings) -> avgpool (resize to 7x7) -> classifier (3 fully connected layers)
with torch.no_grad():
  feat = model.features(x)                   # [1, 512, 7, 7]
print(feat.shape)

# Extract intermediate features (e.g., the ReLU output after the last conv of stage 4)
extractor = model.features[:23].eval()       # features[22] is the ReLU after conv4_3
with torch.no_grad():
  mid = extractor(x)                         # [1, 512, 28, 28]

# To replace the head for 10-class classification and fine-tune
model.classifier[6] = nn.Linear(4096, 10)
for p in model.features.parameters():        # freeze the convolutional part and train only the fully connected layers
  p.requires_grad = False
model.train()                                # enable dropout
optimizer = torch.optim.SGD([p for p in model.parameters() if p.requires_grad], lr=1e-3, momentum=0.9)

FAQ

Q. How do VGG-16 and VGG-19 differ?
A.

Only the number of convolutions in stages 3–5 differs. VGG-16 (configuration D) has 3 per stage and VGG-19 (configuration E) has 4. Their ImageNet results in the paper are almost the same: with multi-scale testing, both had a top-5 error of 7.5%. They have 138 million and 144 million parameters.

Q. Why does it use only 3×3 kernels?
A.

Because stacking 3×3 kernels covers the same region as a large kernel while using fewer weights and adding more nonlinear layers. Three layers cover a 7×7 region with 27C227C^2 weights, fewer than the 49C249C^2 of a single 7×7 layer. 3×3 is the smallest size that can capture left/right, up/down, and center.

Q. Is VGG still used today?
A.

As a backbone for image classification, it has been replaced by lighter and more accurate models such as ResNet. However, because its structure is simple and its intermediate features are easy to interpret, it is still widely used to extract features for style transfer and for losses that measure visual similarity between images (perceptual losses).

References

  1. Simonyan, K., & Zisserman, A. (2015). Very Deep Convolutional Networks for Large-Scale Image Recognition. ICLR 2015. arXiv:1409.1556.
  2. Krizhevsky, A., Sutskever, I., & Hinton, G. E. (2012). ImageNet Classification with Deep Convolutional Neural Networks. NIPS 2012.
  3. Szegedy, C., et al. (2015). Going Deeper with Convolutions. CVPR 2015. arXiv:1409.4842.
  4. PyTorch. torchvision.models.vgg16 (VGG16_Weights).