TExcelTAD
Home › Computer Vision: Images to Detection, Segmentation & Tracking › Pretrained Classifiers and Transfer Learning for Vision

Pretrained Classifiers and Transfer Learning for Vision

The previous lesson measured what backbones cost. This one uses one that has been trained: ResNet-18 with its ImageNet weights, 11.7 million parameters fitted to 1.28 million labelled photos of 1,000 classes. Used as it is, it labels everyday photos out of the box, if the images are prepared exactly the way its training images were; small preprocessing mistakes change the answers without any error message, and the lesson measures how much. The second half is a decision guide for reusing such a backbone on your own task. The general theory and full worked fine-tuning runs are in Training Strategies (transfer learning, ResNet-18 on textures, feature extraction, partial fine-tuning); this lesson adds what is specific to images.

What the weights expect

A pretrained network is a function fitted to inputs of one particular form. For torchvision's ImageNet classifiers (IMAGENET1K_V1 weights) the evaluation recipe is:

  1. an RGB image (not BGR, not grey), as floats;
  2. resize so the shorter side is 256 pixels (keeping the aspect ratio), then centre-crop 224×224224 \times 224;
  3. scale to [0,1][0, 1], then normalise each channel with the ImageNet training-set statistics:
xc′=xc−μcσc,μ=(0.485, 0.456, 0.406),σ=(0.229, 0.224, 0.225)x'_c = \frac{x_c - \mu_c}{\sigma_c}, \qquad \mu = (0.485,\ 0.456,\ 0.406),\quad \sigma = (0.229,\ 0.224,\ 0.225)
  1. arrange as a (N, 3, 224, 224) tensor and call the model in eval() mode; the 1,000 outputs are logits, and the softmax turns them into probabilities.

ResNet18_Weights.IMAGENET1K_V1.transforms() returns exactly this pipeline, and .meta["categories"] the 1,000 class names. The example implements the recipe by hand (with OpenCV, as you would in a deployment without torchvision), compares it with the official transform, and classifies four sample images from scikit-image (public-domain or CC0 photos): a cat, a cup of coffee, an astronaut and a rocket.

python · try it yourself
import numpy as np, cv2
import torch
from torchvision.models import resnet18, ResNet18_Weights
from skimage import data

weights = ResNet18_Weights.IMAGENET1K_V1
model = resnet18(weights=weights).eval()
names = weights.meta["categories"]
MEAN, STD = np.array([0.485, 0.456, 0.406]), np.array([0.229, 0.224, 0.225])

def preprocess(rgb):
    """RGB uint8 (H, W, 3) -> normalised (3, 224, 224) tensor: resize shorter side to 256, centre crop 224."""
    h, w = rgb.shape[:2]
    s = 256 / min(h, w)
    img = cv2.resize(rgb, (round(w * s), round(h * s)), interpolation=cv2.INTER_AREA)
    h, w = img.shape[:2]
    top, left = (h - 224) // 2, (w - 224) // 2
    img = img[top:top + 224, left:left + 224] / 255.0
    return torch.tensor(((img - MEAN) / STD).transpose(2, 0, 1), dtype=torch.float32)

images = {n: getattr(data, n)() for n in ["chelsea", "coffee", "astronaut", "rocket"]}
batch = torch.stack([preprocess(im) for im in images.values()])
official = torch.stack([weights.transforms()(torch.tensor(im).permute(2, 0, 1)) for im in images.values()])
with torch.no_grad():
    p_mine = model(batch).softmax(1)
    p_official = model(official).softmax(1)
print("max difference between the two pipelines' probabilities:", f"{(p_mine - p_official).abs().max().item():.3f}")
for name, a, b in zip(images, p_mine, p_official):
    print(f"  {name:9s} top-1 OpenCV INTER_AREA: {names[a.argmax()]:12s} {a.max().item():.3f} | "
          f"torchvision bilinear: {names[b.argmax()]:12s} {b.max().item():.3f}")
