CS 460G Midterm Hub / Notebooks / Assignment 2 — MNIST with PCA and SVM
Python notebook · Copy_of_CS460G_Assignment2.ipynb

Assignment 2 — MNIST with PCA and SVM

PCA from scratch, linear and RBF SVM, 3-way holdout versus k-fold

assignmentQ5 material

The most technically demanding piece of code in scope, and the best candidate for a coding question because it contains PCA implemented with nothing but NumPy.

The three objectives, as stated

  1. Perform PCA to reduce dimensionality and select the top $k$ features, via 3-way holdout and cross-validation.
  2. Apply linear SVM (soft margin) with 3-way holdout and CV for selecting $C$.
  3. Apply non-linear SVM (Gaussian kernel) with 3-way holdout and CV for selecting $C$ and $\gamma$.

Part 1 — Load MNIST

import torch, numpy as np
from torchvision import datasets

trainset = datasets.MNIST('./data', train=True, download=True)

X_train, y_train = [], []
for k, (image, label) in enumerate(trainset):
    X_train.append(image)
    y_train.append(label)

X_train = np.reshape(X_train, [-1, 28*28])     # (60000, 784)
y_train = np.reshape(y_train, [-1])            # (60000,)

Why the loop: trainset yields (PIL image, label) pairs; they must be collected before np.reshape can stack them. The expected shapes are written into the notebook as a comment — '''Verify shape: (60000, 784) and (60000,)''' — so a wrong shape is immediately visible.

The flatten: 28*28 = 784 pixel intensities become the feature vector. That number is the whole reason the course introduces dimensionality reduction.

Normalisation to $[0,1]$ is a # To Do cell: divide by 255. It matters for both PCA (variance is scale-dependent) and RBF-SVM (Euclidean distance).

Part 2 — PCA in pure NumPy

This is the cell that gets examined.

# 1. normalise
X = X_train.astype(np.float32) / 255.0

# 2. centre (essential before covariance)
Xc = X - X.mean(axis=0)

# 3. covariance matrix  (784 x 784)
cov = np.cov(Xc, rowvar=False)

# 4. eigendecomposition — symmetric matrix, so eigh is correct and faster
eigvals, eigvecs = np.linalg.eigh(cov)

# 5. sort descending
idx = np.argsort(eigvals)[::-1]
eigvals = eigvals[idx]
eigvecs = eigvecs[:, idx]

# 6. cumulative explained variance
ratio = np.cumsum(eigvals) / np.sum(eigvals)
k = int(np.searchsorted(ratio, 0.90) + 1)

# 7. project
W = eigvecs[:, :k]
X_pca = Xc @ W

Every step is a marking opportunity. Explain each:

StepWhy it is there
/255.0puts every pixel on the same scale; PCA maximises variance
centrethe covariance formula assumes zero mean
rowvar=Falsenp.cov treats rows as variables by default; our variables are columns
eigh not eigthe covariance matrix is symmetric — eigh is faster and returns real eigenvalues
argsort()[::-1]eigenvalues come out unsorted; PCs must be ordered by variance
eigvecs[:, idx]reorder the columns, not the rows — eigenvectors are columns
cumsum / sumconverts raw eigenvalues into explained-variance proportions
@ Wthe projection $Z = XW$

Verified result: $k = 87$ components capture 90.01% of the variance. PC1 alone is 9.70%; the first ten together are 48.81%.

Cost: the covariance of 60,000×784 takes ~4.6 s and the eigendecomposition ~0.4 s. Worth saying, because it explains why you do not want to recompute this inside a hyperparameter loop.

Applying the same W to the test set

X_test_c = X_test.astype(np.float32)/255.0 - X_train.mean(axis=0)   # train mean!
X_test_pca = X_test_c @ W                                            # train W!

The classic leak. You must use the training mean and the training projection matrix on the test set. Recomputing PCA().fit(X_test) would give a different basis and silently leak test information into the transformation. Same rule as StandardScaler: fit on train, transform on test.

Part 3 — 3-way holdout for linear SVM

from sklearn.model_selection import train_test_split
X_tr, X_val, y_tr, y_val = train_test_split(
    X_pca, y_train, test_size=0.10, stratify=y_train)
# 54,000 / 6,000
from sklearn.svm import SVC
for C in [0.01, 0.1, 1]:
    svm = SVC(kernel='linear', C=C)
    svm.fit(X_tr, y_tr)
    acc = svm.score(X_val, y_val)
    print(f'C={C}: validation accuracy {acc:.4f}')

