# Lab 2 — Classical ML with Scholar: The Iris Botanist

## Section

Not every problem needs a neural network. Scholar — traditional ML compiled through
the same Nx/EXLA stack — handles the bread-and-butter work of production
ML: scaling, logistic regression, k-NN, clustering, dimensionality
reduction. This lab walks the full lifecycle on the 150-row iris flower
set: 4 features, 3 species, 0 GPUs required. All-new examples: we
classify iris flowers, read a confusion matrix, and let K-Means discover
the species *without labels* — no deep learning anywhere, and yet this is
the workflow most production ML actually looks like.

> **From Erlang you know:** Scholar models are pure structs — `fit/3`
> returns data, `predict/2` takes data. Like an ets-cached computation,
> a fitted model is a value you can pass between processes with no locks
> and no session.

## What You'll Build

1. **A leakage-free pipeline** — shuffle by *indices*, standardize with
   **train-only** statistics, split 80/20.
2. **Two classifiers** — multinomial logistic regression and 5-NN — plus
   the confusion matrix that explains their errors.
3. **Unsupervised discovery** — K-Means recovers species with the labels
   removed; PCA projects 4-D onto 2-D for the plot.

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

## Section 1 — Load and standardize

`Scidata.Iris` returns plain lists: 150 rows × 4 features
(sepal length/width, petal length/width) and integer labels
`0 = setosa, 1 = versicolor, 2 = virginica`.

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

{features_raw, labels_raw} = Scidata.Iris.download()

x = Nx.tensor(features_raw)          # {150, 4} f32
y = Nx.tensor(labels_raw)            # {150} s64

Nx.shape(x) |> IO.inspect(label: :features)
Nx.shape(y) |> IO.inspect(label: :labels)
```

Shuffle and split 80/20. The idiomatic way is to shuffle *indices* first,
then gather — inputs and labels stay aligned by construction:

```elixir
:rand.seed(:exsss, {7, 3, 2026})

indices =
  Nx.to_flat_list(Nx.iota({150}))
  |> Enum.shuffle()
  |> Nx.tensor()

shuffled_x = x[indices]
shuffled_y = y[indices]

