# Lab 3 — Axon: Untangling the Two Spirals

Chapter 19 trained on MNIST, where a linear model already scores ~92%.
The two-spiral benchmark removes that crutch: two interleaved spirals
that **no straight line can separate**. This lab makes the relationship
between depth, nonlinearity, and capacity something you have watched fail
and succeed in the same notebook. All-new examples: we synthesize a
*two-spiral* dataset that no linear model can separate, watch a shallow
network fail, then add depth and watch the decision boundary bend.

> **From Erlang you know:** an Axon model is an immutable graph — pipe
> layers the way you compose function clauses. Adding a layer creates a
> new graph; nothing in place is mutated. Model *state*, like GenServer
> state, is threaded explicitly through the training loop.

## What You'll Build

1. **Synthetic data generation in pure Nx** — two noisy spirals built
   from polar coordinates, seeded through functional `Nx.Random` keys.
2. **A deliberately linear model** — dense layers with no activation —
   and a front-row seat to it plateauing at ~50%.
3. **A three-layer ReLU MLP** that carves the spirals apart, then a
   decision-boundary heatmap that shows *how*.

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

## Section 1 — Synthesize the two-spiral dataset

Classic synthetic benchmark: two interleaved spirals. A straight line
cannot separate them — this is the smallest dataset that *requires* a
nonlinear network.

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

key = Nx.Random.key(2026)
points_per_spiral = 300

# Spiral 1: r grows with theta over two full turns; Spiral 2: same path
# rotated by 180°. Two turns make the arms interleave — anything less and
# the spirals stay linearly separable.
build_spiral = fn offset, k ->
  {noise_r, _} = Nx.Random.normal(k, 0.0, 0.06, shape: {points_per_spiral, 1})
  {noise_a, _} = Nx.Random.normal(k, 0.0, 0.25, shape: {points_per_spiral, 1})

  theta = Nx.linspace(0.0, 4.0 * :math.pi(), n: points_per_spiral) |> Nx.new_axis(-1)
  radius = Nx.divide(theta, 4.0 * :math.pi()) |> Nx.multiply(1.0) |> Nx.add(0.2)

  angle = Nx.add(theta, Nx.add(offset, noise_a))

  cos = Nx.cos(angle)
  sin = Nx.sin(angle)

  x = Nx.multiply(radius, cos) |> Nx.add(Nx.multiply(noise_r, cos))
  y = Nx.multiply(radius, sin) |> Nx.add(Nx.multiply(noise_r, sin))

  Nx.concatenate([x, y], axis: 1)
end

spiral_a = build_spiral.(0.0, Nx.Random.fold_in(key, 1))
spiral_b = build_spiral.(:math.pi(), Nx.Random.fold_in(key, 2))

xs = Nx.concatenate([spiral_a, spiral_b], axis: 0)
ys =
  Nx.concatenate(
    [Nx.broadcast(0.0, {points_per_spiral, 1}), Nx.broadcast(1.0, {points_per_spiral, 1})],
    axis: 0
  )

{perm, _key2} = Nx.Random.shuffle(key, Nx.iota({2 * points_per_spiral}))
xs = xs[perm]
ys = ys[perm]

{Nx.shape(xs), Nx.shape(ys)}
```

Plot it — you can see why this is hard:

```elixir
alias VegaLite, as: Vl

Vl.new(title: "Two spirals", width: 560, height: 560)
|> Vl.data_from_values(%{
  x: Nx.to_flat_list(xs[[.., 0]]),
  y: Nx.to_flat_list(xs[[.., 1]]),
  class: Enum.map(Nx.to_flat_list(ys), &to_string/1)
})
|> Vl.mark(:circle, size: 40)
|> Vl.encode_field(:x, "x", type: :quantitative)
|> Vl.encode_field(:y, "y", type: :quantitative)
|> Vl.encode_field(:color, "class", type: :nominal)
```

## Section 2 — A network that cannot learn it (on purpose)

Two dense layers with **no activation between them** is mathematically
just one linear map — width without activation buys nothing; depth *with*
nonlinearity buys composition. Watching the linear twin stall while the
MLP climbs is the clearest 10-minute lesson in why "deep" learning is
deep. Watch it plateau:

```elixir
linear_model =
  Axon.input("coords", shape: {nil, 2})
  |> Axon.dense(8)
  |> Axon.dense(1, activation: :sigmoid)

train_data =
  xs
  |> Nx.to_batched(64, leftover: :discard)
  |> Stream.zip(Nx.to_batched(ys, 64, leftover: :discard))

linear_state =
  linear_model
  |> Axon.Loop.trainer(:binary_cross_entropy, Polaris.Optimizers.adam(learning_rate: 3.0e-3))
  |> Axon.Loop.metric(:accuracy)
  |> Axon.Loop.run(train_data, %{}, epochs: 30, compiler: EXLA)
```

Accuracy stuck around ~50%: the model draws one straight line through the
spirals and gives up.

## Section 3 — Depth + nonlinearity

Same optimizer, same data — the only change is activations and depth:

```elixir
mlp_model =
  Axon.input("coords", shape: {nil, 2})
  |> Axon.dense(64, activation: :relu)
  |> Axon.dense(64, activation: :relu)
  |> Axon.dense(64, activation: :relu)
  |> Axon.dense(1, activation: :sigmoid)