for name, p in zip(images, p_mine):
    top = p.topk(5)
    print(f"\n{name} {images[name].shape[:2]}:")
    for prob, idx in zip(top.values, top.indices):
        print(f"  {prob.item():.3f}  {idx.item():3d} {names[idx]}")
max difference between the two pipelines' probabilities: 0.045
  chelsea   top-1 OpenCV INTER_AREA: tiger cat    0.414 | torchvision bilinear: Egyptian cat 0.391
  coffee    top-1 OpenCV INTER_AREA: espresso     0.889 | torchvision bilinear: espresso     0.852
  astronaut top-1 OpenCV INTER_AREA: reel         0.088 | torchvision bilinear: stethoscope  0.114
  rocket    top-1 OpenCV INTER_AREA: obelisk      0.505 | torchvision bilinear: obelisk      0.481

chelsea (300, 451):
  0.414  282 tiger cat
  0.345  285 Egyptian cat
  0.235  281 tabby
  0.005  287 lynx
  0.000  283 Persian cat

coffee (400, 600):
  0.889  967 espresso
  0.036  960 chocolate sauce
  0.022  925 consomme
  0.019  809 soup bowl
  0.016  968 cup

astronaut (512, 512):
  0.088  758 reel
  0.071  823 stethoscope
  0.051  542 drumstick
  0.034  560 football helmet
  0.034  570 gasmask

rocket (427, 640):
  0.505  682 obelisk
  0.167  657 missile
  0.153  812 space shuttle
  0.103  744 projectile
  0.031  540 drilling platform

Four lessons in one output:

  • The two pipelines are not identical. Both follow the recipe, but OpenCV's INTER_AREA and torchvision's antialiased bilinear resize produce slightly different pixels, and the probabilities differ by up to 0.045. For the cat and the astronaut, whose top classes are close, that is enough to change the top-1 answer (tiger cat 0.414 against Egyptian cat 0.391). Use one resize function for training, evaluation and serving.
  • The cat is spread over three neighbouring classes: tiger cat 0.414, Egyptian cat 0.345, tabby 0.235. All three are domestic cats; ImageNet's fine-grained labels split them, and the top-5 accuracy that papers report exists because of such near-ties.
  • The coffee is an espresso with 0.889, and "cup" is fifth.
  • The astronaut gets nothing sensible: reel 0.088, stethoscope 0.071, a flat distribution. ImageNet has no "person" or "astronaut" class (people appear in it only as part of other classes, like "scuba diver"). A classifier can only answer with its own labels; the rocket, similarly, becomes an obelisk (0.505) before it becomes a missile (0.167) or a space shuttle (0.153). This is why you transfer the features and train your own head.

Preprocessing done wrong

Every item of the recipe is easy to get wrong in real code: OpenCV loads images as BGR, a data loader forgets the normalisation, someone feeds raw 0 to 255 values, or resizes every photo to 224×224224 \times 224 regardless of its aspect ratio. None of these raises an error, because the network accepts any tensor of the right shape. The example runs the same four images through five broken pipelines and compares the top-1 prediction and its probability with the correct one.

python · try it yourself
import numpy as np, cv2
import torch
from torchvision.models import resnet18, ResNet18_Weights
from skimage import data

weights = ResNet18_Weights.IMAGENET1K_V1
model = resnet18(weights=weights).eval()
names = weights.meta["categories"]
MEAN, STD = np.array([0.485, 0.456, 0.406]), np.array([0.229, 0.224, 0.225])

def resize_crop(rgb, short=256, crop=224):
    h, w = rgb.shape[:2]
    s = short / min(h, w)
    img = cv2.resize(rgb, (round(w * s), round(h * s)), interpolation=cv2.INTER_AREA)
    h, w = img.shape[:2]
    top, left = (h - crop) // 2, (w - crop) // 2
    return img[top:top + crop, left:left + crop]