Verified validation accuracies: 0.9335 / 0.9407 / 0.9407 for $C$ = 0.01 / 0.1 / 1.

Best: $C = 0.1$. Note the shape of the curve — it rises from 0.01 and then plateaus, which says the model is not very sensitive to $C$ above 0.1. That is itself a finding.

Then the test evaluation, once:

best = SVC(kernel='linear', C=0.1).fit(X_tr, y_tr)
print('Test accuracy:', best.score(X_test_pca, y_test))
# 0.9437

Test accuracy 94.37%, 563 errors out of 10,000. Note the validation estimate (94.07%) is within 0.3 points of the test result — evidence that the 6,000-sample validation set is large enough.

Part 4 — k-fold for linear SVM

X_all = np.concatenate([X_tr, X_val])
y_all = np.concatenate([y_tr, y_val])

from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
kf = KFold(n_splits=5, shuffle=True, random_state=0)

for C in [0.01, 0.1, 1]:
    scores = cross_val_score(SVC(kernel='linear', C=C), X_all, y_all, cv=kf, scoring='accuracy')
    print(f'C={C}: {scores.mean():.4f} +/- {scores.std():.4f}')

Verified: 0.9349 / 0.9384 / 0.9382 — best at $C=0.1$ again.

The comparison the assignment asks for in one line: the two protocols agree on the chosen $C$ and on the accuracy to within 0.2 points (94.37% vs 94.27% on test). 3-way holdout is one fit per candidate and gives a single noisy number; 5-fold CV is five fits per candidate and gives a mean with a standard deviation, so it is more reliable — but here, with 60,000 training samples, the holdout was already stable and the extra 4× compute bought almost nothing.

That is the right answer to "which is better?" — it depends on how much data you have. With plenty of data a single holdout is sufficient; with little data, CV is essential.

Part 5 — RBF SVM

Same two protocols, now over a $(C,\gamma)$ grid.

for C in [0.1, 1, 10]:
    for gamma in [0.001, 0.01, 0.1]:
        svm = SVC(kernel='rbf', C=C, gamma=gamma).fit(X_tr, y_tr)
        acc = svm.score(X_val, y_val)

Verified best: $C = 10$, $\gamma = 0.01$, test accuracy 98.41% (159 errors). The 5-fold version gives the same setting and 98.40%.

The finding that matters: $\gamma$ dominates. At $\gamma = 0.1$ the model overfits (each point's influence is too local); the corner $C=0.01,\gamma=0.1$ collapses to ~31% accuracy, predicting almost everything as class 3. Changing $C$ at fixed $\gamma$ moves accuracy by less than a point. So the practical order is tune $\gamma$ first, then $C$.

The results table

ModelSelectionBest settingsValidationTest
Linear SVM3-way holdout$C=0.1$0.94070.9437 (563 err)
Linear SVM5-fold CV$C=0.1$0.93840.9427
RBF SVM3-way holdout$C=10,\ \gamma=0.01$—0.9841 (159 err)
RBF SVM5-fold CV$C=10,\ \gamma=0.01$—0.9840

What to say in the exam

"Explain the PCA block in this notebook." It is a six-step eigendecomposition: normalise to [0,1], centre by the column mean, form the 784×784 covariance with rowvar=False, eigendecompose with eigh (correct for symmetric matrices), sort eigenvalues descending and reorder the eigenvector columns to match, then take the first $k$ columns whose cumulative eigenvalue share reaches 90% and project with X @ W. The result here is $k=87$ of 784 — a 9× compression retaining 90.01% of the variance. Test data is transformed with the training mean and the training $W$, never refitted.

"Why does this assignment require 3-way holdout and cross-validation?" To make you see that they answer the same question with different bias-variance properties. The 3-way holdout reserves 10% for selection and reports a single estimate — cheap, but its accuracy depends on which 6,000 points were chosen. 5-fold CV rotates the validation role so every point is validated once, producing a mean ± standard deviation — 4× the cost, a more stable estimate. Here they agree to 0.1 points, which is the reassuring outcome; on a small dataset they would not.

The honest caveat

Runtime is roughly 2 hours single-threaded if the notebook is run as written, dominated by the RBF grid on 54,000 samples. In the exam, if asked "what would you change to make this faster?", the answer is: subsample the training set for the grid search, use LinearSVC instead of SVC(kernel='linear') (it is the liblinear implementation and far faster), and use PCA(n_components=0.90) rather than a manual cumulative search.