◆ AI All-in-One

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
↗ Plan a path here

Read first

Convolutional Neural NetworksImages as Data

This leads to

Data AugmentationObject DetectionVision Transformers
The full path from zero — 17 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Gradient Descent
  10. Tensors and Shapes
  11. Supervised Learning
  12. Images as Data
  13. Linear Regression
  14. The Perceptron
  15. Logistic Regression
  16. Neural Networks
  17. Convolutional Neural Networks
  18. 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.
Input1×8×8Conv+ReLU16×8×8Max pool16×4×4Conv+ReLU32×4×4Max pool32×2×2Flatten128Linear10 scoresSoftmaxprobabilities, sum to 1 0 1 2 3 4 5 6 7 8 9 “8” 0.80“1” 0.19 Backbone: feature extractorlearns edges, then strokes, then digit parts Head: classifierturns features into one score per class
Fig. 1 A tiny CNN classifying an 8 × 8 handwritten digit. Convolutions and pooling shrink the grid while adding channels, a linear layer gives 10 scores, and softmax turns them into probabilities. Here the model is 80% sure the digit is an 8 and 19% sure it is a 1 (real outputs of the code below).

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, zkz_k per class kk. Softmax converts them into probabilities:

pk=ezk∑j=1Kezjp_k = \frac{e^{z_k}}{\sum_{j=1}^{K} e^{z_j}}

Here KK is the number of classes and ee 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:

L=−log⁡pyL = -\log p_{y}

where yy is the true class. If the model gives the right class probability 0.8, the loss is −log⁡0.8≈0.22-\log 0.8 \approx 0.22. At 0.19, the loss is −log⁡0.19≈1.66-\log 0.19 \approx 1.66. The loss punishes confident mistakes hardest, and Backpropagation pushes the weights to raise pyp_y.

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:

1. Pretraining (done once, by someone else) ImageNet1.28 M photos Backbone (e.g. ResNet-50)≈ 23.5 M weights, learned features Head1000 classes tench, goldfish,… toilet tissue copy the weights throw away 2. Your task (an afternoon on a laptop) Your photose.g. 500 flowers Same backbonefrozen, or fine-tuned gently New head5 classes daisy, rose,tulip, … Feature extraction:freeze the backbone, train only the new head. Fast, needs little data.Fine-tuning:train everything with a small learning rate. Usually more accurate.
Fig. 2 Transfer learning. A backbone pretrained on ImageNet is copied, its 1,000-class head is thrown away, and a new head is trained for your own classes. You can freeze the backbone or fine-tune it gently.
  1. Load a pretrained model.
  2. Replace its final layer with a new one with as many outputs as you have classes.
  3. 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

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

  1. 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?
  2. 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?
  3. 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. The true class is "tabby cat". The model's top five guesses are tiger cat, tabby cat, Egyptian cat, lynx, remote control. How is this image scored?

  2. You have 300 labelled photos for each of your five product types. What is the most sensible way to build a classifier?

  3. A photo-tagging app must mark each image with every label that applies, such as "beach", "sunset" and "people" together. What should the output layer use?

  4. Only 1% of your X-rays show disease. A model reports 99% accuracy. What should you check before celebrating?

  5. A cat-versus-dog classifier is shown a photo of a toaster. What will it most likely do?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Practical Deep Learning for Coders

Jeremy Howard (fast.ai) · Beginner · Free

Top-down and code-first: you train state-of-the-art models in lesson one, then learn how they work. It suits programmers.

Tutorial

Transfer Learning for Computer Vision Tutorial

Sasank Chilamkurthy (PyTorch) · Beginner · Free

Official PyTorch tutorial: fine-tune a pretrained ResNet, or use it as a frozen feature extractor, on a small ants-versus-bees dataset.

Docs

timm (PyTorch Image Models)

Ross Wightman and Hugging Face · Intermediate · Free

A library of hundreds of pretrained image backbones with a uniform API, the usual starting point for vision transfer learning.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/image-classification.md