Skip to content

MLDay 39 of 50Deep Learning

Project 4

a Clothing-Image Classifier

9 min read

An online shop wants to tag each product photo with its type, so shoppers can filter by "shirts". A wrong tag hides a product from the people looking for it. The team needs a model, an honest score, and a plain answer to "which clothes does it mix up?"

The idea

This project tunes a small CNN, scores it once, and then studies its mistakes.

  1. Split three ways, as in Day 6: 5,000 training images, 1,000 validation images for choosing settings, and 1,000 test images. The test images stay locked until the very end.
  2. Tune a little. Start from the small CNN of Day 37, then try a wider one and one with dropout (Day 36). Keep whichever scores best on validation.
  3. Score the test set once. That number is the honest guess for new photos.
  4. Diagnose. A confusion matrix is a 10×10 table of counts: row = the true class, column = the predicted class. Right answers sit on the diagonal; every other cell is one kind of mistake. Per-class precision and recall (Day 13) come straight from it, and an error gallery, real images of each mistake, shows why.
  5. Save the weights so a later script can reuse the model without training it again.

The formula

Precision for a class reads down its column: of everything the model called class kk, how much really was kk?

Pk=Ckk∑iCikP_k = \frac{C_{kk}}{\sum_i C_{ik}}
Symbol Meaning
CikC_{ik} the count in row ii, column kk: images of true class ii predicted as class kk
CkkC_{kk} the diagonal cell: class kk predicted correctly
∑iCik\sum_i C_{ik} the column total: every image predicted as class kk
PkP_k precision for class kk

Recall reads along the row instead: of the real class kk images, how many did the model find?

Rk=Ckk∑jCkjR_k = \frac{C_{kk}}{\sum_j C_{kj}}

Worked, with the shirt column from Step 4 below. The model called 103 test images "shirt". 64 were shirts; the rest were 17 coats, 11 T-shirts, 5 pullovers, 5 dresses and 1 bag. So P=64/103≈0.62P = 64 / 103 \approx 0.62. The test set holds 100 shirts, so R=64/100=0.64R = 64 / 100 = 0.64.

In code

The project is three short files. Each training run takes about 25–40 seconds on a laptop CPU.

Step 1: the shared helpers (clothes.py). It loads the Phase 4 split and defines the network and the training loop from Day 32. c sets the channel count: 16 is the small CNN, and 32 doubles every layer. fit reports accuracy every 5 epochs and saves the weights.

# script_id: day_039_project_clothing_classifier/clothes
import os
from pathlib import Path

import numpy as np
import torch
from sklearn.model_selection import train_test_split
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

CLASSES = ["T-shirt", "Trouser", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
MODEL_DIR = Path(os.environ.get("ML_MODEL_DIR", "models"))
d = np.load(DATA_DIR / "fashion_mnist" / "fashion_mnist_slice.npz")
X, y = d["X_train"].astype("float32") / 255, d["y_train"].astype("int64")
X_tr, X_va, y_tr, y_va = train_test_split(X, y, test_size=1000, stratify=y, random_state=42)
X_tr, X_va = torch.from_numpy(X_tr).unsqueeze(1), torch.from_numpy(X_va).unsqueeze(1)   # add the channel axis
y_tr, y_va = torch.from_numpy(y_tr), torch.from_numpy(y_va)


def make_cnn(c=16, p=0.0):                           # p is the dropout rate before the last layer
    return nn.Sequential(nn.Conv2d(1, c, 3), nn.ReLU(), nn.MaxPool2d(2),
                         nn.Conv2d(c, 2 * c, 3), nn.ReLU(), nn.MaxPool2d(2),
                         nn.Flatten(), nn.Dropout(p), nn.Linear(2 * c * 5 * 5, 10))


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


def fit(name, c=16, p=0.0, epochs=15):
    torch.manual_seed(42)
    model = make_cnn(c, p)
    loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True,
                        generator=torch.Generator().manual_seed(42))
    opt, loss_fn = torch.optim.Adam(model.parameters(), lr=1e-3), nn.CrossEntropyLoss()
    for epoch in range(1, epochs + 1):
        model.train()
        for xb, yb in loader:
            opt.zero_grad()
            loss_fn(model(xb), yb).backward()
            opt.step()
        if epoch % 5 == 0:
            print(f"{name} epoch {epoch:>2}: train {accuracy(model, X_tr, y_tr):.3f}, "
                  f"validation {accuracy(model, X_va, y_va):.3f}")
    MODEL_DIR.mkdir(exist_ok=True)
    torch.save(model.state_dict(), MODEL_DIR / f"{name}.pt")   # the weights only, not the layers


