Sub topic 1
Why start from a pretrained model
Prerequisites
This chapter assumes you know basic Python and have used PyTorch tensors and nn.Module. You should understand loss, gradient descent, and epochs at a high level, and know that a convolutional neural network (CNN) learns visual features from pixels. You do not need to have trained a CNN from scratch.
Why pretrained weights help
A model trained from scratch must learn edges, textures, and shapes from your data alone. A model pretrained on ImageNet, a public set of about 1.2 million labeled photos, already has those features. Starting from its weights usually reaches useful accuracy with a few hundred images per class. Training from scratch on the same data tends to overfit.
Organizing and splitting your images
Put each class in its own sub-folder, then split the data into three sets:
data/
train/<class_name>/*.jpg
val/<class_name>/*.jpg
test/<class_name>/*.jpgSplit by source when you can, such as by photo session or photographer. Near-duplicate images that land in both train and validation inflate scores, which is called data leakage. Leave the test set untouched until the final evaluation.
Preprocessing and augmentation
Torchvision's pretrained models expect 224-pixel inputs normalized with the ImageNet mean and standard deviation. Training images also get random crops and flips, which is called augmentation. Validation images get only deterministic resizing, so scores are comparable across runs.
Loading data in batches
A DataLoader groups images into batches, shuffles training data each epoch, and loads files in parallel workers.
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
train_tfms = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
val_tfms = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
train_ds = datasets.ImageFolder("data/train", transform=train_tfms)
val_ds = datasets.ImageFolder("data/val", transform=val_tfms)
train_loader = DataLoader(train_ds, batch_size=32, shuffle=True, num_workers=4)
val_loader = DataLoader(val_ds, batch_size=32, shuffle=False, num_workers=4)
print(train_ds.classes)Choosing a pretrained architecture
Larger models are more accurate but slower and need more memory. For a small dataset, a mid-sized model is usually the best starting point.
| Model | Parameters | Relative speed | Typical use |
|---|---|---|---|
| ResNet-18 | about 11M | fastest | quick experiments, limited hardware |
| ResNet-50 | about 25M | moderate | general default |
| ConvNeXt-Tiny | about 28M | slower | higher accuracy when you have GPU time |
Exercise
Why should validation images skip RandomResizedCrop?
Show answer
Random crops change each image on every pass, so validation accuracy would vary between runs and would not show whether the model improved. A deterministic resize gives a stable score that you can compare across experiments.