def to_tensor(img, scale=255.0, normalise=True):
    x = img / scale
    if normalise:
        x = (x - MEAN) / STD
    return torch.tensor(x.transpose(2, 0, 1), dtype=torch.float32)

pipelines = {
    "correct": lambda im: to_tensor(resize_crop(im)),
    "BGR order": lambda im: to_tensor(resize_crop(im)[:, :, ::-1].copy()),
    "no normalisation": lambda im: to_tensor(resize_crop(im), normalise=False),
    "0..255, not /255": lambda im: to_tensor(resize_crop(im), scale=1.0),
    "squashed 224x224": lambda im: to_tensor(cv2.resize(im, (224, 224), interpolation=cv2.INTER_AREA)),
    "tiny 64x64 crop": lambda im: to_tensor(resize_crop(im, 73, 64)),
}
images = {n: getattr(data, n)() for n in ["chelsea", "coffee", "astronaut", "rocket"]}
with torch.no_grad():
    for pname, f in pipelines.items():
        p = model(torch.stack([f(im) for im in images.values()])).softmax(1)
        cells = [f"{names[i][:16]:16s} {v:.2f}" for v, i in zip(*p.max(1))]
        print(f"{pname:17s} | " + " | ".join(cells))
correct           | tiger cat        0.41 | espresso         0.89 | reel             0.09 | obelisk          0.50
BGR order         | Egyptian cat     0.91 | cup              0.21 | stethoscope      0.15 | obelisk          0.90
no normalisation  | Egyptian cat     0.38 | cup              0.14 | Petri dish       0.10 | obelisk          0.79
0..255, not /255  | dishwasher       1.00 | dishwasher       1.00 | folding chair    1.00 | hamper           1.00
squashed 224x224  | Egyptian cat     0.81 | espresso         0.99 | football helmet  0.07 | drilling platfor 0.60
tiny 64x64 crop   | tiger cat        0.87 | espresso         0.99 | chain saw        0.55 | dock             0.49

Every broken pipeline still produces confident-looking answers. BGR turns the cat into an Egyptian cat with 0.91 and the espresso into a cup; missing normalisation changes three of four answers; values in 0 to 255 push every image into a single wrong class (dishwasher, folding chair, hamper) with probability 1.00, the most dangerous failure because it looks certain. Squashing to 224×224224 \times 224 changes the shape of objects but keeps the coffee and raises its confidence to 0.99: aspect-ratio distortion is often tolerated for large central objects, and less so for thin ones. The tiny crop keeps two of the answers but turns the astronaut into a chain saw with 0.55. None of these mistakes would be caught by a shape check, so test a pipeline by comparing its predictions on a few known images with the reference preprocessing.

Resolution and grey images

Two practical questions come up in every project. What if my images are not 224 pixels? ResNet ends with global average pooling, so it accepts any input size, but its filters were trained on objects of the sizes that appear in 224×224224 \times 224 ImageNet crops. What if my images are grey (X-rays, thermal, document scans)? The first convolution expects 3 channels. There are two equivalent fixes: repeat the grey channel three times, or sum the first layer's weights over the colour axis and feed one channel. Since the convolution is linear, ∑cWc∗g=(∑cWc)∗g\sum_c W_c * g = (\sum_c W_c) * g when all three inputs are the same grey image gg, so the two give identical outputs, and the second saves a little compute. Note that the ImageNet normalisation then uses the grey image's own statistics per copy, which is fine because the network sees exactly what it would have seen with three equal channels.

python · try it yourself
import numpy as np, cv2
import torch
from torch import nn
from torchvision.models import resnet18, ResNet18_Weights
from skimage import data

weights = ResNet18_Weights.IMAGENET1K_V1
model = resnet18(weights=weights).eval()
names = weights.meta["categories"]
MEAN, STD = np.array([0.485, 0.456, 0.406]), np.array([0.229, 0.224, 0.225])

