Sub topic 5
Choosing a pretrained architecture
This chapter helps you pick which pretrained model to start from. It assumes you know basic PyTorch, what a convolutional neural network does with an image, and the transfer-learning idea from the earlier chapters. You will compare the common torchvision families, read the numbers that matter, and learn how to swap models without breaking the rest of your pipeline.
What you are choosing
A pretrained architecture is a network design plus a set of weights learned on a large dataset, usually ImageNet-1k (about 1.28 million images in 1000 classes). In torchvision you pick both at once:
from torchvision import models
weights = models.ResNet18_Weights.DEFAULT
model = models.resnet18(weights=weights)The choice affects four things you will feel in practice:
- Accuracy ceiling. Larger or newer designs usually extract better features.
- Speed and memory. Training time, batch size and inference latency all scale with model size and input resolution.
- Adaptability. Some designs are easier to fine-tune on small datasets than others.
- Pipeline details. Each model expects a specific input size and normalization, and each has a different place where the classification head lives.
For most projects the right first choice is a small, well-understood model. You can move up later if the results justify it.
The main families
The table lists common torchvision options. Parameter counts and ImageNet top-1 accuracy are approximate and come from the torchvision model documentation. Check the current docs for exact figures, because they change with weight versions.
| Family | Example | Parameters | ImageNet top-1 | Character |
|---|---|---|---|---|
| ResNet | `resnet18` | 11.7M | about 70% | Simple, fast, very stable to fine-tune |
| ResNet | `resnet50` | 25.6M | about 80% (V2 weights) | Strong general default |
| MobileNet | `mobilenet_v3_large` | 5.5M | about 75% | Built for phones and CPUs |
| EfficientNet | `efficientnet_b0` | 5.3M | about 77% | Good accuracy per parameter |
| ConvNeXt | `convnext_tiny` | 28.6M | about 82% | Modern convnet, strong features |
| Vision Transformer | `vit_b_16` | 86.6M | about 81% | Needs more data and memory |
Some points follow from this table.
- Parameter count does not equal speed. EfficientNet has few parameters but many sequential, memory-heavy operations, so it can train more slowly than a ResNet with more parameters.
- Accuracy gains shrink as models grow. Going from 70% to 80% on ImageNet costs a lot of compute. On your own small dataset the gap often narrows further, because label noise and data limits become the bottleneck.
- Vision Transformers (ViTs) pretrained on ImageNet-1k are less forgiving than convnets when your dataset is small. They fine-tune well from large-scale pretraining, so check which weights you are loading.
Decision criteria
Work through these questions in order.
- Where will it run? For a phone or a CPU-only server, start with MobileNet or EfficientNet-B0. For a GPU server, anything in the table works.
- How much data do you have? With a few hundred images per class or fewer, prefer ResNet-18/50 or ConvNeXt-Tiny. Hold ViTs for larger datasets.
- What is your latency and memory budget? Larger models need smaller batch sizes. If
resnet50runs out of GPU memory at batch size 32, that is a signal to try a smaller model or a smaller batch, not a bug. - How similar is your data to ImageNet? Photos of everyday objects transfer easily. Medical scans, satellite images or microscopy transfer less directly, so a stronger model and more unfreezing often help.
A practical workflow is to train resnet18 first as a baseline. It trains quickly and shows whether your data and labels are sound. Then try one or two stronger models and keep the change only if validation accuracy improves clearly.
Weights versions and the matching transform
Each torchvision model offers named weight enums such as ResNet50_Weights.IMAGENET1K_V1 and ResNet50_Weights.IMAGENET1K_V2. The DEFAULT alias points to the best available set. The versions differ in how they were trained, and their recommended preprocessing can differ too. For example, V2 weights for ResNet-50 expect a resize to 232 before the crop, not 256.
Each weights object carries its own transform and metadata:
from torchvision import models
weights = models.ResNet50_Weights.DEFAULT
preprocess = weights.transforms()
print(preprocess)
print(weights.meta["categories"][:3])
print(weights.meta["_metrics"])weights.transforms() returns the exact resize, crop and normalization the weights were trained with. This is the safest way to build your validation transform. The earlier chapter used fixed values (resize 256, crop 224, ImageNet mean and standard deviation), which are correct for ResNet-18. For other models, read the transform from the weights object instead of copying numbers.
Be careful with the training transform. weights.transforms() is a deterministic evaluation pipeline. Keep your own random augmentation for training, and reuse the crop size and the mean and std values that the weights object reports.
from torchvision import models, transforms
weights = models.ConvNeXt_Tiny_Weights.DEFAULT
eval_tfms = weights.transforms()
# Reuse the model's normalization in the training pipeline.
size = eval_tfms.crop_size[0]
train_tfms = transforms.Compose([
transforms.RandomResizedCrop(size),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(eval_tfms.mean, eval_tfms.std),
])
print(size, eval_tfms.mean, eval_tfms.std)Input resolution matters beyond preprocessing. Most of these models were trained at 224 pixels. Feeding larger images can help with small details, but it increases compute roughly with the square of the side length. Vision Transformers with fixed position embeddings are stricter: vit_b_16 in torchvision requires 224 by 224 input unless you change the model.
Where the classification head lives
The head-replacement step from the next chapter depends on the architecture. The final layer has a different name and position in each family, and replacing the wrong attribute is a common error.
| Model | Head attribute | Replace with |
|---|---|---|
| ResNet | `model.fc` | `nn.Linear(model.fc.in_features, n)` |
| MobileNetV3 | `model.classifier[3]` | `nn.Linear(model.classifier[3].in_features, n)` |
| EfficientNet | `model.classifier[1]` | `nn.Linear(model.classifier[1].in_features, n)` |
| ConvNeXt | `model.classifier[2]` | `nn.Linear(model.classifier[2].in_features, n)` |
| ViT | `model.heads.head` | `nn.Linear(model.heads.head.in_features, n)` |
Here n is the number of classes. If you assign to the wrong attribute, PyTorch does not complain. The model keeps its 1000-class output, and your loss function then fails or silently trains on the wrong shape. Print the model, or call print(model.classifier), to see the last layers before you edit.
A helper keeps the choice in one place:
import torch.nn as nn
from torchvision import models
def build_model(name, num_classes):
if name == "resnet18":
m = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
m.fc = nn.Linear(m.fc.in_features, num_classes)
elif name == "efficientnet_b0":
m = models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.DEFAULT)
m.classifier[1] = nn.Linear(m.classifier[1].in_features, num_classes)
elif name == "convnext_tiny":
m = models.convnext_tiny(weights=models.ConvNeXt_Tiny_Weights.DEFAULT)
m.classifier[2] = nn.Linear(m.classifier[2].in_features, num_classes)
else:
raise ValueError(f"unknown model: {name}")
return m
model = build_model("efficientnet_b0", num_classes=5)
print(model.classifier)Freezing is architecture-specific as well. In a ResNet you unfreeze layer4. In EfficientNet and ConvNeXt the backbone is model.features, and you unfreeze its last blocks, for example model.features[-1]. The principle is the same: keep early layers frozen and open the last stage first.
Common mistakes
- Choosing by ImageNet rank alone. The best ImageNet model is not automatically best on your data. Compare on your validation set.
- Changing several things at once. If you switch architecture, learning rate and augmentation together, you cannot tell which change helped. Change one variable per experiment.
- Mismatched preprocessing. Using ResNet-18 numbers for a model that expects a different resize or normalization lowers accuracy without any error message.
- Ignoring batch normalization behavior. ResNet, MobileNet and EfficientNet use batch normalization (BatchNorm). Calling
model.train()updates its running statistics even in frozen layers, sincerequires_grad = Falsedoes not stop that. With very small batches, those statistics become noisy. If you freeze the backbone and want it fixed, put the BatchNorm layers in eval mode. ConvNeXt and ViT use LayerNorm, which has no such issue. - Comparing on the test set. Pick the architecture using the validation split. Touch the test split once, at the end.
A fair comparison
To compare two candidates fairly, hold everything else constant: the same splits, the same seed, the same number of epochs and the same augmentation. Record validation accuracy, validation loss, seconds per epoch and peak GPU memory. A small difference of one or two points may be noise, especially on a small validation set. Repeat with two or three seeds before you decide.
import time
import torch
def time_one_epoch(model, loader, criterion, optimizer, device):
if device.type == "cuda":
torch.cuda.reset_peak_memory_stats()
start = time.perf_counter()
model.train()
for images, labels in loader:
images, labels = images.to(device), labels.to(device)
loss = criterion(model(images), labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if device.type == "cuda":
torch.cuda.synchronize()
seconds = time.perf_counter() - start
peak_mb = torch.cuda.max_memory_allocated() / 1e6 if device.type == "cuda" else 0.0
return seconds, peak_mbThe synchronize call matters. GPU work runs asynchronously, so without it the timer can stop before the work finishes.
Exercise
You have 400 images per class across 6 classes and must deploy on a CPU-only server. A teammate suggests vit_b_16 because it has strong ImageNet accuracy. Which model would you try first, which attribute would you replace to set up a 6-class head, and how would you decide whether the ViT was worth trying later?
Show answer
Start with a small convnet such as efficientnet_b0 or resnet18. A ViT is large (about 87M parameters), slow on CPU, and less forgiving with a small dataset. For efficientnet_b0, replace model.classifier[1] with nn.Linear(model.classifier[1].in_features, 6). For resnet18, replace model.fc. Later, train the ViT with the same splits, seed, epochs and augmentation, and compare validation accuracy, seconds per epoch and CPU inference latency. Keep it only if the accuracy gain justifies the added cost, and never decide using the test set.
Exercise
You switch from ResNet-18 to ConvNeXt-Tiny but keep your old transform with resize 256, crop 224 and the numbers you copied from ResNet-18. Accuracy comes out lower than expected, with no error. What is the likely cause, and how do you fix it?
Show answer
The preprocessing may not match what the new weights were trained with. Read it from models.ConvNeXt_Tiny_Weights.DEFAULT.transforms(), and reuse its crop size, mean and standard deviation in both the training and validation pipelines. Then rerun the comparison.