---
title: "Classification lab: Fisher, neighbors, ROC curves and naive Bayes"
heading: Fisher's discriminant from data with a check that no direction does better, k-nearest-neighbor classification with k chosen by leave-one-out, ROC curves and the AUC as a rank statistic, and a Gaussian naive Bayes classifier's log-odds
eyebrow: S14 · Lesson 19 · Classification lab
xp: 60
---

::: hook
Lessons 15 to 18 gave four ways to draw a boundary between classes: a projection chosen by Fisher's criterion, a probabilistic model of each class, a logistic model of the boundary itself, and no model at all, just the nearest stored examples. In this lab you'll write the ones that need no iterative training, measure them the way lesson 20 recommends, and check each result against an independent calculation.
:::

::: play
- The curves describe two equally likely unit-variance Gaussian classes whose means are d apart.
- The solid curve is the Bayes error, the best any classifier can do; the dashed one is the most a 1-nearest-neighbor classifier can reach with unlimited data, $2R^*(1 - R^*)$.
- The third is the AUC of the optimal score: the probability that a random positive outscores a random negative, $\Phi(d/\sqrt2)$.
:::

```sim plot
view: graph
x: d = 0..5
y: p = 0..1
plot: 0.5*erfc(d/2/sqrt(2)) | label: Bayes error
plot: 2*0.5*erfc(d/2/sqrt(2))*(1 - 0.5*erfc(d/2/sqrt(2))) | dashed | label: 1-NN limit
plot: 0.5*erfc(-d/2) | label: AUC
```

::: predict
## Ten labeled points on a line include two whose labels are wrong. As k grows from 1 to 5, what happens to a k-NN classifier's leave-one-out error?

- [ ] It rises, because larger neighborhoods reach across the boundary
- [x] It falls, because voting outweighs the mislabeled points
- [ ] It stays the same
- [ ] It becomes zero

::: reveal
With k = 1, each mislabeled point misleads its neighbors and is itself misclassified, and task 2's data give a leave-one-out error of 60%. With k = 5 the vote outweighs a single wrong label and the error falls to 30%. Larger k trades resolution for robustness to noisy labels, and leave-one-out is a cheap way to choose it.
:::
:::

::: nameit
## What the lab computes

- **Fisher's discriminant**: from the class means $\mathbf m_1$, $\mathbf m_2$ and the within-class scatter $S_W = \sum_k\sum_{n \in C_k}(\mathbf x_n - \mathbf m_k)(\mathbf x_n - \mathbf m_k)^T$, the direction is $\mathbf w \propto S_W^{-1}(\mathbf m_2 - \mathbf m_1)$ and its separation is $J = (\mathbf m_2 - \mathbf m_1)^TS_W^{-1}(\mathbf m_2 - \mathbf m_1)$, the same as $(m_2' - m_1')^2/(s_1^2 + s_2^2)$ computed from the projections, with $s_k^2$ the sum of squared deviations.
- **k-nearest neighbors**: a majority vote of the k closest stored examples (ties in distance broken by the earlier example); the leave-one-out error classifies each example by the others.
- **ROC and AUC**: sweeping the threshold through every distinct score traces (false-positive rate, true-positive rate) points; the trapezoid area under them equals the Mann–Whitney statistic, the fraction of positive–negative pairs ranked correctly, with ties counting half.
- **Gaussian naive Bayes**: each class's prior, per-feature means and maximum-likelihood variances; the log-odds of class 1 at x is the difference of the two classes' log priors plus summed log densities.
:::

::: check
kind: python

## Write `fisher(X1, X2)` for two-dimensional data: return the unit direction (any sign) and the separation J.

```python starter
def fisher(X1, X2):
    return [1.0, 0.0], 0.0
```