def prepared(rgb, short, crop):
    h, w = rgb.shape[:2]
    s = short / min(h, w)
    img = cv2.resize(rgb, (round(w * s), round(h * s)), interpolation=cv2.INTER_AREA)
    h, w = img.shape[:2]
    top, left = (h - crop) // 2, (w - crop) // 2
    img = img[top:top + crop, left:left + crop] / 255.0
    return torch.tensor(((img - MEAN) / STD).transpose(2, 0, 1), dtype=torch.float32)[None]

cat = data.chelsea()
print("chelsea at different input sizes (resize shorter side, centre crop):")
with torch.no_grad():
    for crop in [64, 112, 224, 320, 448]:
        p = model(prepared(cat, round(crop * 256 / 224), crop)).softmax(1)[0]
        v, i = p.max(0)
        print(f"  {crop:3d} x {crop:<3d} top-1 {names[i]:16s} {v.item():.3f} | tabby 281: {p[281].item():.3f}")

grey = cv2.cvtColor(cat, cv2.COLOR_RGB2GRAY)
g3 = np.repeat(grey[:, :, None], 3, axis=2)                    # grey repeated into 3 channels
proper = prepared(g3, 256, 224)                                # per-channel ImageNet normalisation
same = (proper * torch.tensor(STD, dtype=torch.float32)[:, None, None]
        + torch.tensor(MEAN, dtype=torch.float32)[:, None, None] - MEAN.mean()) / STD.mean()   # one mean/std for all 3
grey_model = resnet18(weights=weights).eval()
conv = nn.Conv2d(1, 64, 7, 2, 3, bias=False)
conv.weight.data = model.conv1.weight.data.sum(1, keepdim=True)   # sum the R, G, B filters
grey_model.conv1 = conv
with torch.no_grad():
    a, b, c = model(proper).softmax(1)[0], model(same).softmax(1)[0], grey_model(same[:, :1]).softmax(1)[0]
print(f"grey, 3 copies, per-channel stats : top-1 {names[a.argmax()]:12s} {a.max().item():.3f}")
print(f"grey, 3 copies, one mean and std  : top-1 {names[b.argmax()]:12s} {b.max().item():.3f}")
print(f"grey, 1 channel, summed conv1     : top-1 {names[c.argmax()]:12s} {c.max().item():.3f}")
print(f"largest probability difference, 3 copies vs summed conv1: {(b - c).abs().max().item():.1e}")
chelsea at different input sizes (resize shorter side, centre crop):
   64 x 64  top-1 tiger cat        0.870 | tabby 281: 0.009
  112 x 112 top-1 tabby            0.406 | tabby 281: 0.406
  224 x 224 top-1 tiger cat        0.414 | tabby 281: 0.235
  320 x 320 top-1 Egyptian cat     0.388 | tabby 281: 0.252
  448 x 448 top-1 tiger cat        0.366 | tabby 281: 0.263
grey, 3 copies, per-channel stats : top-1 Egyptian cat 0.855
grey, 3 copies, one mean and std  : top-1 Egyptian cat 0.838
grey, 1 channel, summed conv1     : top-1 Egyptian cat 0.838
largest probability difference, 3 copies vs summed conv1: 3.0e-07

The cat is "tiger cat" at most sizes, but the probabilities move: 0.870 at 64×6464 \times 64 (the network is very sure about a blurry thumbnail), "tabby" at 112 and "Egyptian cat" at 320. The probability of "tabby" itself grows from 0.009 at 64 pixels to 0.263 at 448 as the fur texture becomes visible. Size changes the answer even though the architecture accepts every size; fine-tuning at the resolution you will deploy at removes most of this effect. In grey, the cat becomes an Egyptian cat (0.855): colour carried part of the evidence. The summed first layer on one channel gives the same probabilities as three identical copies to within 3×10−73 \times 10^{-7}, floating-point rounding; using one mean and standard deviation for the three copies, which that trick needs, changes the top probability only from 0.855 to 0.838.

Reusing the backbone in detectors and segmenters

