Transfer Learning with a Pretrained ResNet-18
This lesson runs the transfer-learning workflow end to end on a real pretrained network: ResNet-18 trained on ImageNet (1.28 million photos, 1,000 classes), reused to classify six kinds of texture from only 6 example images per class.
The pretrained network
ResNet-18 is a convolutional network with 11.7 million parameters, organised in stages that halve the image size and widen the channels:
The global average pooling turns the last feature maps into one 512-number vector per image whatever the input size, and the final fc layer maps it to 1,000 ImageNet scores. Replacing fc by a layer gives a 6-class texture classifier with new parameters on top of 11.2 million pretrained ones.
The task and an honest split
Six images that ship with scikit-image, turned to grey: four surfaces (brick, grass, gravel, the moon) and two microscope images (cells, and a tissue stain). Examples are random 48 x 48 crops, 6 per class for training and 10 per class for testing. Training crops come from the left half of each picture and test crops from the right half, so no test pixel was ever seen in training; overlapping crops on both sides would make the test easy and the score optimistic.
Before reaching for a deep network, a classical baseline in your browser: local binary patterns (LBP), a hand-designed texture descriptor, summarised as a histogram per crop and fed to logistic regression. This is feature extraction too, with features designed by a person instead of learned.
import numpy as np
from skimage import data
from skimage.color import rgb2gray
from skimage.feature import local_binary_pattern
from sklearn.linear_model import LogisticRegression
rng = np.random.default_rng(0)
names = ["brick", "grass", "gravel", "moon", "cell", "immunohistochemistry"]
def grey(name): # 8-bit grey image
img = getattr(data, name)()
return (rgb2gray(img) * 255).astype(np.uint8) if img.ndim == 3 else img
def crops(img, n, left, size=48):
half = img.shape[1] // 2
out = []
for _ in range(n):
x = rng.integers(0, half - size) + (0 if left else half) # left or right half
y = rng.integers(0, img.shape[0] - size)
out.append(img[y:y + size, x:x + size])
return out
X_tr, y_tr, X_te, y_te = [], [], [], []
for c, name in enumerate(names):
img = grey(name)
for p in crops(img, 6, True): X_tr.append(p); y_tr.append(c)
for p in crops(img, 10, False): X_te.append(p); y_te.append(c)
def lbp_hist(patch):
codes = local_binary_pattern(patch, P=8, R=1, method="uniform") # 10 pattern codes
return np.bincount(codes.astype(int).ravel(), minlength=10) / codes.size
F_tr = np.array([lbp_hist(p) for p in X_tr]); F_te = np.array([lbp_hist(p) for p in X_te])
clf = LogisticRegression(max_iter=5000, C=100).fit(F_tr, y_tr)
print("train crops:", len(y_tr), "| test crops:", len(y_te))
print(f"LBP histogram + logistic regression: test accuracy {clf.score(F_te, y_te):.3f}")train crops: 36 | test crops: 60
LBP histogram + logistic regression: test accuracy 0.883
Ten numbers per crop (how often each of the 10 "uniform" local patterns occurs) already reach 0.883 on the 60 test crops. A baseline like this tells you how much a pretrained network has to add to be worth its cost.
Stage 1: replace the head, freeze, train the head
The recorded example builds the same crops (same seed, same order), turns each grey crop into three identical channels, and normalises with the ImageNet mean and standard deviation, because that is the input the pretrained weights expect. Then:
requires_grad = Falseon every pretrained parameter, so the optimiser cannot change them and no gradients are stored for them;- a new
nn.Linear(512, 6)asmodel.fc(new modules are trainable by default); - the backbone stays in
eval()mode. Batch-normalisation layers update their running mean and variance intrain()mode even when their weights are frozen, and a few batches of 8 crops would overwrite statistics estimated on ImageNet.
Stage 2: unfreeze the top stage
With a sensible head in place, layer4 (8.4 million parameters) is unfrozen and training continues with a learning rate 100 times smaller, so the pretrained features are adjusted rather than replaced. The batch-norm layers keep using their ImageNet statistics (eval() mode; their scale and shift parameters in layer4 still learn). For comparison, the same stage 2 is also run the careless way, with the whole model in train() mode. Finally, the same architecture trained from scratch on the same 36 crops gives the baseline. The whole run takes a few seconds on a CPU, because the crops are small and few.
import copy
import numpy as np
import torch
from torch import nn
from torchvision.models import resnet18, ResNet18_Weights
from skimage import data
from skimage.color import rgb2gray
rng = np.random.default_rng(0)
names = ["brick", "grass", "gravel", "moon", "cell", "immunohistochemistry"]
def grey(name):
img = getattr(data, name)()
return (rgb2gray(img) * 255).astype(np.uint8) if img.ndim == 3 else img
def crops(img, n, left, size=48):
half = img.shape[1] // 2
out = []
for _ in range(n):
x = rng.integers(0, half - size) + (0 if left else half)
y = rng.integers(0, img.shape[0] - size)
out.append(img[y:y + size, x:x + size])
return out
X_tr, y_tr, X_te, y_te = [], [], [], []
for c, name in enumerate(names):
img = grey(name).astype(np.float32) / 255
for p in crops(img, 6, True): X_tr.append(p); y_tr.append(c)
for p in crops(img, 10, False): X_te.append(p); y_te.append(c)
mean = torch.tensor([0.485, 0.456, 0.406])[:, None, None] # ImageNet statistics
std = torch.tensor([0.229, 0.224, 0.225])[:, None, None]
def to_tensor(patches):
x = torch.tensor(np.stack(patches))[:, None].repeat(1, 3, 1, 1) # grey -> 3 channels
return (x - mean) / std
X_tr, X_te = to_tensor(X_tr), to_tensor(X_te)
y_tr, y_te = torch.tensor(y_tr), torch.tensor(y_te)
def accuracy(model):
model.eval()
with torch.no_grad():
return (model(X_te).argmax(1) == y_te).float().mean().item()
def train(model, lr, epochs, backbone_eval):
params = [p for p in model.parameters() if p.requires_grad]
opt = torch.optim.Adam(params, lr=lr)
for _ in range(epochs):
model.train()
if backbone_eval: # keep ImageNet batch-norm statistics
model.eval()
for idx in torch.randperm(len(y_tr)).split(8):
xb = X_tr[idx].flip(3) if torch.rand(1).item() < 0.5 else X_tr[idx] # random mirror
loss = nn.functional.cross_entropy(model(xb), y_tr[idx])
opt.zero_grad(); loss.backward(); opt.step()
count = lambda m: sum(p.numel() for p in m.parameters() if p.requires_grad)
torch.manual_seed(0)
model = resnet18(weights=ResNet18_Weights.IMAGENET1K_V1)
print("pretrained parameters:", sum(p.numel() for p in model.parameters()))
for p in model.parameters():
p.requires_grad = False
model.fc = nn.Linear(512, 6) # replace the head
print("before training, test accuracy:", round(accuracy(model), 3))
train(model, lr=1e-2, epochs=10, backbone_eval=True)
print(f"stage 1 (head only) trainable {count(model):>9,} test accuracy {accuracy(model):.3f}")
for p in model.layer4.parameters(): # unfreeze the last stage
p.requires_grad = True
stage1 = copy.deepcopy(model)
train(model, lr=1e-4, epochs=5, backbone_eval=True)
print(f"stage 2 (+ layer4) trainable {count(model):>9,} test accuracy {accuracy(model):.3f}")
careless = stage1 # the same stage 2, but every layer in train() mode
train(careless, lr=1e-4, epochs=5, backbone_eval=False)
print(f"stage 2, BN in train mode test accuracy {accuracy(careless):.3f}")
torch.manual_seed(0)
scratch = resnet18(num_classes=6) # same architecture, random weights
train(scratch, lr=1e-3, epochs=15, backbone_eval=False)
print(f"from scratch trainable {count(scratch):>9,} test accuracy {accuracy(scratch):.3f}")pretrained parameters: 11689512
before training, test accuracy: 0.2
stage 1 (head only) trainable 3,078 test accuracy 0.983
stage 2 (+ layer4) trainable 8,396,806 test accuracy 0.983
stage 2, BN in train mode test accuracy 0.817
from scratch trainable 11,179,590 test accuracy 0.683
Before training, the random head is at chance (0.2 against ). Training 3,078 parameters for 10 epochs on 36 crops brings it to 0.983, one test crop wrong, far above both the hand-made LBP features (0.883) and the same network trained from scratch (0.683). Unfreezing layer4 keeps 0.983: on this small task the frozen features were already enough. The careless stage 2 drops to 0.817. Nothing about the weights' learning rate changed; in train() mode every batch-norm layer, including those in the frozen stages, replaced its ImageNet statistics with averages over batches of 8 texture crops, and at test time the network normalised its features with the wrong numbers.
What the numbers say, and what they do not
- 60 test crops is a small test set: each crop is about 0.017 of accuracy. The ranking (pretrained far above LBP, LBP above scratch) is clear; a difference of a crop or two between variants would need more test data, or several seeds, to claim.
- The test crops come from the same four photographs as the training crops, only from other regions. A model that has to recognise other brick walls and other lawns would face a harder test. Collecting test images from different sources is the honest next step.
- Training from scratch does poorly, as expected: 11 million parameters and 36 examples.
Pitfalls
- Wrong input statistics. Pretrained weights expect the normalisation and colour channels they were trained with. Forgetting the ImageNet mean and standard deviation or the three channels silently costs accuracy.
- Batch norm in train mode with a frozen backbone. Freezing weights does not freeze running statistics; keep frozen parts in
eval(). - Too large a learning rate after unfreezing. The rate that suits a random head (1e-2 here) destroys pretrained features. Use 10 to 100 times smaller, or one rate per parameter group.
- Optimiser built before unfreezing. An optimiser only updates the parameters it was given; build a new one (or add a parameter group) after changing
requires_grad. - Overlapping crops in train and test, or near-duplicate photos, inflate the score.
Practice
- How many parameters does the new head have for 10 classes?
- The example builds a new Adam optimiser in each call to
train. What would go wrong if stage 2 reused stage 1's optimiser? - Why mirror the crops at random during training but not at test time?
Answers
- .
- Stage 1's optimiser holds only
fc's parameters, so the unfrozenlayer4would get gradients but never be updated (and its learning rate would be the stage 1 rate). - Mirroring is data augmentation: a mirrored texture is still the same texture, so it adds training variety for free. At test time the goal is to measure the model on the real images, unchanged.
Test yourself
Why are the grey texture crops repeated into three channels and normalised with the ImageNet mean and standard deviation?
- To make the images look nicer
- Because the pretrained weights expect 3-channel inputs with exactly that normalisation
- Grey images cannot be classified
- To make training from scratch possible
The backbone's weights are frozen with requires_grad = False. What else must stay fixed so that the batch-normalisation layers keep their ImageNet behaviour?
- Nothing else
- The frozen part must be in
eval()mode, otherwise its running mean and variance are updated by the new batches - The learning rate must be 0
- The images must be 224 x 224
Why are training crops taken from the left half of each picture and test crops from the right half?
- To save memory
- So that no test pixel was seen during training, which would make the test score optimistic
- Because the right half is harder
- ResNet needs it