```python solution
import math

def fisher(X1, X2):
    m1 = [sum(r[i] for r in X1) / len(X1) for i in range(2)]
    m2 = [sum(r[i] for r in X2) / len(X2) for i in range(2)]
    S = [[0.0, 0.0], [0.0, 0.0]]
    for X, m in ((X1, m1), (X2, m2)):
        for r in X:
            d = [r[0] - m[0], r[1] - m[1]]
            for i in range(2):
                for j in range(2):
                    S[i][j] += d[i] * d[j]
    det = S[0][0] * S[1][1] - S[0][1] * S[1][0]
    dm = [m2[0] - m1[0], m2[1] - m1[1]]
    w = [(S[1][1] * dm[0] - S[0][1] * dm[1]) / det, (-S[1][0] * dm[0] + S[0][0] * dm[1]) / det]
    J = w[0] * dm[0] + w[1] * dm[1]
    n = math.hypot(w[0], w[1])
    return [w[0] / n, w[1] / n], J
```

```python tests
import math
X1 = [[0, 0], [1, 1], [2, 1], [1, 0], [0, 1]]
X2 = [[2, 3], [3, 3], [3, 2], [4, 4], [2, 2.5]]
w, J = fisher(X1, X2)
def J_of(v):
    p1 = [v[0] * r[0] + v[1] * r[1] for r in X1]
    p2 = [v[0] * r[0] + v[1] * r[1] for r in X2]
    a, b = sum(p1) / 5, sum(p2) / 5
    return (b - a) ** 2 / (sum((p - a) ** 2 for p in p1) + sum((p - b) ** 2 for p in p2))
assert abs(J - 1.650532) < 1e-5 and abs(J_of(w) - J) < 1e-9, "J = 1.651, the same from the projections."
assert all(J_of([math.cos(a / 50), math.sin(a / 50)]) <= J + 1e-9 for a in range(315)), "No direction separates better."
assert abs(abs(w[0]) - 0.240478) < 1e-5, "The direction leans mostly along the second feature."
```

::: right
Right. The direction tilts away from the mean difference toward the feature with less within-class spread.
:::
:::

::: check
kind: python

## Write `knn_predict(train, labels, x, k)` for 0/1 labels and odd k, and `loo_error(train, labels, k)`.

```python starter
def knn_predict(train, labels, x, k):
    return 0

def loo_error(train, labels, k):
    return 0.0
```

```python solution
def knn_predict(train, labels, x, k):
    order = sorted(range(len(train)), key=lambda i: (sum((a - b) ** 2 for a, b in zip(train[i], x)), i))
    votes = sum(labels[i] for i in order[:k])
    return 1 if 2 * votes > k else 0

def loo_error(train, labels, k):
    wrong = 0
    for i in range(len(train)):
        rest, lab = train[:i] + train[i + 1:], labels[:i] + labels[i + 1:]
        wrong += knn_predict(rest, lab, train[i], k) != labels[i]
    return wrong / len(train)
```

```python tests
xs = [[0], [1], [2], [3], [4.5], [2.5], [4], [5], [6], [7]]
ys = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
assert knn_predict(xs, ys, [6.5], 3) == 1 and knn_predict(xs, ys, [0.5], 3) == 0, "Far from the mislabeled points, the neighbors agree."
assert [loo_error(xs, ys, k) for k in (1, 3, 5)] == [0.6, 0.4, 0.3], "Leave-one-out errors 60%, 40% and 30%."
```

::: right
Right. Leave-one-out picks k = 5 here, the smoothest of the three.
:::
:::

::: check
kind: python

## Write `auc(pos, neg)` as the Mann–Whitney statistic, `roc(pos, neg)` returning the (FPR, TPR) points from (0, 0) through each distinct threshold, highest first, and `trapezoid(points)`.

```python starter
def auc(pos, neg):
    return 0.5

def roc(pos, neg):
    return [(0.0, 0.0), (1.0, 1.0)]

def trapezoid(points):
    return 0.5
```