The same pretrained weights serve dense tasks too. torchvision's detection models build a feature pyramid network (FPN) on top of a ResNet: the outputs of layer1 to layer4 (strides 4 to 32) are projected to 256 channels and merged top-down, so every level has both fine positions and strong semantics. The detection and mask heads are new and trained on the target task; the backbone starts from ImageNet. resnet_fpn_backbone builds this from the cached ResNet-18 weights and lets you choose how many stages stay trainable (the rest are frozen, and every batch-norm layer is replaced by a frozen one, because detection batches are too small to estimate batch statistics):

python · try it yourself
import torch
from torchvision.models import ResNet18_Weights
from torchvision.models.detection.backbone_utils import resnet_fpn_backbone

backbone = resnet_fpn_backbone(backbone_name="resnet18", weights=ResNet18_Weights.IMAGENET1K_V1,
                               trainable_layers=2)              # layer3 and layer4 train, the rest is frozen
backbone.eval()
with torch.no_grad():
    feats = backbone(torch.zeros(1, 3, 512, 640))
for k, v in feats.items():
    print(f"level {k:5s} {tuple(v.shape)}  stride {512 // v.shape[2]}")
total = sum(p.numel() for p in backbone.parameters())
trainable = sum(p.numel() for p in backbone.parameters() if p.requires_grad)
print(f"parameters: {total:,} | trainable: {trainable:,} | frozen: {total - trainable:,}")
print("frozen batch norm in layer1:", type(backbone.body.layer1[0].bn1).__name__)
level 0     (1, 256, 128, 160)  stride 4
level 1     (1, 256, 64, 80)  stride 8
level 2     (1, 256, 32, 40)  stride 16
level 3     (1, 256, 16, 20)  stride 32
level pool  (1, 256, 8, 10)  stride 64
parameters: 13,774,016 | trainable: 13,092,864 | frozen: 681,152
frozen batch norm in layer1: FrozenBatchNorm2d

The FPN returns five levels of 256 channels for the 512×640512 \times 640 input: strides 4, 8, 16 and 32 from layer1 to layer4, plus a stride-64 level made by max pooling the top one, which helps with very large objects. Note the parameter split: with trainable_layers=2 only the stem, layer1 and layer2 are frozen, and they hold just 681,152 of the 13,774,016 parameters. Most parameters of a CNN sit in its last stages, where the channels are widest, so "freezing the early layers" saves little memory for the weights; it saves compute in the backward pass and, more importantly, keeps the generic low-level filters intact.

A decision guide for vision transfer