if __name__ == "__main__":
    print(f"train {len(X_tr):,}, validation {len(X_va):,}, test {len(d['X_test']):,} (locked)")
    for c in [16, 32]:
        print(f"c={c}: {sum(w.numel() for w in make_cnn(c).parameters()):,} weights")
train 5,000, validation 1,000, test 1,000 (locked)
c=16: 12,810 weights
c=32: 34,826 weights

Step 2: tune on the validation set. One script, three runs, one setting changed at a time.

# script_id: day_039_project_clothing_classifier/tune
from clothes import fit

for name, c, p in [("small", 16, 0.0), ("wide", 32, 0.0), ("wide_dropout", 32, 0.3)]:
    fit(name, c=c, p=p)
small epoch  5: train 0.824, validation 0.817
small epoch 10: train 0.858, validation 0.830
small epoch 15: train 0.874, validation 0.834
wide epoch  5: train 0.847, validation 0.827
wide epoch 10: train 0.883, validation 0.845
wide epoch 15: train 0.909, validation 0.859
wide_dropout epoch  5: train 0.852, validation 0.833
wide_dropout epoch 10: train 0.886, validation 0.847
wide_dropout epoch 15: train 0.897, validation 0.850

Step 3: choose. Doubling the channels lifts validation accuracy from 0.834 to 0.859. Dropout narrows the gap between train and validation a little, but lowers validation to 0.850. That gap was only 0.05, so there was little overfitting for dropout to fix. The winner is wide, with no dropout. Its validation score was still climbing at epoch 15, so a longer run is the next thing to try.

Step 4: score the test set once. A fresh script rebuilds the same layers, loads the saved weights, and predicts the 1,000 locked images.

# script_id: day_039_project_clothing_classifier/evaluate
import os
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import torch
from sklearn.metrics import confusion_matrix, precision_score, recall_score

from clothes import CLASSES, MODEL_DIR, d, make_cnn

model = make_cnn(c=32)                                # the same layers as the saved run
model.load_state_dict(torch.load(MODEL_DIR / "wide.pt"))
model.eval()
X_te, y_te = torch.from_numpy(d["X_test"].astype("float32") / 255).unsqueeze(1), d["y_test"]
with torch.no_grad():
    pred = model(X_te).argmax(dim=1).numpy()
print(f"test accuracy {(pred == y_te).mean():.3f}")

cm = confusion_matrix(y_te, pred)                     # rows: true class, columns: predicted class
prec, rec = precision_score(y_te, pred, average=None), recall_score(y_te, pred, average=None)
for k in np.argsort(prec):
    print(f"{CLASSES[k]:<10} precision {prec[k]:.2f}  recall {rec[k]:.2f}  "
          f"(predicted {cm[:, k].sum():>3}, right {cm[k, k]:>2})")
test accuracy 0.842
Shirt      precision 0.62  recall 0.64  (predicted 103, right 64)
Pullover   precision 0.74  recall 0.81  (predicted 110, right 81)
Coat       precision 0.75  recall 0.66  (predicted  88, right 66)
Dress      precision 0.84  recall 0.91  (predicted 108, right 91)
T-shirt    precision 0.86  recall 0.72  (predicted  84, right 72)
Bag        precision 0.87  recall 0.96  (predicted 110, right 96)
Sneaker    precision 0.89  recall 0.93  (predicted 105, right 93)
Ankle boot precision 0.93  recall 0.96  (predicted 103, right 96)
Sandal     precision 0.96  recall 0.88  (predicted  92, right 88)
Trouser    precision 0.98  recall 0.95  (predicted  97, right 95)