mlp_state =
  mlp_model
  |> Axon.Loop.trainer(:binary_cross_entropy, Polaris.Optimizers.adam(learning_rate: 3.0e-3))
  |> Axon.Loop.metric(:accuracy)
  |> Axon.Loop.run(train_data, %{}, epochs: 60, compiler: EXLA)
```

## Section 4 — Visualize the decision boundary

The boundary is the model. Accuracy is one number; the decision-boundary
heatmap is the model's *shape*. Predict a dense grid of points through the
trained network and paint the plane — you see the sigmoid fold the space
around each spiral arm. When a classifier misbehaves in production,
reproduce this plot on a 2-D slice of the feature space before touching
the training loop. This is the single most instructive visualization for
small classifiers:

```elixir
{n, range} = {80, 2.2}

grid_axis = Nx.linspace(-range, range, n: n)

grid =
  for gy <- Nx.to_flat_list(grid_axis), gx <- Nx.to_flat_list(grid_axis) do
    [gx, gy]
  end
  |> Nx.tensor()

scores =
  Axon.predict(mlp_model, mlp_state, grid)
  |> Nx.reshape({n, n})
```

Build meshes for the plot axes and render the plane under the data:

```elixir
gx_mesh = Nx.tile(Nx.reshape(grid_axis, {1, n}), [n, 1])
gy_mesh = Nx.tile(Nx.reshape(grid_axis, {n, 1}), [1, n])

Vl.new(title: "Decision boundary", width: 640, height: 640)
|> Vl.data_from_values(%{
  bx: Nx.to_flat_list(gx_mesh),
  by: Nx.to_flat_list(gy_mesh),
  score: Nx.to_flat_list(scores)
})
|> Vl.layers([
  Vl.new()
  |> Vl.mark(:rect)
  |> Vl.encode_field(:x, "bx", type: :quantitative)
  |> Vl.encode_field(:y, "by", type: :quantitative)
  |> Vl.encode_field(:color, "score", type: :quantitative)
  |> Vl.encode(:opacity, value: 0.45),
  Vl.new()
  |> Vl.mark(:circle, size: 30)
  |> Vl.data_from_values(%{
    px: Nx.to_flat_list(xs[[.., 0]]),
    py: Nx.to_flat_list(xs[[.., 1]]),
    pclass: Enum.map(Nx.to_flat_list(ys), &to_string/1)
  })
  |> Vl.encode_field(:x, "px", type: :quantitative)
  |> Vl.encode_field(:y, "py", type: :quantitative)
  |> Vl.encode_field(:color, "pclass", type: :nominal)
])
```

## Section 5 — Sanity check on held-out points

Never trust a pretty picture alone — evaluate on points the trainer never
saw:

```elixir
{test_x, _} =
  Nx.Random.uniform(Nx.Random.fold_in(key, 9), -range, range, shape: {500, 2})

test_pred =
  Axon.predict(mlp_model, mlp_state, test_x)
  |> Nx.greater(0.5)
  |> Nx.squeeze(axes: [-1])

# Ground truth via nearest neighbor: label of the closest spiral point.
dists =
  test_x
  |> Nx.new_axis(1)
  |> Nx.subtract(Nx.new_axis(xs, 0))
  |> Nx.pow(2)
  |> Nx.sum(axes: [-1])

test_truth =
  ys[Nx.argmin(dists, axis: 1)]
  |> Nx.squeeze(axes: [-1])

acc =
  test_pred
  |> Nx.equal(test_truth)
  |> Nx.mean()
  |> Nx.to_number()

"Held-out agreement with nearest spiral point: #{Float.round(acc * 100, 1)}%"
```

## Checkpoint

1. Why does the linear model's loss stop improving while the MLP's keeps
   dropping on the *same data and optimizer*?
2. `Nx.Random.key/1` is threaded explicitly and `fold_in/2` derives
   sub-keys. What failure mode does this design prevent?
3. The held-out check uses nearest-neighbor labels from the synthetic
   distribution instead of a test split. When is that legitimate?

**Answers**

1. The linear model has zero representational gap left — its best
   achievable loss on non-separable data is bounded, so gradient descent
   converges to that plateau. The MLP's loss surface keeps offering
   directions downhill.
2. Accidentally reusing an RNG stream — the bug class of hidden global
   seeds. Functional keys make every experiment reproducible and
   parallelizable without shared state.
3. When the synthetic process *is* the ground truth: points between the
   noisy arms have no "real" answer, so agreement with the generating
   distribution is the only meaningful check.

## Where to next

* Exercise: drop the hidden layers to one `dense(8, activation: :relu)` —
  how much capacity does the spiral actually need? Find the minimum
  capacity that still separates the spirals.
* Exercise: swap `:relu` for `:tanh` and compare convergence speed and
  boundary smoothness.
* Exercise: add `Axon.dropout(rate: 0.1)` after each hidden layer. Does the
  boundary get smoother?
* Exercise: replace the sigmoid output with logits + `Axon.Losses.binary_cross_entropy(from_logits: true)` — the more production-idiomatic setup.
* Exercise: retrain the *linear* model with polynomial features you engineer
  by hand (x², y², x·y) and see how far feature engineering gets you — then
  decide when feature engineering beats depth.