feature extractionfrozen backbone,linear head fine-tunetop stages or all,small learning rate partial fine-tunestrong augmentation; or acloser pretrained model fine-tune everythingconsider domain orself-supervised pretraining labelled images: few (hundreds) ... many (tens of thousands) similarto ImageNetdifferentdomain
  • Few labels, similar domain (product photos, animals, vehicles): start with feature extraction, embeddings from the frozen backbone and a linear classifier. It takes minutes on a CPU and is often good enough.
  • Many labels, similar domain: fine-tune; unfreeze the top stages first, then everything, with a learning rate 10 to 100 times smaller than for a new head (partial fine-tuning, fine-tuning recipe).
  • Different domain (X-rays, satellite images, microscopy, thermal, documents): the low-level filters (edges, textures) still transfer, the top stages less so. Fine-tune more of the network, augment strongly, and look for a backbone pretrained on images closer to yours, or pretrain on your own unlabelled images (self-supervised pretraining). ImageNet pretraining is still almost always better than random initialisation.
  • Input resolution: keep objects at roughly the sizes the backbone saw. For small objects in large images, crop or tile rather than shrinking the whole image to 224 pixels; fine-tuning at a higher resolution than pretraining usually helps (and costs compute quadratically).
  • Grey or extra channels: repeat grey into three channels (or sum the first layer's filters); for four or more channels (RGB + depth, multispectral), keep the RGB filters and initialise the new channels' filters with their mean, then fine-tune the first layer.
  • Detection and segmentation: you almost never train the backbone from scratch: build the detector on a pretrained backbone (as above), or better, start from a detector pretrained on COCO (YOLO).
  • Licences: pretrained weights carry the licence and the terms of the data they were trained on; check both before shipping a product (public, licensed and synthetic data).

Pitfalls

  • BGR input. OpenCV's imread returns BGR; convert with cv2.cvtColor(img, cv2.COLOR_BGR2RGB) before a model trained on RGB.
  • Missing or doubled normalisation, or 0 to 255 values: the network still answers, wrongly and often confidently.
  • Training and serving with different resizing (antialiasing on or off, different interpolation, crop vs squash): small, silent accuracy losses. Use the same function in both.
  • ImageNet labels as your labels. The 1,000 classes include 118 dog breeds and no "person" class; fine-grained labels like "sports car" or "minivan" may not match the classes you need. Transfer the features, train your own head.
  • train() mode at inference, or batch-norm statistics updated by a few small batches while fine-tuning a frozen backbone (ResNet-18 on textures shows the damage).
  • Reporting top-5 when the product uses top-1. Report the metric the application consumes.

Practice

  1. A pipeline loads images with cv2.imread, resizes to 224 x 224 and divides by 255. List what is wrong for a torchvision ImageNet model and fix it.
  2. Why does replacing conv1's weights by their sum over the colour axis give the same output as repeating a grey image three times, before normalisation is taken into account?
  3. You have 300 labelled chest X-rays. Which strategy from the grid would you try first, and what would you check?
Answer
  1. BGR to RGB is missing (cv2.cvtColor(img, cv2.COLOR_BGR2RGB)), the squash to 224 x 224 distorts the aspect ratio (resize the shorter side to 256, centre-crop 224), and the ImageNet mean and standard deviation are not applied after dividing by 255.
  2. Convolution is linear in its input: the output is ∑cWc∗xc\sum_c W_c * x_c. If every xcx_c equals the same image gg, this is ∑cWc∗g=(∑cWc)∗g\sum_c W_c * g = (\sum_c W_c) * g, a single-channel convolution with the summed kernel. With per-channel normalisation the three copies differ slightly, so the exact equivalent first normalises the grey image per channel (or folds the normalisation into the weights and bias).
  3. Few labels and a different domain: start with a frozen backbone as a baseline (fast, shows how much transfers), then fine-tune the top stages with augmentation suitable for X-rays (small rotations and contrast changes; no flips if left and right matter). Check performance per subgroup and per hospital or device, and split by patient, never by image.

Test yourself

Which preprocessing does torchvision's ResNet-18 ImageNet model expect?

  1. BGR, 0 to 255, any size
  2. RGB, shorter side 256 then a 224 x 224 centre crop, scaled to 0-1 and normalised with the ImageNet mean and standard deviation
  3. Grey, 28 x 28
  4. RGB, 0 to 255, no normalisation

An image is passed to an ImageNet classifier in BGR order instead of RGB. What happens?

  1. An error is raised
  2. The model still returns predictions, often less confident or different, because its filters were fitted to RGB colour statistics
  3. Nothing changes: CNNs ignore colour
  4. The output has 3 classes

You have 500 labelled product photos (similar to ImageNet photos) and a CPU. What is the sensible first approach?

  1. Train a ResNet-50 from scratch
  2. Feature extraction: embeddings from a frozen pretrained backbone and a linear classifier
  3. Fine-tune a ViT-L on a GPU cluster
  4. Use the ImageNet labels directly

Why does torchvision's resnet_fpn_backbone replace batch normalisation with frozen batch normalisation by default?

  1. Frozen BN is faster to train
  2. Detection batches are small (a few large images), so batch statistics would be noisy; the ImageNet statistics are kept fixed instead
  3. FPN has no batch norm
  4. To reduce the number of classes