# Lab 4 — CNN on Fashion-MNIST: Garments at 28×28

Chapter 19 introduced convolutions; Chapter 21 served the result. This lab sits
between them and fills the operational gap: a **three-way data split**,
**early stopping** on validation loss, and a **confusion matrix** that
turns one accuracy number into a story about which garments look like
which at 28×28. All-new examples: instead of digits or pets, we classify
10 categories of clothing, add a validation split with early stopping,
and read the confusion matrix to see *which* garments the network
confuses.

> **From Erlang you know:** `Nx.to_batched/2` returns a lazy Stream —
> the training loop never holds the dataset twice in memory, the same
> discipline as streaming a file through a fold rather than loading it
> into a list.

## What You'll Build

1. **Fashion-MNIST end-to-end** — 60,000 grayscale images of clothing in
   10 classes, loaded via `Scidata.FashionMNIST`, kept as
   `{n, 28, 28, 1}` for the channel axis convolutions require.
2. **A compact CNN** — two conv/pool blocks into a dense head with
   dropout, summarized with `IO.inspect/1`.
3. **Disciplined training** — train/validation/test split, early stop
   with patience 3, and a single final evaluation on the untouched test
   set.

```elixir
Mix.install([
  {:axon, "~> 0.8"},
  {:nx, "~> 0.13"},
  {:exla, "~> 0.13"},
  {:polaris, "~> 0.1"},
  {:scidata, "~> 0.1.11"},
  {:scholar, "~> 0.4"},
  {:kino, "~> 0.14"}
])
```

## Section 1 — Data

Fashion-MNIST ships in the same raw-binary format as MNIST: 60,000
grayscale 28×28 images, 10 classes.

```elixir
Nx.global_default_backend(EXLA.Backend)

{images, labels} = Scidata.FashionMNIST.download()
{image_data, image_type, _shape} = images
{label_data, label_type, label_shape} = labels

images =
  image_data
  |> Nx.from_binary(image_type)
  |> Nx.divide(255)
  |> Nx.reshape({60_000, 28, 28, 1})   # keep the channel axis for conv layers

labels =
  label_data
  |> Nx.from_binary(label_type)
  |> Nx.reshape(label_shape)

labels =
  labels
  |> Nx.new_axis(-1)
  |> Nx.equal(Nx.iota({1, 10}))        # one-hot {60000, 10}

classes = [
  "t-shirt", "trouser", "pullover", "dress", "coat",
  "sandal", "shirt", "sneaker", "bag", "ankle boot"
]

{Nx.shape(images), Nx.shape(labels)}
```

Render a few samples as heatmaps — `Nx.to_heatmap` gives you a quick
Kino-ready image with zero extra dependencies:

```elixir
render = fn idx ->
  img = images[idx][[.., .., 0]]
  label = labels[idx] |> Nx.argmax() |> Nx.to_number()

  Kino.Layout.grid(
    [Nx.to_heatmap(img), Kino.Markdown.new("**#{Enum.at(classes, label)}**")],
    boxed: true
  )
end

Enum.map([0, 1, 2, 3, 4], render)
|> Kino.Layout.grid(columns: 5)
```

## Section 2 — Split & batch: train / validation / test

Three-way split — three sets, three jobs:

| Set | Who sees it | What it decides |
|-----|-------------|-----------------|
| Train | gradient descent | parameter updates |
| Validation | early stopping | *when to stop*, hyperparameters |
| Test | you, once | the number you report |

The validation set steers training (`Axon.Loop.validate/3` +
`Axon.Loop.early_stop/3`); the test set is touched exactly once, after
training is frozen. Merging them back is how teams ship models that were
never actually evaluated. The validation set drives early stopping; the
test set is touched exactly once at the end:

```elixir
train_images = images[0..49_999//1]
train_labels = labels[0..49_999//1]

val_images = images[50_000..54_999//1]
val_labels = labels[50_000..54_999//1]

test_images = images[55_000..-1//1]
test_labels = labels[55_000..-1//1]

batch_size = 128

batch = fn xs, ys ->
  # leftover: :discard — the default (:repeat) pads the final batch by
  # repeating rows, which would leak junk samples into training.
  xs
  |> Nx.to_batched(batch_size, leftover: :discard)
  |> Stream.zip(Nx.to_batched(ys, batch_size, leftover: :discard))
end

train_data = batch.(train_images, train_labels)
val_data = batch.(val_images, val_labels)
test_data = batch.(test_images, test_labels)
```

