Level 3 In-Depth AI · Vision, Audio and Multimodal
Image Classification
Give a model a picture and it says what is in it, chosen from a fixed list of classes. This is the founding task of deep learning for vision, and the place to learn the full workflow from pixels to predictions, including how to reuse a model someone else has already trained.
- Level
- ●●●●● Easy
- Reading
- 11 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 17 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 17 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- Supervised Learning
- Images as Data
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Convolutional Neural Networks
- Image Classification
Read them roughly in this order. See it on the concept map →
Why it matters
Image classification means assigning one label from a fixed list to a whole image: "cat", "dog", "pneumonia", "no pneumonia", "ripe", "unripe". It sounds modest, but it was the task on which deep learning first proved itself. In 2012 a convolutional network called AlexNet won the ImageNet competition by a margin so large that the whole field changed direction within two years (A Short History of AI tells that story).
Classification is still everywhere. Phones sort photos by what is in them. Factories reject faulty parts on the production line. Doctors get second opinions on skin lesions and retinal scans. Farmers identify plant diseases from a photo. And the networks trained for classification became the backbones of nearly everything else in vision: Object Detection, Image Segmentation, image–text models and the vision parts of multimodal chatbots all start from a network that was first trained, or pretrained, to classify.
This chapter takes you through the whole workflow: the standard datasets, how a classifier turns pixels into probabilities, how to measure it, and how to get a good classifier for your own problem with very little data by starting from a pretrained one.
The intuition
Think of how a child learns to tell cats from dogs. Nobody gives them a rule like "pointy ears plus whiskers means cat". They see hundreds of examples with the right word attached, and gradually notice which visual features matter. A classifier learns the same way: from many labelled examples, by gradient descent.
The network itself is a pipeline with two parts:
- A backbone that turns the image into a list of numbers describing it. Early layers respond to edges and colour blobs, middle layers to textures and parts, and late layers to whole object parts such as eyes, wheels or petals. This is the Convolutional Neural Networks feature hierarchy.
- A head, usually a single linear layer, that turns those features into one score per class. A softmax turns the scores into probabilities that add up to 1.
The prediction is the class with the highest probability. The probabilities also tell you how sure the model is, although, as we'll see, not always honestly.
Key idea A classifier is a backbone that turns pixels into features plus a head that turns features into class probabilities. In practice you rarely train the backbone from scratch: you borrow one pretrained on millions of images and train a new head for your classes.
How it works
The standard datasets
Progress in classification was driven by shared benchmark datasets, and their names come up constantly:
| Dataset | Images | Size | Classes | Notes |
|---|---|---|---|---|
| MNIST | 70,000 | 28 × 28 grey | 10 digits | The "hello world" of vision. Easy: simple CNNs exceed 99% accuracy. |
| CIFAR-10 | 60,000 | 32 × 32 colour | 10 objects | Planes, cars, birds, cats… Tiny, but hard enough to be interesting. |
| ImageNet (ILSVRC-2012) | about 1.28 million training, 50,000 validation | variable, usually resized to 224 × 224 | 1,000 | The benchmark that launched modern deep learning. |
This chapter's code uses scikit-learn's built-in digits dataset: 1,797 images of 8 × 8 pixels, a miniature MNIST that needs no download.
From scores to probabilities
The head outputs one raw score, or logit, per class . Softmax converts them into probabilities:
Here is the number of classes and is the exponential function. Exponentiating makes every score positive, and dividing by the total makes them add up to 1. A bigger score always gives a bigger probability.
Training minimises the cross-entropy loss, which for one example is minus the log of the probability given to the correct class:
where is the true class. If the model gives the right class probability 0.8, the loss is . At 0.19, the loss is . The loss punishes confident mistakes hardest, and Backpropagation pushes the weights to raise .
Measuring it: top-1 and top-5
Top-1 accuracy is the fraction of test images whose highest-probability class is correct. It is plain accuracy.
Top-5 accuracy counts a prediction as correct if the true class is anywhere among the model's five most likely classes. It was ImageNet's headline metric because many images legitimately contain several objects, and many of the 1,000 classes are hard to tell apart even for people (ImageNet has more than a hundred dog breeds). An image labelled "laptop" that also shows a desk, a mug and a notebook isn't really a mistake if the model's first guess is "desk".
Worked example. Suppose the true class is "tabby cat" and the model's top five are: tiger cat (0.41), tabby cat (0.33), Egyptian cat (0.12), lynx (0.05), remote control (0.02). Top-1 is wrong, because the first guess is tiger cat. Top-5 is right, because tabby cat is in the list. Across a test set you simply average these hits.
Some reference points. In 2012 AlexNet reached a top-5 error of 15.3%, against 26.2% for the best non-deep entry. By 2015 a ResNet ensemble reached 3.57%. A careful human labeller, Andrej Karpathy, measured his own top-5 error at about 5.1%. Top-1 accuracy is the number usually quoted today. A standard ResNet-50 gets about 76% to 81% top-1, depending on the training recipe. As of late 2026, the best models, pretrained on far larger datasets, get roughly 90–91%.
For your own problems, accuracy is often not enough. With imbalanced classes (say 1% of X-rays show disease) a model that always says "healthy" is 99% accurate and useless. Look at the confusion matrix, precision and recall per class.
Variants of the task
- Multi-label classification: an image can have several labels at once ("beach", "sunset", "people"). Replace softmax with one independent sigmoid per class, and cross-entropy with binary cross-entropy per class.
- Fine-grained classification: telling apart very similar classes, such as 200 bird species or car models by year. It needs higher resolution and more data per class.
- Binary classification: two classes, such as defect or no defect. It is often framed with a single sigmoid output and a tuned decision threshold.
Transfer learning: the practical path
Training a ResNet-50 on ImageNet from scratch takes about 90 passes over 1.28 million images, and days on a single GPU. You almost never need to. A backbone trained on ImageNet has learned general features (edges, textures, shapes and object parts) that are useful for nearly any photo. Transfer learning reuses them:
- Load a pretrained model.
- Replace its final layer with a new one with as many outputs as you have classes.
- Either freeze the backbone and train only the new head (feature extraction), or fine-tune everything with a small learning rate, roughly 10 times smaller than for training from scratch.
With a few hundred labelled images per class this routinely gets accuracy that training from scratch would need tens of thousands of images to reach. It is the single most useful trick in applied computer vision.
In code
A complete classifier trained from scratch on scikit-learn's digits, with top-1 and top-3 accuracy. It runs on a laptop CPU in a few seconds.
import torch
import torch.nn as nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
torch.manual_seed(0)
digits = load_digits()
X = torch.tensor(digits.images, dtype=torch.float32).unsqueeze(1) / 16.0 # (1797, 1, 8, 8)
y = torch.tensor(digits.target)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y)
model = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2), # 16 x 4 x 4
nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2), # 32 x 2 x 2
nn.Flatten(), # 128
nn.Linear(128, 10), # 10 class scores
)
opt = torch.optim.Adam(model.parameters(), lr=1e-2)
loss_fn = nn.CrossEntropyLoss()
for epoch in range(15):
model.train()
for i in torch.randperm(len(X_train)).split(64): # mini-batches of 64
loss = loss_fn(model(X_train[i]), y_train[i])
opt.zero_grad(); loss.backward(); opt.step()
if epoch % 5 == 4:
model.eval()
with torch.no_grad():
acc = (model(X_test).argmax(1) == y_test).float().mean()
print(f"epoch {epoch + 1:2d} loss {loss.item():.3f} test accuracy {acc:.3f}")
with torch.no_grad():
logits = model(X_test)
probs = logits.softmax(dim=1)
print("predicted", probs[0].argmax().item(), "with p =", round(probs[0].max().item(), 3), "| true", y_test[0].item())
top3 = logits.topk(3, dim=1).indices
top1 = (top3[:, 0] == y_test).float().mean()
top3_acc = (top3 == y_test[:, None]).any(dim=1).float().mean()
print(f"top-1 {top1:.3f} top-3 {top3_acc:.3f}")
# epoch 5 loss 0.004 test accuracy 0.951
# epoch 10 loss 0.031 test accuracy 0.980
# epoch 15 loss 0.000 test accuracy 0.984
# predicted 2 with p = 0.999 | true 2
# top-1 0.984 top-3 1.000
For real photos, start from a pretrained model. With torchvision (this downloads about 100 MB of weights the first time, and dog.jpg is any photo):
import torch
from PIL import Image
from torchvision.models import resnet50, ResNet50_Weights
weights = ResNet50_Weights.DEFAULT # best available ImageNet weights
model = resnet50(weights=weights).eval()
preprocess = weights.transforms() # the exact resize/crop/normalise it was trained with
img = Image.open("dog.jpg").convert("RGB")
with torch.no_grad():
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]:20s} {p:.3f}")
And the transfer-learning recipe for your own five classes. Freeze the backbone, swap the head, and train only the head with the same loop as above:
import torch.nn as nn
from torchvision.models import resnet50, ResNet50_Weights
model = resnet50(weights=ResNet50_Weights.DEFAULT)
for p in model.parameters():
p.requires_grad = False # freeze the backbone
model.fc = nn.Linear(model.fc.in_features, 5) # new head: 2048 features -> 5 classes
opt = torch.optim.AdamW(model.fc.parameters(), lr=1e-3)
Common pitfalls
- Wrong preprocessing for a pretrained model. Use the weights' own transforms (
weights.transforms()in torchvision, or the model's processor in Hugging Face). Different resizing or normalisation silently costs accuracy. See Images as Data. - Forgetting
model.eval(). Batch normalisation and Dropout and Regularizing Neural Networks behave differently in training and evaluation mode. Predictions made in training mode are noisy and usually worse. - Leakage between train and test. Near-duplicate photos (burst shots, the same patient on two days, frames of one video) split across training and test sets inflate the score. Split by patient, by video or by date. See Training, Validation and Test Sets.
- Shortcut learning. Models latch onto whatever separates the classes most easily. One well-known kind of failure: a pneumonia detector that partly learns which hospital's scanner took the image, because the hospitals had different disease rates. Check what the model looks at, and test on data from a new source.
- Overconfident probabilities. Modern networks are often too confident: "0.99" may be right only 90% of the time. If decisions depend on the number, check calibration.
- Class imbalance. Report per-class recall, not just accuracy, and consider weighting the loss or resampling.
Watch out A classifier always answers with one of its classes, even for an image that belongs to none of them. Show a cat-versus-dog model a photo of a toaster and it will confidently say "dog". If unexpected inputs are possible, add an "other" class with examples, or reject predictions below a confidence threshold that you have tested.
Where it leads
- Classic CNN Architectures: LeNet to ResNet covers the backbones that won ImageNet year after year: AlexNet, VGG, Inception, ResNet, EfficientNet and ConvNeXt.
- Data Augmentation is the cheapest way to make a classifier more accurate and more robust.
- Object Detection and Image Segmentation extend classification to where objects are, not just what.
- Vision Transformers replace the convolutional backbone with a Transformer.
- CLIP and Contrastive Learning removes the fixed list of classes entirely, so you can classify with any text label you like ("zero-shot").
- Transfer Learning goes deeper into freezing, fine-tuning and choosing what to reuse.
A bit of history
Yann LeCun and colleagues trained convolutional networks to read handwritten digits at Bell Labs from the late 1980s. Their LeNet read cheques in American banks in the 1990s, and the MNIST dataset (1998) came from that line of work. Through the 2000s, though, the best image classifiers used hand-designed features such as SIFT and HOG, fed into support vector machines.
Fei-Fei Li's team built ImageNet from 2007 to 2009, labelling millions of images through crowd-sourcing, and the yearly ImageNet Large Scale Visual Recognition Challenge (ILSVRC) started in 2010. In 2012, Alex Krizhevsky, Ilya Sutskever and Geoffrey Hinton's AlexNet, a CNN trained on two gaming GPUs, cut the top-5 error from 26.2% to 15.3%. Within three years ResNet had beaten the human estimate, and the competition ended in 2017. Around the same time, transfer learning from ImageNet became the default recipe for applied vision, and from 2020 onwards vision Transformers and image–text pretraining extended it further.
Try it
- Replace the CNN in the digits code with a plain
nn.Sequential(nn.Flatten(), nn.Linear(64, 10))(a softmax regression). How much test accuracy do you lose?- Train with only 10% of the training set (
X_train[:135]). What happens to test accuracy, and to the gap between the training loss and the test result?- Harder: print the confusion matrix with
sklearn.metrics.confusion_matrix(y_test, model(X_test).argmax(1)). Which digits get confused with which?Hint for 3: rows are true digits and columns are predictions, so look at the largest numbers off the diagonal. With the seed above, most of the few mistakes are 8s predicted as something else, usually 1.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Stanford CS231n: Deep Learning for Computer Vision
Famous course notes on neural nets, backprop, CNNs and training, written very clearly.
Practical Deep Learning for Coders
Top-down and code-first: you train state-of-the-art models in lesson one, then learn how they work. It suits programmers.
Transfer Learning for Computer Vision Tutorial
Official PyTorch tutorial: fine-tune a pretrained ResNet, or use it as a frozen feature extractor, on a small ants-versus-bees dataset.
timm (PyTorch Image Models)
A library of hundreds of pretrained image backbones with a uniform API, the usual starting point for vision transfer learning.
ImageNet: A Large-Scale Hierarchical Image Database
The dataset of millions of labelled images whose yearly competition became the proving ground for deep learning.
ImageNet Classification with Deep Convolutional Neural Networks
AlexNet: the GPU-trained CNN that won ImageNet by a huge margin and started the deep learning boom.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/image-classification.md