Deep learning in practice · lesson 13 of 13
Parts in this lesson
Adatasets.FashionMNIST("data", train=True, download=True)download the training set once, into the data folder
Brecord("all but " + trick, {**full, trick: False})an ablation: everything, minus one thing
Ctorch.save({"config": config, "model": model.state_dict()}, ...)7.11: save the settings with the weights

Project: a Fashion-MNIST classifier in PyTorch

Last updated

Fashion-MNIST is MNIST's harder sibling: 70,000 small greyscale photos of clothes, from T-shirts to ankle boots, in ten classes. In this project you'll train a deep network on it in PyTorch, add Stage 7's tricks one at a time, then take each one away again to find out which ones really earned their place. The best version is tested once and saved with its settings. Every number below is what the scripts printed when we ran them.

By the end of this lesson you can

  • Download Fashion-MNIST with torchvision and split off a validation set
  • Add optimiser, normalisation, regularisation and schedule tricks one at a time, and measure each
  • Read an ablation table and choose a model from it
  • Test the chosen model once, and save it with the settings needed to rebuild it

Plan it

The question: which of Stage 7's tricks actually help a deep network on real images, and by how much?

The data: Fashion-MNIST (Xiao, Rasul and Vollgraf, 2017). 60,000 training images and 10,000 test images, each 28×28 greyscale, the same size and format as MNIST, but of clothes: T-shirt/top, trouser, pullover, dress, coat, sandal, shirt, sneaker, bag and ankle boot. It was made because MNIST had become too easy; a shirt and a T-shirt are much harder to tell apart than a 1 and a 7.

What you'll make: a folder called 07-fashion inside ml-course, with four files:

  1. load.py downloads the data, splits 10,000 of the training images off for validation, and saves everything to data/fashion.pt;
  2. fashion.py, a small library: the model and the training loop, with each trick behind a switch;
  3. ablation.py adds the tricks one at a time, then takes each one away from the full set, and records every run;
  4. final.py trains the best settings, reports the test accuracy once, and saves the model.

The tricks: AdamW instead of SGD (7.3), batch norm (7.7), dropout (7.8), a cosine schedule (7.4), weight decay (7.8) and random left–right flips (7.8).

The goal: beat the baseline on validation, know why, and report an honest test score.

Download all four files here (lesson 7.1 also has a Colab and Kaggle notebook for every lesson, this one included):

07-fashion.zip4 files, made in this page
  • 07-fashion/ablation.py45 lines
  • 07-fashion/fashion.py60 lines
  • 07-fashion/final.py33 lines
  • 07-fashion/load.py27 lines

Load the data

torchvision, installed with PyTorch in lesson 7.1, knows where to download Fashion-MNIST: four files, about 31 MB. download=True fetches them into data/ the first time and finds them there afterwards:

"""Download Fashion-MNIST once, split off a validation set, and save it all as tensors in data/fashion.pt."""
import contextlib
import io

import torch
from torchvision import datasets

with contextlib.redirect_stdout(io.StringIO()):     # keep torchvision's download messages out of the output
    train = datasets.FashionMNIST("data", train=True, download=True)
    test = datasets.FashionMNIST("data", train=False, download=True)

X = train.data.float().div(255).view(-1, 784)       # 60,000 images of 28 x 28 pixels, now 0 to 1
y = train.targets
order = torch.randperm(len(X), generator=torch.Generator().manual_seed(0))
val, tr = order[:10000], order[10000:]
data = {
    "X_train": X[tr], "y_train": y[tr],
    "X_val": X[val], "y_val": y[val],
    "X_test": test.data.float().div(255).view(-1, 784), "y_test": test.targets,
    "classes": train.classes,
}
torch.save(data, "data/fashion.pt")

print("classes:", ", ".join(train.classes))
for part in ("train", "val", "test"):
    print(f"{part:5}: {tuple(data['X_' + part].shape)}  images per class: {torch.bincount(data['y_' + part]).tolist()}")
