TExcelTAD
Home › Math for Machine Learning › Mini Project: Classifying Handwritten-Style Digits from Scratch

Mini Project: Classifying Handwritten-Style Digits from Scratch

This project chains the four applications of the course into one small pipeline on tiny 6×66 \times 6 images of the digits 0, 1 and 7: PCA compresses each image, a Gaussian mixture trained with EM discovers the three digit groups without labels, and a linear classifier trained with the hinge loss recognizes them with labels. Everything is NumPy, and every step checks itself against the theory.

What we are building:

Step Part Course topics
1. Make the dataset data data as matrices, randomness
2. Compress with PCA dimensionality reduction SVD, explained variance, projection
3. Cluster with a GMM density estimation EM, responsibilities, log-sum-exp
4. Classify with a linear SVM classification hinge loss, subgradient descent, one-vs-rest
5. Check the gradients verification numerical gradient checking

Note: Each step is a complete program (the playground does not share variables between runs), so the data generator is repeated at the top of each one.

Step 1: Make the dataset

Each digit has a clean 6×66 \times 6 template. A sample shifts it by at most one pixel, flips a few pixels and adds Gaussian noise. Flattened, every image is a vector in R36\mathbb{R}^{36}, and the dataset is a 600×36600 \times 36 matrix (Data as Vectors and Matrices).

python · try it yourself
import numpy as np

T = {0: [".####.", "#....#", "#....#", "#....#", "#....#", ".####."],
     1: ["..##..", ".###..", "..##..", "..##..", "..##..", ".####."],
     7: ["######", ".....#", "....#.", "...#..", "..#...", "..#..."]}
def make_data(n_per_class, seed):
    rng = np.random.default_rng(seed)
    X, y = [], []
    for label, rows in T.items():
        base = np.array([[c == "#" for c in r] for r in rows], dtype=float)
        for _ in range(n_per_class):
            img = np.roll(base, rng.integers(-1, 2, size=2), axis=(0, 1))
            flip = rng.uniform(size=img.shape) < 0.05
            img = np.abs(img - flip) + 0.2 * rng.normal(size=img.shape)
            X.append(img.ravel()); y.append(label)
    return np.array(X), np.array(y)

X, y = make_data(200, seed=0)
print("data matrix:", X.shape, " labels:", np.unique(y, return_counts=True))
print("first image of a 7 (rounded):")
for row in np.round(X[y == 7][0].reshape(6, 6)).astype(int):
    print("".join("#" if v > 0 else "." for v in row))
data matrix: (600, 36)  labels: (array([0, 1, 7]), array([200, 200, 200]))
first image of a 7 (rounded):
######
.....#
....#.
.#....
..#...
..#..#

Step 2: Compress with PCA

Centre the data and take the thin SVD (PCA in Practice). The explained variance ratio shows how much of the 36-dimensional variation a few components keep, and the reconstruction error equals the sum of the discarded eigenvalues (PCA: Minimum Reconstruction Error).

python · try it yourself
import numpy as np

T = {0: [".####.", "#....#", "#....#", "#....#", "#....#", ".####."],
     1: ["..##..", ".###..", "..##..", "..##..", "..##..", ".####."],
     7: ["######", ".....#", "....#.", "...#..", "..#...", "..#..."]}
def make_data(n_per_class, seed):
    rng = np.random.default_rng(seed)
    X, y = [], []
    for label, rows in T.items():
        base = np.array([[c == "#" for c in r] for r in rows], dtype=float)
        for _ in range(n_per_class):
            img = np.roll(base, rng.integers(-1, 2, size=2), axis=(0, 1))
            flip = rng.uniform(size=img.shape) < 0.05
            img = np.abs(img - flip) + 0.2 * rng.normal(size=img.shape)
            X.append(img.ravel()); y.append(label)
    return np.array(X), np.array(y)

X, y = make_data(200, seed=0)
mu = X.mean(axis=0); Xc = X - mu
U, s, Vt = np.linalg.svd(Xc, full_matrices=False)
lam = s**2 / len(X)
ratio = np.cumsum(lam) / lam.sum()
print("explained variance, first 5 PCs:", np.round(lam[:5] / lam.sum(), 3))
print("cumulative with 2, 5, 10 PCs:", np.round(ratio[[1, 4, 9]], 3))
M = 5
Z = Xc @ Vt[:M].T
err = np.mean(np.sum((Xc - Z @ Vt[:M]) ** 2, axis=1))
print(f"reconstruction error with M={M}: {err:.4f}   sum of discarded eigenvalues: {lam[M:].sum():.4f}")
for d in (0, 1, 7):
    print(f"digit {d}: mean code on PC1, PC2 = {np.round(Z[y == d, :2].mean(axis=0), 2)}")