The test score, 0.842, sits a little under validation's 0.859. That's expected: the winner was the best of three validation scores, so its score was slightly lucky, and a 1,000-image score wobbles by about a point either way. Shoes, bags and trousers are easy. Shirts are the weak spot: only 62% of the "shirt" tags are right.

Step 5: the confusion matrix. The chart shows where the 158 mistakes go.

# script_id: day_039_project_clothing_classifier/evaluate
TOPS = [0, 2, 4, 6]                                   # T-shirt, Pullover, Coat, Shirt
mixups = cm[TOPS][:, TOPS].sum() - cm[TOPS, TOPS].sum()
print(f"mistakes: {len(y_te) - np.trace(cm)}, of which {mixups} swap one top for another")

FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
fig, ax = plt.subplots(figsize=(6, 5))
ax.imshow(cm, cmap="Blues")
for i, j in np.ndindex(cm.shape):
    if cm[i, j]:
        ax.text(j, i, cm[i, j], ha="center", va="center", fontsize=8, color="white" if cm[i, j] > 50 else "black")
ax.set_xticks(range(10), CLASSES, rotation=45, ha="right")
ax.set_yticks(range(10), CLASSES)
ax.set(title="Most mistakes swap one top for another", xlabel="Predicted class", ylabel="True class")
fig.tight_layout()
fig.savefig(FIG_DIR / "confusion_matrix.png", dpi=120)
plt.close(fig)
mistakes: 158, of which 90 swap one top for another

Most mistakes swap one top for another

More than half the mistakes stay inside four classes: T-shirt, pullover, coat and shirt. The biggest cells are coats called shirts (17) and coats called pullovers (12). Shoes are mostly mixed up with other shoes.

Step 6: the error gallery. One test image for each pair of T-shirt, pullover and shirt. The diagonal holds correct answers; the title gives each cell's count.

# script_id: day_039_project_clothing_classifier/evaluate
LOOK_ALIKES = [0, 2, 6]                               # T-shirt, Pullover, Shirt
fig, axes = plt.subplots(3, 3, figsize=(6, 6))
for r, t in enumerate(LOOK_ALIKES):
    for c, p in enumerate(LOOK_ALIKES):
        ax = axes[r, c]
        ax.axis("off")
        idx = np.flatnonzero((y_te == t) & (pred == p))
        if len(idx):
            ax.imshow(d["X_test"][idx[0]], cmap="gray_r")
        ax.set_title(f"{CLASSES[t]} → {CLASSES[p]}: {len(idx)}", fontsize=9)
fig.suptitle("Shirts get mixed up with T-shirts and pullovers both ways")
fig.tight_layout()
fig.savefig(FIG_DIR / "error_gallery.png", dpi=120)
plt.close(fig)

Shirts get mixed up with T-shirts and pullovers both ways

At 28×28 pixels the three share one outline. A short-sleeved shirt looks like a T-shirt, and a dark long-sleeved one looks like a pullover. Buttons and collars, the real difference, are a few grey pixels.

Quick check

Quick check

1. In a confusion matrix with true classes as rows, where do you read a class's precision?

2. Why was dropout left out of the final model?

3. Test accuracy (0.842) came out below the winner's validation accuracy (0.859). What does that suggest?

Next

Images are grids of numbers already; Day 40 turns words into vectors a network can learn from.

Data: Fashion-MNIST (Zalando Research), MIT licence; cite Xiao, H., Rasul, K. and Vollgraf, R. (2017), "Fashion-MNIST: a Novel Image Dataset for Benchmarking Machine Learning Algorithms", arXiv:1708.07747.

Next · Day 40 · 9 minEmbeddings: Tokens as Vectors← Previous: Day 38 · Transfer Learning
Not tapped yet