• VGG16 (VGGNet): Architecture, Parameters and Code in PyTorch and Keras

    vgg16

    VGG16 is a 16-layer convolutional neural network for image classification, created in 2014 by Karen Simonyan and Andrew Zisserman of the Visual Geometry Group (VGG) at the University of Oxford. It stacks 13 convolutional layers with small 3×3 filters and 3 fully connected layers, has 138 million parameters, and took second place in classification and first place in localization at the ImageNet ILSVRC-2014 challenge. Its simple, uniform design made VGG16 one of the most widely used CNNs of the 2010s: a standard backbone for object detection, segmentation and style transfer, and still the network behind popular perceptual losses for image generation.

    This guide explains the VGG16 architecture layer by layer, where its parameters and computation go, how it differs from VGG19 and how it was trained. It includes PyTorch and Keras code for classification, a VGG16 implementation from scratch and transfer learning. We also ran our own tests: how fast VGG16 is on a CPU compared with ResNet-50, EfficientNet and a Vision Transformer, and how good its frozen features are on a dataset of 37 cat and dog breeds.

    Key takeaways

    • VGG16 = 13 convolutional + 3 fully connected layers. Every convolution is 3×3 with stride 1, every pooling layer is 2×2 max pooling, and the number of filters doubles from 64 to 512 after each pooling stage.
    • 138.4 million parameters, 15.5 billion multiply-accumulate operations per 224×224 image. 89% of the parameters sit in the fully connected layers (the first one alone holds 74%), but 99% of the computation happens in the convolutional layers.
    • The famous 92.7% top-5 accuracy is the ILSVRC-2014 result of an ensemble of seven networks. A single VGG16 from torchvision reaches 71.6% top-1 and 90.4% top-5 accuracy on ImageNet.
    • On a 2-core CPU, VGG16 needs 238 ms per image: 2.6 times longer than ResNet-50 and 8 times longer than EfficientNet-B0, both of which are more accurate.
    • In our pet-breed test, frozen VGG16 features reached 90.5% accuracy with 50 training photos per breed and 82.6% with five. ResNet-50, EfficientNet-B0 and ViT-B/16 reached 92.7–94.3% and 86.4–87.8%.
    • VGG16 is still used for perceptual losses (LPIPS, style transfer, super-resolution), in older detectors such as SSD and in teaching. For a new image-classification project, newer backbones are faster and more accurate.

    What is VGG16?

    VGG16 is a deep convolutional neural network (CNN) that takes a 224×224 color image and outputs probabilities for the 1,000 ImageNet classes. The name combines the lab, the Visual Geometry Group, with the number of layers that have learnable weights: 13 convolutional and 3 fully connected. Pooling and softmax layers have no weights and are not counted. The whole family of these networks is often called VGGNet.

    The network was described in the paper “Very Deep Convolutional Networks for Large-Scale Image Recognition”, first posted on arXiv in September 2014 and presented at ICLR 2015. The authors asked a simple question: what happens to accuracy if you keep the design fixed and only make the network deeper? They built six configurations with 11 to 19 weight layers, all using tiny 3×3 filters. The 16-layer configuration D and the 19-layer configuration E, now known as VGG16 and VGG19, gave the best results.

    At ILSVRC-2014 the VGG team took second place in classification with a 7.3% top-5 error, behind GoogLeNet with 6.7%, and won the localization task with a 25.3% error. After the competition, an ensemble of just two models, VGG16 and VGG19, brought the classification error down to 6.8%.

    VGG16 architecture diagram: five blocks of convolutional layers with max pooling, followed by three fully connected layers
    VGG16 architecture: five convolutional blocks, each ending in max pooling, and three fully connected layers

    VGG16 came two years after AlexNet, which used large 11×11 and 5×5 filters in its first layers. VGG replaced them with stacks of 3×3 filters and doubled the depth. That idea, small filters and many layers, was adopted by almost every CNN that came after it, including ResNet.

    VGG16 architecture

    The input is a fixed-size 224×224 RGB image. The only preprocessing in the original paper is subtracting the mean RGB value of the training set from every pixel. The image then passes through five blocks of convolutional layers and three fully connected layers:

    • Convolutional layers use 3×3 filters with stride 1 and padding 1, so the height and width of the feature map stay the same. Each convolution is followed by a ReLU activation.
    • Max pooling with a 2×2 window and stride 2 ends each block and halves the height and width: 224 → 112 → 56 → 28 → 14 → 7.
    • The number of filters starts at 64 and doubles after each pooling layer until it reaches 512: blocks 1–5 have 64, 128, 256, 512 and 512 channels. Blocks 1 and 2 contain two convolutional layers each, blocks 3–5 contain three.
    • The classifier consists of three fully connected (FC) layers: 4,096, 4,096 and 1,000 units, with dropout of 0.5 after the first two. A softmax turns the last 1,000 values into class probabilities.
    • There are no normalization layers. The authors tested the Local Response Normalization used in AlexNet and found that it did not improve accuracy while costing memory and time. Batch normalization was published a few months later; torchvision offers a separate vgg16_bn version with it.
    VGG16 layer diagram with input 224x224x3, convolutional blocks, max pooling layers and fully connected layers
    VGG16 layer by layer: the feature map shrinks from 224×224 to 7×7 while the number of channels grows from 64 to 512

    Why 3×3 convolutions?

    Two stacked 3×3 convolutions see a 5×5 region of the input, and three see a 7×7 region, the same as one large filter. But the stack is cheaper and more expressive. With 512 input and output channels, a single 7×7 layer needs 12.8 million weights, while three 3×3 layers need 7.1 million, 45% fewer. The stack also applies three ReLU non-linearities instead of one, so it can represent more complex functions.

    As layers are added, the receptive field grows: a single value after the last pooling layer of VGG16 depends on a 212×212 pixel region, almost the whole 224×224 input. The paper also tested 1×1 convolutions (configuration C): at the same depth they were worse than 3×3 layers, which shows that spatial context matters, not just depth.

    VGG16 layers, parameters and computation

    We counted the parameters and the multiply-accumulate operations (MACs) of every layer with a short script on top of torchvision’s vgg16. A convolutional layer with 3×3 filters, Cin input channels and Cout filters has 3·3·Cin·Cout weights plus Cout biases: the first layer has 3·3·3·64 + 64 = 1,792 parameters. The first fully connected layer receives all 7·7·512 = 25,088 values of the last feature map, so it has 25,088·4,096 + 4,096 = 102,764,544 parameters.

    Block Layers Output size Parameters MACs, millions
    1 2 × conv 3×3, 64 filters; max pool 112×112×64 38,720 1,936
    2 2 × conv 3×3, 128 filters; max pool 56×56×128 221,440 2,775
    3 3 × conv 3×3, 256 filters; max pool 28×28×256 1,475,328 4,624
    4 3 × conv 3×3, 512 filters; max pool 14×14×512 5,899,776 4,624
    5 3 × conv 3×3, 512 filters; max pool 7×7×512 7,079,424 1,387
    FC6 fully connected 25,088 → 4,096; ReLU, dropout 4,096 102,764,544 103
    FC7 fully connected 4,096 → 4,096; ReLU, dropout 4,096 16,781,312 17
    FC8 fully connected 4,096 → 1,000; softmax 1,000 4,097,000 4
    Total 13 conv + 3 FC layers 138,357,544 15,470

    In total VGG16 has 138,357,544 parameters and performs 15.5 billion multiply-accumulate operations per image. torchvision lists this as 15.47 GFLOPS; strictly speaking, one multiply-accumulate is two floating-point operations, so a forward pass takes about 31 billion FLOPs.

    Bar charts: share of VGG16 parameters and computation by layer. Fully connected layers hold 89% of the parameters, convolutional blocks do 99% of the computation
    89% of the VGG16 parameters sit in the fully connected layers, while 99% of the computation happens in the convolutional blocks

    The chart shows the main imbalance of VGG16:

    • 89.4% of the parameters are in the three fully connected layers. The first of them, FC6, alone holds 102.8 million weights, 74.3% of the network. The 13 convolutional layers have only 14.7 million.
    • 99.2% of the computation happens in the convolutional layers. Blocks 3 and 4 do 60% of the work: they combine a large feature map with many channels.
    • Memory. In 32-bit floats the weights take 528 MiB, which is the size of the familiar vgg16 file (264 MiB in 16-bit). A single 224×224 image produces 15.1 million intermediate values, about 58 MiB; training has to keep them for backpropagation, which is why VGG16 needs a lot of GPU memory even for small batches.

    Later networks removed this imbalance. ResNet and most modern CNNs replace the large fully connected layers with global average pooling and a single small classifier, which is also the easiest way to shrink VGG16 for transfer learning.

    VGG16 vs VGG19 and other VGG networks

    The paper describes configurations A–E. Four of them became standard models: VGG11 (A), VGG13 (B), VGG16 (D) and VGG19 (E). They differ only in the number of 3×3 convolutional layers per block; the fully connected part is the same.

    Table of VGG configurations A to E from the original paper, VGG16 is column D and VGG19 is column E
    VGG configurations A–E from the original paper: VGG16 is column D, VGG19 is column E
    Network Config Conv + FC layers Parameters GMACs Top-1 / top-5 error, paper* Top-1 accuracy, torchvision With batch norm
    VGG11 A 8 + 3 132.9M 7.6 29.6% / 10.4% 69.0% 70.4%
    VGG13 B 10 + 3 133.0M 11.3 28.7% / 9.9% 69.9% 71.6%
    VGG16 D 13 + 3 138.4M 15.5 27.0% / 8.8% 71.6% 73.4%
    VGG19 E 16 + 3 143.7M 19.6 27.3% / 9.0% 72.4% 74.2%

    * ImageNet validation error at a single scale, training and test images rescaled to 256 pixels (Table 3 of the paper). With scale jittering during training, VGG16 and VGG19 reached 25.6% and 25.5% top-1 error.

    VGG16 vs VGG19. VGG19 adds one more convolutional layer to each of blocks 3, 4 and 5. That adds 5.3 million parameters (+3.8%) and 27% more computation, but very little accuracy: in the paper the two networks were within 0.3 percentage points of each other, and with torchvision weights VGG19 is 0.8 points better. The authors concluded that the error saturated at 19 layers. Going deeper only became possible with batch normalization and the residual connections of ResNet. In practice VGG16 is the more popular choice; VGG19 is used mostly in style transfer and super-resolution, where its features became the standard for perceptual losses.

    How VGG16 was trained

    VGG16 was trained on the ILSVRC-2012 dataset, a subset of ImageNet with 1,000 classes: about 1.3 million training images, 50,000 validation and 100,000 test images. ImageNet as a whole has more than 14 million images in about 22,000 categories.

    • Data augmentation. Each training image was rescaled so that its shorter side equals S, and a random 224×224 crop was taken, then flipped horizontally at random and shifted in color. The best models used scale jittering: S was sampled from 256 to 512 for every image, so the network saw objects at different sizes.
    • Optimization. Mini-batch gradient descent with momentum 0.9, batch size 256, weight decay 5·10-4, dropout 0.5 in the first two FC layers. The learning rate started at 0.01 and was divided by 10 three times, when validation accuracy stopped improving. Training stopped after 370,000 iterations, or 74 epochs.
    • Initialization. Deep plain networks are hard to start training from random weights, so the authors first trained the shallow configuration A and copied its first four convolutional layers and three FC layers into the deeper networks. After the paper was submitted they found that Glorot (Xavier) initialization works without this step.
    • Hardware. Training ran on four NVIDIA Titan Black GPUs with data parallelism, 3.75 times faster than on one GPU, and took 2–3 weeks per network. Today the same training would take less than a day on a single modern data-center GPU.
    • Testing. At test time the FC layers were converted into convolutions (a 7×7 convolution and two 1×1 convolutions), so the network could be applied to a whole rescaled image at once. Predictions over several scales, horizontal flips and crops were averaged.

    VGG16 results on ImageNet

    In the paper, a single VGG16 reached 24.4% top-1 and 7.2% top-5 error on the ImageNet validation set with multi-scale, multi-crop and dense evaluation. The table below compares VGG with the best entries of ILSVRC 2012–2014 by top-5 test error (lower is better).

    Model Year Top-5 test error
    VGG, ensemble of 2 nets (VGG16 + VGG19), after the competition 2014 6.8%
    VGG, single network 2014 7.0%
    VGG, ILSVRC-2014 submission, 7 nets 2014 7.3%
    GoogLeNet, 7 nets (ILSVRC-2014 winner) 2014 6.7%
    GoogLeNet, single network 2014 7.9%
    MSRA, 11 nets 2014 8.1%
    Clarifai (ILSVRC-2013 winner) 2013 11.7%
    OverFeat, 7 nets 2013 13.6%
    Zeiler and Fergus, 6 nets 2013 14.8%
    AlexNet, 5 nets (ILSVRC-2012 winner) 2012 16.4%
    VGG16 comparison with ILSVRC 2012 to 2014 entries, table from the original paper
    Comparison with the state of the art in 2014, Table 7 of the paper

    Where does 92.7% come from? Many sources say that VGG16 reaches 92.7% top-5 accuracy. That number, 100% minus 7.3%, is the team’s competition submission, an ensemble of seven networks. A single VGG16 evaluated on one 224×224 center crop reaches 90.4% top-5 and 71.6% top-1 accuracy with torchvision weights, and 90.1% and 71.3% with the Keras weights.

    VGG16 in PyTorch

    PyTorch includes VGG16 in torchvision. Its weights are not the original Oxford weights: the PyTorch team retrained the network with a simplified recipe and got 71.6% top-1 accuracy. weights.transforms() applies the matching preprocessing: resize to 256 pixels, center crop to 224 and normalize with the ImageNet mean and standard deviation. If you are new to the framework, start with our PyTorch tutorial.

    Classify an image with pretrained VGG16

    import torch
    from PIL import Image
    from torchvision.models import vgg16, VGG16_Weights
    
    weights = VGG16_Weights.IMAGENET1K_V1          # 528 MB, downloaded on first use
    model = vgg16(weights=weights).eval()
    preprocess = weights.transforms()              # resize 256, center crop 224, ImageNet mean/std
    
    img = Image.open("dog.jpg").convert("RGB")
    with torch.inference_mode():
        probs = model(preprocess(img).unsqueeze(0)).softmax(dim=1)[0]
    
    top5 = probs.topk(5)
    for p, i in zip(top5.values, top5.indices):
        print(f"{weights.meta['categories'][i]:<28}{p:.3f}")

    The script prints the five most likely ImageNet classes with their probabilities. There is also a second set of weights, VGG16_Weights.IMAGENET1K_FEATURES: it contains only the convolutional part of the original model and is used by torchvision’s SSD detector.

    VGG16 implementation from scratch

    The whole network fits in about 35 lines. The list CFG_VGG16 encodes the architecture: numbers are the output channels of 3×3 convolutions, “M” is max pooling.

    import torch
    from torch import nn
    
    # numbers = output channels of 3x3 convolutions, "M" = 2x2 max pooling
    CFG_VGG16 = [64, 64, "M", 128, 128, "M", 256, 256, 256, "M",
                 512, 512, 512, "M", 512, 512, 512, "M"]
    
    
    class VGG16(nn.Module):
        def __init__(self, num_classes=1000):
            super().__init__()
            layers, in_ch = [], 3
            for v in CFG_VGG16:
                if v == "M":
                    layers.append(nn.MaxPool2d(kernel_size=2, stride=2))
                else:
                    layers += [nn.Conv2d(in_ch, v, kernel_size=3, padding=1), nn.ReLU(inplace=True)]
                    in_ch = v
            self.features = nn.Sequential(*layers)
            self.avgpool = nn.AdaptiveAvgPool2d((7, 7))  # lets the network accept other input sizes
            self.classifier = nn.Sequential(
                nn.Linear(512 * 7 * 7, 4096), nn.ReLU(inplace=True), nn.Dropout(0.5),
                nn.Linear(4096, 4096), nn.ReLU(inplace=True), nn.Dropout(0.5),
                nn.Linear(4096, num_classes),
            )
    
        def forward(self, x):
            x = self.features(x)
            x = torch.flatten(self.avgpool(x), 1)
            return self.classifier(x)
    
    
    model = VGG16()
    print(sum(p.numel() for p in model.parameters()))   # 138357544
    print(model(torch.randn(1, 3, 224, 224)).shape)     # torch.Size([1, 1000])

    The layer names and shapes match torchvision exactly (we checked every tensor), so you can load the pretrained weights into this class: model.load_state_dict(torchvision.models.vgg16(weights="DEFAULT").state_dict()). The adaptive pooling layer comes from torchvision: it resizes any feature map to 7×7, so the network also accepts images larger than 224×224.

    Fine-tune VGG16 on your own images

    For a small dataset, keep the pretrained convolutional layers frozen and train only the classifier. The example expects a folder with one sub-folder per class, such as pets/train/beagle/*.jpg.

    import torch
    from torch import nn
    from torchvision import datasets, transforms
    from torchvision.models import vgg16, VGG16_Weights
    
    weights = VGG16_Weights.IMAGENET1K_V1
    norm = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
    train_tf = transforms.Compose([transforms.RandomResizedCrop(224, scale=(0.6, 1.0)),
                                   transforms.RandomHorizontalFlip(), transforms.ToTensor(), norm])
    test_tf = transforms.Compose([transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), norm])
    
    train_ds = datasets.ImageFolder("pets/train", train_tf)   # one sub-folder per class
    test_ds = datasets.ImageFolder("pets/test", test_tf)
    train_dl = torch.utils.data.DataLoader(train_ds, batch_size=32, shuffle=True, num_workers=2)
    test_dl = torch.utils.data.DataLoader(test_ds, batch_size=64, num_workers=2)
    
    device = "cuda" if torch.cuda.is_available() else "cpu"
    model = vgg16(weights=weights)
    for p in model.features.parameters():
        p.requires_grad = False                                # freeze the 13 conv layers
    model.classifier[6] = nn.Linear(4096, len(train_ds.classes))  # new output layer
    model = model.to(device)
    
    optimizer = torch.optim.AdamW((p for p in model.parameters() if p.requires_grad), lr=1e-4, weight_decay=1e-4)
    loss_fn = nn.CrossEntropyLoss(label_smoothing=0.1)
    
    for epoch in range(5):
        model.train()
        for x, y in train_dl:
            x, y = x.to(device), y.to(device)
            optimizer.zero_grad()
            loss = loss_fn(model(x), y)
            loss.backward()
            optimizer.step()
        model.eval()
        correct = 0
        with torch.inference_mode():
            for x, y in test_dl:
                correct += (model(x.to(device)).argmax(1).cpu() == y).sum().item()
        print(f"epoch {epoch + 1}: loss {loss.item():.3f}, test accuracy {correct / len(test_ds):.3f}")

    Practical tips:

    • Only the classifier is trained, but every step still runs the full convolutional part, so a GPU is strongly recommended. If you need many epochs, extract the features once and train on them, as in our experiment below.
    • With more data, unfreeze block 5 (model.features[24:]) and train it with a 10 times smaller learning rate.
    • The three FC layers hold 124 million parameters. Replacing them with global average pooling and one linear layer, as in the Keras example below, makes the model 9 times smaller, but in our test it cost accuracy: keep FC6 and FC7 if model size is not a problem.
    • To use VGG16 as a feature extractor, cut the classifier after FC7: model.classifier = model.classifier[:5] returns a 4,096-value vector per image.

    VGG16 in Keras

    In Keras, VGG16 is available as keras.applications.VGG16. Keras ships the original weights released by the Oxford team, converted from Caffe, so it needs the original preprocessing: preprocess_input converts RGB to BGR and subtracts the ImageNet mean of each channel, without scaling to 0–1. Do not mix this with the torchvision normalization: the result is still a valid image, but accuracy drops. Keras 3 runs on TensorFlow, JAX or PyTorch. We tested the code with Keras 3.15: the first example on the PyTorch backend, the second on TensorFlow 2.21, which image_dataset_from_directory uses to load images.

    Classify an image

    import os
    os.environ["KERAS_BACKEND"] = "torch"  # or "tensorflow" / "jax"
    
    import keras
    import numpy as np
    from keras.applications.vgg16 import VGG16, decode_predictions, preprocess_input
    
    model = VGG16(weights="imagenet")  # downloads 528 MB of weights on first run
    print(f"{model.count_params():,} parameters")
    
    img = keras.utils.load_img("dog.jpg", target_size=(224, 224))
    x = preprocess_input(np.expand_dims(keras.utils.img_to_array(img), 0))
    preds = model.predict(x, verbose=0)
    for _, label, prob in decode_predictions(preds, top=5)[0]:
        print(f"{label:<22}{prob:.3f}")

    Output for the sample photo of a Samoyed from the PyTorch Hub repository:

    138,357,544 parameters
    Samoyed               0.871
    Eskimo_dog            0.059
    white_wolf            0.019
    Siberian_husky        0.010
    wallaby               0.005

    Transfer learning with VGG16 in Keras

    With include_top=False the model contains only the 13 convolutional layers, 14.7 million parameters, and accepts any image of at least 32×32 pixels. A global average pooling layer turns the 7×7×512 feature map into 512 numbers, and a new softmax layer is trained on top.

    import keras
    from keras.applications.vgg16 import VGG16, preprocess_input
    
    train_ds, val_ds = keras.utils.image_dataset_from_directory(
        "pets/train", image_size=(224, 224), batch_size=32,
        validation_split=0.2, subset="both", seed=42)
    num_classes = len(train_ds.class_names)
    
    base = VGG16(weights="imagenet", include_top=False, input_shape=(224, 224, 3))
    base.trainable = False                       # freeze all 13 convolutional layers
    
    inputs = keras.Input(shape=(224, 224, 3))
    x = keras.layers.RandomFlip("horizontal")(inputs)
    x = preprocess_input(x)                      # RGB -> BGR and mean subtraction, as in the original model
    x = base(x, training=False)
    x = keras.layers.GlobalAveragePooling2D()(x) # 512 values instead of 25,088
    x = keras.layers.BatchNormalization()(x)     # VGG16 features are large (tens to hundreds): rescale them
    x = keras.layers.Dropout(0.3)(x)
    outputs = keras.layers.Dense(num_classes, activation="softmax")(x)
    model = keras.Model(inputs, outputs)
    
    model.compile(optimizer=keras.optimizers.Adam(1e-3),
                  loss="sparse_categorical_crossentropy", metrics=["accuracy"])
    model.fit(train_ds, validation_data=val_ds, epochs=10)
    print(f"trainable parameters: {sum(w.numpy().size for w in model.trainable_weights):,}")

    The VGG16 activations are large, tens to hundreds, because the original weights work with pixel values from 0 to 255. The batch normalization layer rescales them; without it, the first epochs of training are unstable. This is the most common setup and keeps the model small, but in our experiment below the features of the fully connected layers were more accurate, especially with few images. To use them, load the full model and take the output of FC7: base = VGG16(weights="imagenet"), then features = keras.Model(base.input, base.get_layer("fc2").output), and put features in place of base without the pooling and batch normalization layers. Compare PyTorch and TensorFlow if you are choosing a framework.

    Experiment: VGG16 features vs newer networks

    Most people use VGG16 today as a pretrained feature extractor. We checked how good its features are compared with newer networks. As a test we took the Oxford-IIIT Pet dataset: photos of 37 breeds of cats and dogs, created in 2012 by the same Oxford group together with IIIT Hyderabad. Breeds are hard to tell apart, which makes the task harder than classifying generic objects.

    Setup. 50 training and 50 test photos per breed, 1,850 + 1,850 in total, chosen at random with a fixed seed. Each network was frozen; we extracted features once and trained logistic regression on top (a linear probe), choosing the regularization strength by 5-fold cross-validation on the training set. We then repeated the training with only 5, 10 and 20 photos per breed, averaging over five random draws. All computation ran on a 2-core CPU with PyTorch 2.15.

    Networks. VGG16 with the original Oxford weights, from three layers: the last convolutional block with global average pooling (512 values), FC6 and FC7 (4,096 values each). ResNet-50 trained with the “ResNet strikes back” recipe (80.4% ImageNet top-1), EfficientNet-B0 trained with RandAugment (77.7%) and ViT-B/16 pretrained by Google on ImageNet-21k, 14 million images. The ViT therefore saw ten times more data than the others; it is included as an example of a modern transformer backbone.

    Network and layer Feature size CPU time per image 5 photos per breed 10 20 50
    VGG16, last conv block + average pooling 512 238 ms 65.9% 75.6% 81.6% 86.2%
    VGG16, FC6 4,096 238 ms 79.0% 85.1% 87.7% 90.6%
    VGG16, FC7 4,096 238 ms 82.6% 87.1% 89.1% 90.5%
    ResNet-50 2,048 91 ms 86.8% 90.1% 92.4% 94.3%
    EfficientNet-B0 1,280 30 ms 86.4% 90.7% 91.6% 92.9%
    ViT-B/16, ImageNet-21k 768 232 ms 87.8% 91.0% 91.9% 92.7%
    Line chart: test accuracy on Oxford-IIIT Pet vs training photos per breed for frozen VGG16, ResNet-50, EfficientNet-B0 and ViT-B/16 features
    Accuracy of a linear classifier on frozen features, Oxford-IIIT Pet, 37 breeds. Our experiment

    What the results show:

    • Take VGG16 features from the fully connected layers. FC7 and FC6 gave 90.5% and 90.6% with 50 photos per breed, the last convolutional block with average pooling only 86.2%. With 5 photos per breed the gap grows to 17 points (82.6% vs 65.9%), likely because average pooling discards where features are in the image, while FC6 sees all 7×7 positions.
    • Newer CNNs are better at every training-set size. ResNet-50 reached 94.3% and EfficientNet-B0 92.9%. VGG16 makes 1.7 times as many mistakes as ResNet-50, and with 5 photos per breed it is 4 points behind.
    • Cheaper, too. EfficientNet-B0 extracts features 8 times faster than VGG16 on a CPU, and its feature vector is 3 times shorter: 1,280 values instead of 4,096.
    • The transformer wins only with very little data. ViT-B/16 pretrained on ImageNet-21k was the best with 5 photos per breed, 87.8%, but with 50 photos it reached 92.7%, on par with EfficientNet-B0 and behind ResNet-50. It needs about as much computation as VGG16 and is still 2 points more accurate.
    • A caveat. ImageNet-1k already contains many of these dog and cat breeds, which is why all networks score high here. On images unlike ImageNet, such as medical scans or satellite photos, the ranking can change, so test a few backbones on your own data.

    VGG16 vs modern architectures

    The table compares VGG16 with networks that replaced it. Accuracy, parameters and operations are from torchvision’s model table; CPU time is our measurement for one 224×224 image on a 2-core CPU (PyTorch 2.15, median of 10 runs).

    Model Year Parameters GMACs ImageNet top-1 CPU, ms per image Weights, MB
    AlexNet 2012 61.1M 0.71 56.5% – 233
    VGG16 2014 138.4M 15.5 71.6% 238 528
    VGG19 2014 143.7M 19.6 72.4% 293 548
    ResNet-50 2015 25.6M 4.1 76.1% (80.9% with newer weights) 91 97
    MobileNetV3-Large 2019 5.5M 0.22 75.3% 19 21
    EfficientNet-B0 2019 5.3M 0.39 77.7% 30 20
    ViT-B/16 2020 86.6M 17.6 81.1% 232 330
    ConvNeXt-Tiny 2022 28.6M 4.5 82.5% 77 109
    Scatter plot of ImageNet top-1 accuracy vs CPU time per image for VGG16, VGG19, ResNet-50, EfficientNet-B0, MobileNetV3, ConvNeXt-Tiny and ViT-B/16
    VGG16 and VGG19 are the slowest and the least accurate of these ImageNet models. Our measurement on a 2-core CPU

    ResNet-50 has 5.4 times fewer parameters and 3.8 times fewer operations than VGG16, runs 2.6 times faster on our CPU and is 4.5–9 points more accurate, depending on the weights. ConvNeXt-Tiny, a modern CNN that borrows ideas from transformers, is 11 points more accurate and 3 times faster. ViT-B/16 needs about as much computation as VGG16 but is almost 10 points more accurate. Three things explain the gap:

    • VGG spends its computation at high resolution. Blocks 1–3 run 64–256-channel convolutions on 224×224 to 56×56 feature maps. Later networks shrink the image quickly with a strided first layer and use bottleneck or depthwise convolutions.
    • No shortcuts and no normalization. Residual connections and batch normalization let ResNet train networks with 50 to 152 layers; VGG stopped improving at 19.
    • Training recipes improved. The same ResNet-50 architecture gains almost 5 points with torchvision’s newer weights, thanks to longer training and stronger augmentation. VGG16 never got such an update.

    The VGG idea did not disappear, though. RepVGG (CVPR 2021) trains a network with extra 1×1 and identity branches and then merges them into a plain stack of 3×3 convolutions and ReLUs for inference, a pure VGG-style network that runs fast on GPUs. It was the first plain model to pass 80% top-1 on ImageNet, and RepVGG-style blocks are used in the backbone of the YOLOv6 detector. For general-purpose image features in 2025–2026, the reference point is large pretrained backbones such as Meta’s DINOv3, a self-supervised Vision Transformer with up to 7 billion parameters trained on 1.7 billion images.

    Where VGG16 is used today

    Perceptual losses. This is where VGG is still everywhere. Instead of comparing two images pixel by pixel, a perceptual loss compares their VGG feature maps, which matches human judgement of similarity much better. Johnson and colleagues used VGG16 features for fast style transfer and super-resolution in 2016; SRGAN and ESRGAN use a “VGG loss” on VGG19 features. LPIPS, the most popular learned perceptual metric, has a VGG16 variant that compares five layers before pooling, and the autoencoder of Stable Diffusion was trained with this LPIPS loss. The code below shows the idea:

    import torch
    import torch.nn.functional as F
    from torchvision.models import vgg16, VGG16_Weights
    
    vgg = vgg16(weights=VGG16_Weights.IMAGENET1K_V1).features.eval()
    for p in vgg.parameters():
        p.requires_grad = False
    
    LAYERS = {3: "relu1_2", 8: "relu2_2", 15: "relu3_3", 22: "relu4_3"}  # indices in vgg.features
    MEAN = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
    STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
    
    
    def vgg_features(img):                 # img: (B, 3, H, W), values in [0, 1]
        x, feats = (img - MEAN) / STD, []
        for i, layer in enumerate(vgg[:23]):
            x = layer(x)
            if i in LAYERS:
                feats.append(x)
        return feats
    
    
    def perceptual_loss(output, target):
        return sum(F.mse_loss(a, b) for a, b in zip(vgg_features(output), vgg_features(target)))
    
    
    output = torch.rand(1, 3, 224, 224, requires_grad=True)  # e.g. the output of a super-resolution model
    target = torch.rand(1, 3, 224, 224)
    loss = perceptual_loss(output, target)
    loss.backward()                                           # gradients flow back into the generator
    print(loss.item(), output.grad.shape)

    Neural style transfer. The original method by Gatys and colleagues (2015) separates the content and the style of an image using VGG19 features, and most tutorials still use VGG.

    Object detection and segmentation. VGG16 was the main backbone of the first strong deep detectors and segmenters: Faster R-CNN (2015), SSD (2016), FCN (2015) and SegNet, whose encoder repeats the 13 convolutional layers of VGG16. torchvision still includes ssd300_vgg16 (25.1 box mAP on COCO). U-Net variants such as TernausNet used VGG encoders pretrained on ImageNet. Modern detectors and segmentation models have moved to newer backbones.

    Teaching and applied projects. VGG16 is the easiest deep CNN to understand and implement, so it is a common baseline in courses and in student projects such as brain-tumor MRI or chest X-ray classification. For real applications, a ResNet, EfficientNet or ConvNeXt fine-tuned the same way usually gives better accuracy at a fraction of the cost.

    Audio and faces. VGGish, a VGG-like network from Google for audio, produces the embeddings used by the Fréchet Audio Distance, a standard metric for music and audio generators. The Oxford group also built VGGFace and the VGGFace2 dataset for face recognition.

    The lab itself. The Visual Geometry Group is still one of the leading computer vision labs. In 2025 its VGGT model, a transformer that reconstructs 3D scenes from one to hundreds of photos, won the best paper award at CVPR together with co-authors from Meta. VGGT has nothing in common with VGG16 except the name of the lab, but it explains why searches for “VGG” no longer lead only to the 2014 network.

    Limitations of VGG16

    • Size and speed. 528 MB of weights and 15.5 billion operations per image make VGG16 a poor fit for phones and edge devices. Even on a GPU, newer models give better accuracy for the same time.
    • Memory during training. Large high-resolution feature maps mean high memory use per image and small batches.
    • Fully connected head. 124 million parameters in three layers overfit small datasets, and the original classifier only accepts 224×224 inputs.
    • Limited depth. Without batch normalization and residual connections, plain VGG networks stop improving at about 19 layers and are hard to train from scratch.
    • Accuracy. 71.6% top-1 on ImageNet is far below the 80–90% of current models, and its features are weaker for transfer learning, as our experiment shows.

    FAQ

    What does VGG stand for?

    VGG stands for the Visual Geometry Group, the computer vision lab of the Department of Engineering Science at the University of Oxford where the network was developed. VGGNet is the common name for the family of networks from the 2014 paper: VGG11, VGG13, VGG16 and VGG19.

    Why is it called VGG16?

    Because it has 16 layers with learnable weights: 13 convolutional layers and 3 fully connected layers. The 5 max-pooling layers and the softmax are not counted.

    How many parameters does VGG16 have?

    138,357,544, or 138.4 million. The 13 convolutional layers have 14,714,688 parameters, which is the size of the model loaded with include_top=False in Keras; the three fully connected layers have 123,642,856.

    What is the input size of VGG16?

    224×224 pixels with 3 color channels. Without the fully connected layers the network accepts any size of at least 32×32. torchvision’s version has an adaptive pooling layer, so even the full model works with larger images.

    What is the difference between VGG16 and VGG19?

    VGG19 has three more convolutional layers, one each in blocks 3, 4 and 5: 16 convolutional layers instead of 13. It has 143.7 million parameters, needs 27% more computation and is only slightly more accurate: 72.4% vs 71.6% top-1 with torchvision weights.

    Is VGG16 better than ResNet-50?

    No. ResNet-50 has 5.4 times fewer parameters, needs 3.8 times fewer operations, is 4.5–9 points more accurate on ImageNet and gave better features in our transfer learning test. VGG16 is simpler to understand, which is why it is still popular in teaching.

    Is VGG16 still used in 2026?

    Yes, but mostly as a fixed feature extractor: in perceptual losses such as LPIPS, in style transfer and super-resolution, and in older detection pipelines. For new classification projects, newer backbones are faster and more accurate.

    Can VGG16 be used for object detection?

    Yes, as a backbone. Faster R-CNN and SSD were built on VGG16, and torchvision still provides ssd300_vgg16. Modern detectors such as the YOLO family use more efficient backbones.

    How long does it take to train VGG16?

    In 2014 training took 2–3 weeks on four NVIDIA Titan Black GPUs for 74 epochs on 1.3 million images. Today you almost never need to train it from scratch: fine-tuning only the classifier on a few thousand images takes minutes on a GPU.


    bnr2mob
    Subscribe
    Notify of
    guest

    51 Comments
    Oldest
    Newest Most Voted
    trackback

    […] will use VGG16 as our deep learning model. We could have trained our own model from ground up, but this takes time […]

    trackback

    […] Taken from: https://neurohive.io/en/popular-networks/vgg16/ […]

    trackback

    […] map) at shallow layer(conv-1) of each conv block. A typical pre-trained classification CNN like VGG16 is consist of a few conv blocks, which has 2 or 3 convolution(Conv2D) layers(conv1,conv2… Read more »

    trackback

    […] map) at shallow layer(conv-1) of each conv block. A typical pre-trained classification CNN like VGG16 is consist of a few conv blocks, which has 2 or 3 convolution(Conv2D) layers(conv1,conv2… Read more »

    trackback

    […] המאומנות כמו VGG16, VGG19, Resnet101 ורבות אחרות נמצאות ברשת לשימוש הכל, עם […]

    trackback

    […] a predição em diferentes elevações. Para agilizar o treinamento, eles usaram a estrutura VGG-16 inicializada com pesos oriundos de um pré-treinamento no dataset ImageNet. A tarefa específica do […]

    trackback

    […] here’s some visualization of what the actual filters that pass over the images look like in a VGG16 network. (more specifically, an image on which the filter activates the… Read more »

    trackback

    […] here’s some visualization of what the actual filters that pass over the images look like in a VGG16 network. (more specifically, an image on which the filter activates the… Read more »

    trackback

    […] Nuerohive: Convolution Network for Classification and Detection  […]

    trackback

    […] Referencehttps://neurohive.io/en/popular-networks/vgg16/https://www.quora.com/What-is-the-VGG-neural-network […]

    trackback

    […] this topic have focused on learning from famous, high-performance deep learning networks, such as VGGNet-16, ResNet-50, or Inception-V3/V4, etc. These networks were trained on the massive ImageNet database, […]

    trackback

    […] have targeted on studying from well-known, high-performance deep studying networks, similar to VGGNet-16, ResNet-50, or Inception-V3/V4, and many others. These networks had been educated on the […]

    trackback

    […] the advancement of deep learning such as convolutional neural network (i.e., ConvNet) [1], computer vision becomes a hot scientific research topic again. One of the main goals of […]

    trackback

    […] of every picture within the coaching set are calculated utilizing a hidden layer of the pretrained VGG-16 convolutional neural community. A single absolutely related feed-forward layer is skilled to… Read more »

    trackback

    […] 20 novembre 2018 VGG16 è un modello di rete neurale convoluzionale proposto da K. Simonyan e A. Zisserman dell’Università di Oxford nel documento “Reti convoluzionali molto profonde per il… Read more »

    trackback

    […] features of each image in the training set are calculated using a hidden layer of the pretrained VGG-16 convolutional neural network. A single fully connected feed-forward layer is trained… Read more »

    trackback

    […] features of each image in the training set are calculated using a hidden layer of the pretrained VGG-16 convolutional neural network. A single fully connected feed-forward layer is trained… Read more »

    trackback

    […] ciascuno aspetto nel set nel corso di sono calcolate usando unico mano introvabile del pretrattatoVGG – 16 neurale convoluzionale. Un specifico calibro feed-forward del tutto collegato viene preparato verso… Read more »

    trackback

    […] [3] “VGG16 – Convolutional Network for Classification and Detection”. [Online]. Available: https://neurohive.io/en/popular-networks/vgg16/.&nbsp; […]

    trackback

    […] Layered architecture of VGG16 (Source) […]

    trackback

    […] will use the pre-trained AlexNet and VGG16. They both receive 224*224 (3 channel) as input, so we need to resize our image to 224*224. Because […]

    trackback

    […] An occasion of options at totally different ranges within the VGG-16 architecture […]

    trackback

    […] An instance of features at different levels in the VGG-16 architecture […]

    trackback
    trackback

    […] https://neurohive.io/en/popular-networks/vgg16/ — VGG16 – Convolutional Network for Classification and Detection (emphasis mine) […]

    trackback

    […] example, the neural nets, which can include VGG-16, RESNET-50, and others, have the following size when used as a tf.keras application (for example, […]

    trackback

    […] VGG16 – Convolutional network for classification and detection. (2018, November 21). Neurohive – Neural Networks. https://neurohive.io/en/popular-networks/vgg16/ […]

    trackback

    […] For image Detecting, we are using a pre-trained model which is VGG16. VGG16 is already installed in the Keras library.VGG 16 was proposed by Karen Simonyan and Andrew Zisserman… Read more »

    trackback

    […] This isn’t an easy question because this is a full separate paper on its own, but I will give you an idea of what it is. Encoder decoder frameworks… Read more »

    trackback

    […] This isn’t an easy question because this is a full separate paper on its own, but I will give you an idea of what it is. Encoder decoder frameworks… Read more »

    trackback

    […] We will first run the images through the VGG16 base model. VGG16 is a pre-trained model that takes in (224,224) RGB images and converts them into features. It comes… Read more »

    trackback

    […] We will first run the images through the VGG16 base model. VGG16 is a pre-trained model that takes in (224,224) RGB images and converts them into features. It comes… Read more »

    trackback

    […] a single image prediction faster, I could always resort to using a network with fewer layers like VGG16, […]

    trackback

    […] a single image prediction faster, I could always resort to using a network with fewer layers like VGG16, […]

    trackback

    […] of this algorithm is that it takes a large scale of enterprise logos from a database and, utilizing VGG16 for feature extraction, forms K clusters of visually similar […]

    trackback

    […] of this algorithm is that it takes a large scale of enterprise logos from a database and, utilizing VGG16 for feature extraction, forms K clusters of visually similar […]

    trackback

    […] I was able to find the VGG16 CNN model (For more information of VGG16 model: VGG16 Paper and Blog post) and implemented the VGG16 model provided by the Python Tensorflow and Keras.… Read more »

    trackback
    trackback

    […] [3] “VGG16 – Convolutional Network for Classification and Detection”. [Online]. Available: https://neurohive.io/en/popular-networks/vgg16/.  […]

    trackback

    […] [1] Detection of novel coronavirus from chest X-rays using deep convolu…[2] Fast coronavirus tests: what they can and can’t do[3] VGG16 – Convolutional Network for Classification and Detection […]

    trackback

    […] [1] Detection of novel coronavirus from chest X-rays using deep convolutional neural networks [2] Fast coronavirus tests: what they can and can’t do [3] VGG16 – Convolutional Network for Classification… Read more »

    trackback

    […] deep convolutional neural networks [2] Fast coronavirus tests: what they can and can’t do [3] VGG16 – Convolutional Network for Classification and DetectionSee […]

    trackback

    […] [1] Detection of novel coronavirus from chest X-rays using deep convolu…[2] Fast coronavirus tests: what they can and can’t do[3] VGG16 – Convolutional Network for Classification and Detection […]

    trackback

    […] is true that science never puts their feet apart from the chain of innovations and inventions. The VGG16 is similarly another invention by the industry’s intelligent performers, which led to the… Read more »

    trackback

    […] the Convolutional Neural Network (CNN) model being attacked in the above example is VGGFace (VGG-16), trained on Columbia University’s PubFig dataset. Other attack samples developed by the […]

    trackback

    […] Convolutional Neural Community (CNN) mannequin being attacked within the above instance is VGGFace (VGG-16), skilled on Columbia College’s PubFig dataset. Different assault samples developed by the […]

    trackback

    […] the Convolutional Neural Network (CNN) model being attacked in the above example is VGGFace (VGG-16), trained on Columbia University’s PubFig dataset. Other attack samples developed by the […]

    trackback

    […] Convolutional Neural Network (CNN) mannequin being attacked within the above instance is VGGFace (VGG-16), educated on Columbia College’s PubFig dataset. Different assault samples developed by the […]

    trackback

    […] Convolutional Neural Community (CNN) mannequin being attacked within the above instance is VGGFace (VGG-16), educated on Columbia College’s PubFig dataset. Different assault samples developed by the […]

    trackback

    […] the Convolutional Neural Network (CNN) model being attacked in the above example is VGGFace (VGG-16), trained on Columbia University’s PubFig dataset. Other attack samples developed by the […]