explained variance, first 5 PCs: [0.113 0.11  0.079 0.071 0.058]
cumulative with 2, 5, 10 PCs: [0.223 0.43  0.641]
reconstruction error with M=5: 5.4889   sum of discarded eigenvalues: 5.4889
digit 0: mean code on PC1, PC2 = [ 0.79 -0.75]
digit 1: mean code on PC1, PC2 = [-0.65  0.91]
digit 7: mean code on PC1, PC2 = [-0.14 -0.17]

The three digits sit in different places already in the first two components, so a low-dimensional code is enough for the next steps.

Step 3: Cluster with a Gaussian mixture

Run EM with K=3K = 3 full-covariance components on the 5-dimensional PCA codes, without looking at the labels (The EM Algorithm). Log-likelihoods use log-sum-exp, and a small ϵI\epsilon I keeps covariances invertible. Afterwards we peek at the labels to measure purity: the fraction of points whose cluster's majority label matches their own.

python · try it yourself
import numpy as np

T = {0: [".####.", "#....#", "#....#", "#....#", "#....#", ".####."],
     1: ["..##..", ".###..", "..##..", "..##..", "..##..", ".####."],
     7: ["######", ".....#", "....#.", "...#..", "..#...", "..#..."]}
def make_data(n_per_class, seed):
    rng = np.random.default_rng(seed)
    X, y = [], []
    for label, rows in T.items():
        base = np.array([[c == "#" for c in r] for r in rows], dtype=float)
        for _ in range(n_per_class):
            img = np.roll(base, rng.integers(-1, 2, size=2), axis=(0, 1))
            flip = rng.uniform(size=img.shape) < 0.05
            img = np.abs(img - flip) + 0.2 * rng.normal(size=img.shape)
            X.append(img.ravel()); y.append(label)
    return np.array(X), np.array(y)

X, y = make_data(200, seed=0)
Xc = X - X.mean(axis=0)
Vt = np.linalg.svd(Xc, full_matrices=False)[2]
Z = Xc @ Vt[:5].T
N, D = Z.shape; K = 3

def log_gauss(Z, m, S):
    L = np.linalg.cholesky(S); W = np.linalg.solve(L, (Z - m).T)
    return -0.5 * D * np.log(2 * np.pi) - np.log(np.diag(L)).sum() - 0.5 * np.sum(W**2, axis=0)

def em(seed):
    rng = np.random.default_rng(seed)
    pi = np.full(K, 1 / K); m = Z[rng.choice(N, K, replace=False)]; S = np.array([np.cov(Z.T)] * K)
    prev = -np.inf
    for _ in range(300):
        logp = np.column_stack([np.log(pi[k]) + log_gauss(Z, m[k], S[k]) for k in range(K)])
        top = logp.max(axis=1, keepdims=True)
        ll = np.sum(top[:, 0] + np.log(np.exp(logp - top).sum(axis=1)))
        r = np.exp(logp - top); r /= r.sum(axis=1, keepdims=True)
        Nk = r.sum(axis=0); pi = Nk / N; m = (r.T @ Z) / Nk[:, None]
        S = np.array([((r[:, k, None] * (Z - m[k])).T @ (Z - m[k])) / Nk[k] + 1e-3 * np.eye(D) for k in range(K)])
        if ll - prev < 1e-6:
            break
        prev = ll
    return ll, r

runs = [em(seed) for seed in range(5)]                 # restarts: keep the best likelihood
best_ll, r = max(runs, key=lambda t: t[0])
print("log-likelihoods of 5 restarts:", [round(float(t[0]), 1) for t in runs])
cluster = r.argmax(axis=1)
purity = sum(np.bincount(y[cluster == k]).max() for k in range(K) if np.any(cluster == k)) / N
for k in range(K):
    labels, counts = np.unique(y[cluster == k], return_counts=True)
    print(f"cluster {k}: size {np.sum(cluster == k)}, labels {dict(zip(labels.tolist(), counts.tolist()))}")
print(f"purity: {purity:.3f}")
log-likelihoods of 5 restarts: [-3342.7, -3286.1, -3284.5, -3372.6, -3323.9]
cluster 0: size 290, labels {0: 175, 1: 1, 7: 114}
cluster 1: size 155, labels {0: 25, 1: 129, 7: 1}
cluster 2: size 155, labels {1: 70, 7: 85}
purity: 0.648

The restarts end at different log-likelihoods, which is why we keep the best one. Without any labels, the mixture finds a cluster that is mostly 1s and one that is mostly 0s, but it mixes many 7s into the 0 cluster, and its third cluster is half 1s and half 7s: a purity of about 0.65, well above the 0.33 of random assignment, yet far from perfect. Unsupervised clusters follow the shape of the data, which need not match the labels we care about.

Step 4: Classify with a linear SVM

Now use the labels. Train three one-vs-rest linear classifiers on the PCA codes (plus a bias) by subgradient descent on the regularized hinge loss (Soft Margin and the Hinge Loss), predict the class with the highest score, and evaluate on a fresh test set generated with another seed. The test images are projected with the training mean and components, as in any real pipeline.

python · try it yourself
import numpy as np