## Section 3 — A compact CNN

Two conv/pool blocks, then a dense head with dropout. Padding `:same`
keeps spatial sizes predictable:

```elixir
model =
  Axon.input("pixels", shape: {nil, 28, 28, 1})
  |> Axon.conv(32, kernel_size: {3, 3}, activation: :relu, padding: :same)
  |> Axon.max_pool(kernel_size: {2, 2}, strides: [2, 2])
  |> Axon.conv(64, kernel_size: {3, 3}, activation: :relu, padding: :same)
  |> Axon.max_pool(kernel_size: {2, 2}, strides: [2, 2])
  |> Axon.flatten()
  |> Axon.dense(128, activation: :relu)
  |> Axon.dropout(rate: 0.3)
  |> Axon.dense(10, activation: :softmax)

# Compact summary — Axon.Display.as_table/2 is broken in Axon 0.8.1
# for conv graphs, so use the model inspect instead.
IO.inspect(model, label: "conv model")
```

## Section 4 — Train with early stopping

Stop when validation loss stops improving — patience 3 epochs. Early
stopping is a supervisor for epochs: three consecutive epochs without
validation improvement and the loop halts. It is the same philosophy as a
restart budget in a supervisor — bounded resources, explicit policy, no
infinite retry:

```elixir
trained_state =
  model
  |> Axon.Loop.trainer(:categorical_cross_entropy, Polaris.Optimizers.adam(learning_rate: 1.0e-3))
  |> Axon.Loop.metric(:accuracy)
  |> Axon.Loop.validate(model, val_data)
  |> Axon.Loop.early_stop("validation_loss", mode: :min, patience: 3)
  |> Axon.Loop.run(train_data, %{}, epochs: 12, compiler: EXLA)
```

## Section 5 — Evaluate once on the test set

```elixir
model
|> Axon.Loop.evaluator()
|> Axon.Loop.metric(:accuracy)
|> Axon.Loop.run(test_data, trained_state, compiler: EXLA)
```

## Section 6 — Read the confusion matrix

Overall accuracy hides the interesting story. Which garments get mixed up?

```elixir
test_preds =
  Axon.predict(model, trained_state, test_images)
  |> Nx.argmax(axis: -1)

test_truth =
  test_labels
  |> Nx.argmax(axis: -1)

cm =
  Scholar.Metrics.Classification.confusion_matrix(test_truth, test_preds, num_classes: 10)

cm_rows =
  cm
  |> Nx.to_batched(1)
  |> Enum.with_index(fn row, actual ->
    vals = Nx.to_flat_list(row)
    %{"actual" => Enum.at(classes, actual)}
    |> Map.merge(
      classes
      |> Enum.with_index()
      |> Map.new(fn {name, j} -> {name, Enum.at(vals, j)} end)
    )
  end)

Kino.DataTable.new(cm_rows, name: "Confusion matrix (rows = actual)")
```

Shirts dominate the off-diagonal: t-shirts, pullovers, coats, and shirts
share a silhouette at 28×28. Sandals and ankle boots, with their distinct
shapes, are nearly always right. Overall accuracy hides that asymmetry;
per-class reading tells you which *data to collect next*, not just that
something is wrong.

## Checkpoint

1. Why reshape to `{60_000, 28, 28, 1}` instead of flattening to 784
   immediately?
2. Your validation loss is still dropping at epoch 12 but the loop is set
   to 12 epochs with patience 3. What happens, and how do you get the
   extra training safely?
3. Dropout is active during training and disabled at inference. Which
   Axon mechanism makes that switch, and what would go wrong without it?

**Answers**

1. Convolutions operate on spatial structure; flattening discards the 2-D
   neighborhood relationships that kernels exploit.
2. The loop stops at 12 — patience never extends a fixed epoch budget.
   Raise the epoch cap and let early stopping, not your guess, pick the
   stopping point.
3. The `:mode` flag (`:train` vs `:inference`) threaded into every layer
   via `Axon.build` / the loop. Without it, dropout noise corrupts
   deterministic predictions.

## Where to next

- Exercise: add `Axon.batch_norm()` after each conv and retrain — does the
  early-epoch accuracy curve get steeper?
- Exercise: convert to `:channels_first` layout (`{nil, 1, 28, 28}`) and
  pass `channels: :first` to conv/pool layers; measure the speed
  difference on your machine.
- Exercise: log per-class accuracy with `Scholar.Metrics.Classification.recall`
  and rank the classes by how much more data each one needs.