```python solution
def auc(pos, neg):
    s = 0.0
    for p in pos:
        for q in neg:
            s += 1.0 if p > q else (0.5 if p == q else 0.0)
    return s / (len(pos) * len(neg))

def roc(pos, neg):
    pts = [(0.0, 0.0)]
    for t in sorted(set(pos + neg), reverse=True):
        pts.append((sum(q >= t for q in neg) / len(neg), sum(p >= t for p in pos) / len(pos)))
    return pts

def trapezoid(points):
    return sum((x2 - x1) * (y1 + y2) / 2 for (x1, y1), (x2, y2) in zip(points, points[1:]))
```

```python tests
import math
pos, neg = [0.9, 0.8, 0.8, 0.4], [0.8, 0.3, 0.2]
assert abs(auc(pos, neg) - 5 / 6) < 1e-12 and abs(trapezoid(roc(pos, neg)) - 5 / 6) < 1e-12, "Ties count half: AUC = 5/6 both ways."
def ninv(p):
    lo, hi = -10.0, 10.0
    for _ in range(100):
        m = (lo + hi) / 2
        lo, hi = (m, hi) if 0.5 * math.erfc(-m / math.sqrt(2)) < p else (lo, m)
    return lo
n = [ninv((i + 0.5) / 200) for i in range(200)]
p = [v + 1 for v in n]
assert abs(auc(p, n) - 0.5 * math.erfc(-0.5)) < 0.001, "Gaussian scores one standard deviation apart: AUC = Φ(1/√2) = 0.760."
```

::: right
Right. The area under the ROC curve is a rank statistic: it depends only on how the scores are ordered.
:::
:::

::: check
kind: python

## Write `fit_gnb(X, y)` returning {class: (prior, means, variances)} for classes 0 and 1, and `log_odds(x, model)`.

```python starter
def fit_gnb(X, y):
    return {0: (0.5, [0.0], [1.0]), 1: (0.5, [0.0], [1.0])}

def log_odds(x, model):
    return 0.0
```

```python solution
import math

def fit_gnb(X, y):
    model = {}
    for c in (0, 1):
        R = [r for r, t in zip(X, y) if t == c]
        m = [sum(r[i] for r in R) / len(R) for i in range(len(R[0]))]
        v = [sum((r[i] - m[i]) ** 2 for r in R) / len(R) for i in range(len(m))]
        model[c] = (len(R) / len(X), m, v)
    return model

def log_odds(x, model):
    def lp(c):
        p, m, v = model[c]
        return math.log(p) + sum(-0.5 * math.log(2 * math.pi * vi) - (xi - mi) ** 2 / (2 * vi) for xi, mi, vi in zip(x, m, v))
    return lp(1) - lp(0)
```

```python tests
X = [[0, 1], [1, 2], [2, 0], [1, 1], [4, 3], [5, 5], [6, 4], [5, 4]]
y = [0, 0, 0, 0, 1, 1, 1, 1]
mod = fit_gnb(X, y)
assert mod[0][1] == [1.0, 1.0] and mod[1][1] == [5.0, 4.0] and mod[0][2] == [0.5, 0.5], "Means (1, 1) and (5, 4), variances 0.5."
assert abs(log_odds([3, 2.5], mod)) < 1e-12, "Halfway between the means, with equal variances: even odds."
assert abs(log_odds([1, 1], mod) + 25.0) < 1e-9, "At class 0's mean the log-odds are −25."
```

::: right
Right. With equal variances in both classes the log-odds are linear in x, so naive Bayes draws a straight boundary.
:::
:::

::: explain
## Why does the area under the ROC curve equal the probability that a random positive example outscores a random negative one?

::: model
Each step along the ROC curve lowers the threshold past one more score. When it passes a negative's score, the false-positive rate rises by one negative's share and the curve moves right at the current true-positive rate, which is the fraction of positives scoring above that negative. The area added is therefore that negative's share times the fraction of positives that outrank it. Summing over all negatives gives the average, over negatives, of the fraction of positives scoring higher, which is exactly the probability that a randomly chosen positive outscores a randomly chosen negative, with ties, where the curve rises diagonally, counting half.
:::
:::