T = {0: [".####.", "#....#", "#....#", "#....#", "#....#", ".####."],
     1: ["..##..", ".###..", "..##..", "..##..", "..##..", ".####."],
     7: ["######", ".....#", "....#.", "...#..", "..#...", "..#..."]}
def make_data(n_per_class, seed):
    rng = np.random.default_rng(seed)
    X, y = [], []
    for label, rows in T.items():
        base = np.array([[c == "#" for c in r] for r in rows], dtype=float)
        for _ in range(n_per_class):
            img = np.roll(base, rng.integers(-1, 2, size=2), axis=(0, 1))
            flip = rng.uniform(size=img.shape) < 0.05
            img = np.abs(img - flip) + 0.2 * rng.normal(size=img.shape)
            X.append(img.ravel()); y.append(label)
    return np.array(X), np.array(y)

X, y = make_data(200, seed=0)
X_test, y_test = make_data(100, seed=1)
mu = X.mean(axis=0); Vt = np.linalg.svd(X - mu, full_matrices=False)[2][:5]
feat = lambda A: np.column_stack([(A - mu) @ Vt.T, np.ones(len(A))])
F, F_test = feat(X), feat(X_test)

def train_hinge(F, t, lam=1e-3, lr=0.05, epochs=300):
    w = np.zeros(F.shape[1])
    for _ in range(epochs):
        active = t * (F @ w) < 1
        g = lam * w - (t[active, None] * F[active]).sum(axis=0) / len(t)
        w -= lr * g
    return w

classes = np.array([0, 1, 7])
W = np.array([train_hinge(F, np.where(y == c, 1.0, -1.0)) for c in classes])
for name, A, labels in (("train", F, y), ("test", F_test, y_test)):
    pred = classes[np.argmax(A @ W.T, axis=1)]
    print(f"{name} accuracy: {np.mean(pred == labels):.3f}")
pred = classes[np.argmax(F_test @ W.T, axis=1)]
print("confusion matrix (rows = true 0, 1, 7):")
print(np.array([[np.sum((y_test == a) & (pred == b)) for b in classes] for a in classes]))
train accuracy: 0.815
test accuracy: 0.807
confusion matrix (rows = true 0, 1, 7):
[[ 86   0  14]
 [  0 100   0]
 [ 24  20  56]]

With labels, a linear classifier on just 5 PCA features reaches about 81% on unseen images, and the train and test accuracies are close, so it is not overfitting. Every 1 is recognized; most errors are 7s taken for 0s or 1s, a sign that 5 linear features cannot fully separate them (try more components, as suggested under "Where to go next").

Step 5: Check the gradients

The classifier above relied on a hand-written subgradient. Away from the kinks of the hinge (where no margin equals exactly 1), the loss is differentiable and a central difference must agree with it (Checking Gradients Numerically).

python · try it yourself
import numpy as np

rng = np.random.default_rng(4)
F = rng.normal(size=(50, 6)); t = np.where(rng.uniform(size=50) < 0.5, 1.0, -1.0)
w = rng.normal(size=6) * 0.3
lam = 1e-3
def loss(w): return 0.5 * lam * w @ w + np.mean(np.maximum(0, 1 - t * (F @ w)))
def subgrad(w):
    active = t * (F @ w) < 1
    return lam * w - (t[active, None] * F[active]).sum(axis=0) / len(t)
num = np.array([(loss(w + 1e-6 * e) - loss(w - 1e-6 * e)) / 2e-6 for e in np.eye(6)])
g = subgrad(w)
print("closest margin to the kink:", round(float(np.min(np.abs(1 - t * (F @ w)))), 4))
print("relative error:", f"{np.linalg.norm(g - num) / (np.linalg.norm(g) + np.linalg.norm(num)):.1e}")
closest margin to the kink: 0.024
relative error: 4.7e-10

Where to go next

  • Keep 10 or 20 PCA components instead of 5 and watch the test accuracy and the confusion matrix.
  • Replace the hinge loss by the logistic loss and compare calibrated probabilities (Maximum Likelihood).
  • Swap the linear classifier for an RBF kernel model (The Dual SVM and Kernels) and see if it helps on the raw 36 pixels.
  • Use BIC to choose the number of mixture components (Model Selection).
  • Continue with neural networks in Math for Deep Learning & LLMs, where the linear classifier gets hidden layers, and with Machine Learning for the scikit-learn versions of all four algorithms.

Test yourself

Why are the test images projected with the training mean and PCA components?

  1. It is faster
  2. The test set must be transformed exactly like the training data, without fitting anything on it
  3. PCA cannot be computed on test data
  4. It increases the test accuracy artificially

EM was restarted from 5 random initializations because…

  1. EM never converges
  2. EM finds a local maximum of the likelihood, which depends on the start
  3. the data changes between runs
  4. it needs 5 components

A one-vs-rest classifier predicts…

  1. the class whose binary classifier gives the highest score
  2. the most frequent class
  3. a random class
  4. the class of the nearest training point