train_x = shuffled_x[0..119//1]
train_y = shuffled_y[0..119//1]
test_x = shuffled_x[120..149//1]
test_y = shuffled_y[120..149//1]

{Nx.shape(train_x), Nx.shape(test_x)}
```

Standardize **using train statistics only** — a classic leakage bug is
letting the test set vote on the mean and std. Applying the *test set's*
own statistics is target leakage — the most common silent accuracy
inflator in applied ML. The transform must be a closure over numbers the
model could have known at training time:

```elixir
mean = Nx.mean(train_x, axes: [0], keep_axes: true)
std = Nx.standard_deviation(train_x, axes: [0], keep_axes: true)

standardize = fn t -> Nx.divide(Nx.subtract(t, mean), std) end

train_x = standardize.(train_x)
test_x = standardize.(test_x)
```

## Section 2 — Logistic regression (multinomial)

```elixir
logreg = Scholar.Linear.LogisticRegression.fit(train_x, train_y, num_classes: 3)

preds = Scholar.Linear.LogisticRegression.predict(logreg, test_x)
Scholar.Metrics.Classification.accuracy(test_y, preds)
```

The confusion matrix tells you *how* it fails, not just how often.
Accuracy compresses 30 test predictions into one number; the matrix
decompresses it: which species eats which other's samples, and how often.
You will see setosa errors are (almost) nonexistent — it is linearly
separable — while versicolor and virginica share borderline samples. That
asymmetry is a *product decision* waiting to happen:

```elixir
cm = Scholar.Metrics.Classification.confusion_matrix(test_y, preds, num_classes: 3)

classes = ["setosa", "versicolor", "virginica"]

cm_list =
  cm
  |> Nx.to_flat_list()
  |> Enum.chunk_every(3)
  |> Enum.with_index(fn row, i ->
    %{"actual" => Enum.at(classes, i), "setosa" => Enum.at(row, 0),
      "versicolor" => Enum.at(row, 1), "virginica" => Enum.at(row, 2)}
  end)

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

## Section 3 — K-Nearest Neighbors

A lazy learner: no training at all, just distance lookups. Compare its
accuracy with logistic regression's:

```elixir
knn =
  Scholar.Neighbors.KNNClassifier.fit(train_x, train_y,
    num_classes: 3,
    num_neighbors: 5
  )

knn_preds = Scholar.Neighbors.KNNClassifier.predict(knn, test_x)
Scholar.Metrics.Classification.accuracy(test_y, knn_preds)
```

Try `num_neighbors: 1` vs `15` — low k chases noise, high k blurs class
boundaries. That trade-off is the whole game in k-NN.

## Section 4 — K-Means: discovering species without labels

Drop the labels entirely. Does the geometry of the data recover the three
species on its own?

```elixir
kmeans = Scholar.Cluster.KMeans.fit(standardize.(x), num_clusters: 3)

kmeans.clusters |> Nx.shape() |> IO.inspect(label: :centroids)
```

Cluster IDs are arbitrary (`2` may mean setosa), so compare distributions
rather than exact matches. K-Means on the unlabeled data recovers three
groups, but "cluster 2" has no canonical meaning — the plot below sets
clusters against PCA coordinates to make the correspondence visible
without pretending the IDs align. A 2-D projection makes the structure
visible:

```elixir
alias VegaLite, as: Vl

pca = Scholar.Decomposition.PCA.fit(standardize.(x), num_components: 2)
projected = Scholar.Decomposition.PCA.transform(pca, standardize.(x))

species = Enum.map(Nx.to_flat_list(y), &Enum.at(classes, &1))

Vl.new(title: "Iris in 2 principal components", width: 720, height: 480)
|> Vl.data_from_values(%{
  pc1: Nx.to_flat_list(projected[[.., 0]]),
  pc2: Nx.to_flat_list(projected[[.., 1]]),
  species: species
})
|> Vl.mark(:point, size: 80)
|> Vl.encode_field(:x, "pc1", type: :quantitative)
|> Vl.encode_field(:y, "pc2", type: :quantitative)
|> Vl.encode_field(:color, "species", type: :nominal)
```

Setosa is linearly separable from the other two — which explains why the
confusion matrix in Section 2 had (almost) no setosa errors.

## Section 5 — Where models disagree

Inspect the test rows where logistic regression and k-NN disagree — these
are exactly the samples worth labeling by hand in a real project:

```elixir
logreg_all = Scholar.Linear.LogisticRegression.predict(logreg, test_x)

disagreements =
  Nx.equal(logreg_all, knn_preds)
  |> Nx.to_flat_list()
  |> Enum.with_index(fn same, i -> if same == 0, do: i end)
  |> Enum.reject(&is_nil/1)

Enum.map(disagreements, fn i ->
  %{
    "row" => i,
    "features" => Nx.to_flat_list(test_x[i]),
    "logreg" => Enum.at(classes, Nx.to_number(logreg_all[i])),
    "knn" => Enum.at(classes, Nx.to_number(knn_preds[i])),
    "truth" => Enum.at(classes, Nx.to_number(test_y[i]))
  }
end)
|> Kino.DataTable.new(name: "Disagreements")
```

## Checkpoint

1. Why shuffle indices and gather, instead of zipping shuffled rows?
2. Your k-NN with `num_neighbors: 1` scores 94% on train and 88% on test.
   What phenomenon is this, and which knob fixes it?
3. Two models disagree on 4 test rows. Why are those rows worth more than
   the rows both got right?

**Answers**

1. Gathering by an index tensor is one `Nx.take`-style operation — shape
   stays `{n, 4}` end-to-end, and inputs/labels cannot fall out of sync
   the way parallel shuffles can.
2. Overfitting (variance). Raising `num_neighbors` smooths the decision
   boundary by averaging over a wider neighborhood.
3. Disagreements mark the boundary of what the features can express —
   exactly where labels are cheap and model headroom is highest.

## Where to next

* Exercise: split 60/40 instead of 80/20 — how stable are the two accuracy
  numbers? Run the shuffle with three different seeds and record the
  accuracy spread — your first lesson in why single splits lie.
* Exercise: add per-class `Scholar.Metrics.Classification.precision` and
  `recall`; decide which metric matters if a wrong "virginica" guess is
  costly, and which class you would collect more samples for.
* Exercise: train a `Scholar.Linear.SVM` (if your Scholar version ships it)
  on the same split and compare.
* The preprocessing, metrics, and decomposition namespaces used in this
  lab are documented at [hexdocs.pm/scholar](https://hexdocs.pm/scholar/).