print(f"mean pixel value in the training set: {data['X_train'].mean().item():.3f}")
Terminal, in ml-course/07-fashion
(.venv) $ python load.py
classes: T-shirt/top, Trouser, Pullover, Dress, Coat, Sandal, Shirt, Sneaker, Bag, Ankle boot
train: (50000, 784)  images per class: [5009, 5022, 5012, 5001, 5052, 5001, 4945, 4984, 4974, 5000]
val  : (10000, 784)  images per class: [991, 978, 988, 999, 948, 999, 1055, 1016, 1026, 1000]
test : (10000, 784)  images per class: [1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000]
mean pixel value in the training set: 0.286

The images arrive as 8-bit integers, 0 to 255; dividing by 255 makes them 0 to 1, and .view(-1, 784) flattens each one into a row, as the MLP needs. A seeded random 10,000 become the validation set, and the classes come out roughly balanced in both parts, about 5,000 and 1,000 each. The test set has exactly 1,000 of each, and nothing in this project looks at it until final.py.

Baseline, then one trick at a time

The model is three hidden layers of 256 units with ReLU. Every trick is a switch in a settings dictionary, so one function builds and trains every version:

"""The model and training loop for the Fashion-MNIST project, with each of Stage 7's tricks behind a switch."""
import math

import torch
from torch import nn
from torch.nn import functional as F

BASELINE = {"adamw": False, "batchnorm": False, "dropout": False, "cosine": False, "weight_decay": False, "flip": False}
EPOCHS = 10


def build(config, width=256):
    """784 inputs, three hidden layers of `width`, 10 outputs."""
    layers, n_in = [], 784
    for _ in range(3):
        layers.append(nn.Linear(n_in, width))
        if config["batchnorm"]:
            layers.append(nn.BatchNorm1d(width))
        layers.append(nn.ReLU())
        if config["dropout"]:
            layers.append(nn.Dropout(0.2))
        n_in = width
    layers.append(nn.Linear(width, 10))
    return nn.Sequential(*layers)


def flip(xb):
    """Mirror a random half of the images left to right: a mirrored shirt is still a shirt."""
    imgs = xb.view(-1, 28, 28)
    mirror = torch.rand(len(xb)) < 0.5
    imgs = torch.where(mirror[:, None, None], imgs.flip(2), imgs)
    return imgs.reshape(-1, 784)


def accuracy(model, X, y):
    model.eval()
    with torch.no_grad():
        return (model(X).argmax(1) == y).float().mean().item()


def train(config, X, y, seed=0, epochs=EPOCHS, batch=128):
    torch.manual_seed(seed)
    model = build(config)
    if config["adamw"]:
        optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.05 if config["weight_decay"] else 0.0)
    else:
        optimizer = torch.optim.SGD(model.parameters(), lr=0.05, weight_decay=5e-4 if config["weight_decay"] else 0.0)
    steps = epochs * math.ceil(len(X) / batch)
    scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=steps) if config["cosine"] else None
    for epoch in range(epochs):
        model.train()
        for idx in torch.randperm(len(X)).split(batch):
            xb = flip(X[idx]) if config["flip"] else X[idx]
            loss = F.cross_entropy(model(xb), y[idx])
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            if scheduler:
                scheduler.step()                        # T_max is in steps, so step it every batch (lesson 7.4)
    return model

Two details from earlier lessons: the cosine schedule's T_max counts batches, so it's stepped every batch (7.4's wrong way, done right); and the flip mirrors a random half of each batch left to right, which never changes what an item of clothing is.

ablation.py starts from the baseline, plain SGD with none of the tricks, and switches them on one by one, 10 epochs each:

"""Add Stage 7's tricks one at a time, then take each one away from the full set: an ablation table."""
import csv
import json
import os

import torch

from fashion import BASELINE, accuracy, train

data = torch.load("data/fashion.pt")
X, y, Xv, yv = data["X_train"], data["y_train"], data["X_val"], data["y_val"]
TRICKS = ["adamw", "batchnorm", "dropout", "cosine", "weight_decay", "flip"]

rows = []


def record(name, config):
    model = train(config, X, y)
    row = {"run": name, **config, "train_acc": round(accuracy(model, X[:10000], y[:10000]), 4),
           "val_acc": round(accuracy(model, Xv, yv), 4)}
    rows.append(row)
    print(f"{name:24} train {row['train_acc']:.4f}   validation {row['val_acc']:.4f}")


print("adding one trick at a time:")
config = dict(BASELINE)
record("baseline", config)
for trick in TRICKS:
    config = {**config, trick: True}
    record("+ " + trick, config)

print("taking one away from all six:")
full = {t: True for t in TRICKS}
for trick in TRICKS:
    record("all but " + trick, {**full, trick: False})

os.makedirs("runs", exist_ok=True)
with open("runs/ablation.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=rows[0].keys())
    writer.writeheader()
    writer.writerows(rows)
best = max(rows, key=lambda r: r["val_acc"])
with open("runs/best.json", "w") as f:
    json.dump({t: best[t] for t in TRICKS}, f)
print(f"best on validation: {best['run']} ({best['val_acc']:.4f}); its settings are saved in runs/best.json")
Terminal, in ml-course/07-fashion
(.venv) $ python ablation.py
adding one trick at a time:
baseline                 train 0.8703   validation 0.8542
+ adamw                  train 0.9070   validation 0.8775
+ batchnorm              train 0.9303   validation 0.8762
+ dropout                train 0.9191   validation 0.8844
+ cosine                 train 0.9397   validation 0.8952
+ weight_decay           train 0.9397   validation 0.8961
+ flip                   train 0.9217   validation 0.8931
taking one away from all six:
all but adamw            train 0.9031   validation 0.8825
all but batchnorm        train 0.9032   validation 0.8846
all but dropout          train 0.9466   validation 0.8968
all but cosine           train 0.9047   validation 0.8839
all but weight_decay     train 0.9217   validation 0.8929
all but flip             train 0.9397   validation 0.8961
best on validation: all but dropout (0.8968); its settings are saved in runs/best.json

The first half of the table, adding tricks in order:

  • Baseline: 85.4%. Already a working classifier.
  • AdamW: 87.8%, the biggest single jump. Adam's per-weight step sizes make much faster progress in 10 epochs than SGD at one learning rate.
  • Batch norm: 87.6%. Training accuracy rose to 93.0%, but validation didn't move: it fits faster, and overfits a little more.
  • Dropout: 88.4%. Training accuracy fell, validation rose: exactly what a regulariser should do.
  • Cosine: 89.5%. Small steps at the end let the weights settle.
  • Weight decay: 89.6% and flips: 89.3%: within a few tenths of each other.

Adding things in order has a weakness: each trick is judged on top of whatever came before it. That's what the second half is for.

An ablation table

An ablation (a word borrowed from surgery: removing a part to see what it did) starts from the full set and takes one trick away at a time. If removing something makes the model worse, it was earning its place; if removing it makes no difference, or helps, it wasn't. Here, compared with all six together at 89.31%:

removedvalidationchange
AdamW88.25%−1.06
cosine schedule88.39%−0.92
batch norm88.46%−0.85
weight decay89.29%−0.02
flips89.61%+0.30
dropout89.68%+0.37

Reading it:

  • AdamW, the cosine schedule and batch norm each matter, by about a point each. Batch norm looked useless when it was added in step 3, but with everything else in place, taking it away costs 0.85: tricks interact, which is why the ablation is worth running.
  • Weight decay does nothing measurable here. 0.02 points is 2 images out of 10,000.
  • Dropout and flips hurt slightly, in this setting. Both make training harder, and with only 10 epochs the network hasn't trained long enough to need the help: with all the tricks on, training accuracy was only 92.2%, not far above validation. Removing dropout lets it reach 94.7% on training data and 89.7% on validation, the best of every run.

Be careful how much you read into the smallest numbers. Each run here used one seed, and lesson 7.11 found seed-to-seed spreads of a few tenths of a point. The point-sized effects are real; the 0.3-point ones might not be. Running each row with three seeds would settle it, at three times the cost. (One check you get for free: "all but flip" is exactly the same settings as "+ weight_decay" in the first half, and it gave the identical 0.8961. Seeded runs repeat.)

The best on validation was all but dropout, and ablation.py saved its settings to runs/best.json.

Test once, and save the best model

The choice is made, so the validation images can join the training set: final.py trains the chosen settings on all 60,000 training images, then measures the test set for the first and only time:

"""Train the best settings on training + validation data, test once, and save the model with its settings."""
import json

import torch

from fashion import accuracy, build, train

data = torch.load("data/fashion.pt")
with open("runs/best.json") as f:
    config = json.load(f)
print("settings:", ", ".join(k for k, v in config.items() if v) or "baseline")

X = torch.cat([data["X_train"], data["X_val"]])     # the choice is made, so the validation set can train too
y = torch.cat([data["y_train"], data["y_val"]])
model = train(config, X, y)

Xt, yt = data["X_test"], data["y_test"]
print(f"test accuracy: {accuracy(model, Xt, yt):.4f}")
with torch.no_grad():
    pred = model(Xt).argmax(1)
for k, name in enumerate(data["classes"]):
    print(f"  {name:12} {(pred[yt == k] == k).float().mean().item():.3f}")
confusion = torch.zeros(10, 10, dtype=torch.long)
confusion.index_put_((yt, pred), torch.ones_like(yt), accumulate=True)
confusion.fill_diagonal_(0)
t, p = divmod(confusion.argmax().item(), 10)
print(f"most common mistake: {data['classes'][t]} taken for {data['classes'][p]}, {confusion[t, p].item()} times")

torch.save({"config": config, "model": model.state_dict()}, "runs/fashion.pt")
saved = torch.load("runs/fashion.pt")
again = build(saved["config"])
again.load_state_dict(saved["model"])
print(f"saved to runs/fashion.pt; reloaded, it scores {accuracy(again, Xt, yt):.4f}")
Terminal, in ml-course/07-fashion
(.venv) $ python final.py
settings: adamw, batchnorm, cosine, weight_decay, flip
test accuracy: 0.8977
  T-shirt/top  0.860
  Trouser      0.979
  Pullover     0.835
  Dress        0.917
  Coat         0.827
  Sandal       0.950
  Shirt        0.708
  Sneaker      0.966
  Bag          0.977
  Ankle boot   0.958
most common mistake: Shirt taken for T-shirt/top, 124 times
saved to runs/fashion.pt; reloaded, it scores 0.8977

Test accuracy: 89.77%, close to the 89.68% on validation, which is what an honest validation set predicts. Up from the baseline's 85.4%, the tricks are worth about four points.

The classes tell the rest. Trousers, bags, sneakers and ankle boots are above 95%: their shapes are distinctive. Shirts are right only 70.8% of the time, and the most common mistake is a shirt taken for a T-shirt or top, 124 times. Pullovers and coats are weak too, at 83.5% and 82.7%. At 28×28 pixels, a shirt, a T-shirt, a pullover and a coat are all roughly the same blob with sleeves, and a dense layer sees each pixel separately, with no idea of edges or collars. Stage 8's convolutional networks look at local patterns and do much better on exactly these classes.

Finally, the model is saved the way lesson 7.11 recommends, with its settings beside its weights, and reloaded into a model built from those settings. It scores the same 89.77%.

Finished

You've trained a deep network in PyTorch and found out what each part of it is for. Your four files

  • download Fashion-MNIST once, and split off a validation set,
  • build and train the model with each of Stage 7's tricks behind a switch,
  • add the tricks one at a time, then ablate each one, and record every run in runs/ablation.csv,
  • choose on validation only, test once: 89.77%, and
  • save the model with the settings needed to rebuild it.

Before you call it finished, delete the data and runs folders and run load.py, ablation.py and final.py again, in order. Your numbers should match these closely (lesson 7.11 says why they might not match exactly). The ablation takes a few minutes on a laptop CPU; with a GPU, move the data and the model to the device first (lesson 7.1).

Try next:

  • Run every row of the ablation with three seeds, as lesson 7.11 did. Which of the small effects survive?
  • Train for 30 epochs instead of 10. Does dropout start to help once the network has time to overfit?
  • Swap the flips for one-pixel shifts, as lesson 7.8 did for digits. Do shifts help clothes more than flips?
  • Add residual connections (lesson 7.9) and make the network 10 layers deep. Does depth help a dense network here?

Stage 8 replaces the dense layers with convolutions, which were made for images, and Fashion-MNIST comes back in lesson 8.4 to show the difference.

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning