CS 460G Midterm Hub / Notebooks / Model Evaluation
Python notebook · Copy of model-evaluation.ipynb

Model Evaluation

Every validation protocol on one dataset — the best teaching example in the course

practice nbQ6 material

This notebook takes a single model and evaluates it five different ways, which is what makes it the best illustration of why validation design matters.

The sequence

#ProtocolCodeWhat changes
1Single holdouttrain_test_split(test_size=0.25)baseline
2Stratifiedstratify=yfixes class proportions
3Repeated holdoutloop 50×, test_size=0.5averages out split luck
43-way holdoutsecond split for valseparates selection from testing
5k-fold CVKFold(n_splits=5)every point validates once
6CV hyperparameter sweepcross_val_score over $k$model selection done properly

The interesting cells

1. All four features this time

X = features        # (150, 4) — not [:, :2]
y = labels

The earlier notebooks restricted to two features so the boundary could be drawn. Here all four are used, because the point is evaluation, not visualisation.

2. The unstratified split's damage

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)

Then a histogram of y_train and y_test. In the lecture deck the same construction produces a test set with no versicolor at all — a 3-class problem where one class is entirely absent from the evaluation. That is the argument for stratification in one image.

3. Stratified

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, stratify=y)

Now the bars line up. The accuracy does not necessarily improve — what improves is the meaningfulness of the number.

4. Repeated holdout — the loop

Acc = []
k = 50
for i in range(k):
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, stratify=y)
    SVM_Model = SVC(kernel='linear').fit(X_train, y_train)
    Acc.append(accuracy_score(y_test, SVM_Model.predict(X_test)))
print('Average accuracy: ', np.mean(Acc).round(3))
# 0.976
plt.bar(np.arange(k), Acc)

What to explain: a single holdout gives one number with unknown uncertainty. Fifty repeats give a distribution — mean 0.976 plus a visible spread. That spread is the honest error bar on the estimate, and the bar chart is how you show it. This is also called Monte Carlo cross-validation.

Note the split is 50:50, not 75:25 — with repeats you can afford a smaller training set because you are averaging.

5. 3-way holdout — the cell with the lesson

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, stratify=y)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.05, stratify=y_train)
# X_train (106,4) | X_test (38,4) | X_val (6,4)

Six validation samples. Then:

KNN_Model = KNeighborsClassifier(5).fit(X_train, y_train)
print('Validation acc: ', accuracy_score(y_val, KNN_Model.predict(X_val)))   # 0.8333
print('Test acc: ',       accuracy_score(y_test, KNN_Model.predict(X_test)))  # 0.9474

This is the most quotable number in the course. Validation says 83.3%, test says 94.7% — an 11-point gap from the same model. The cause is not overfitting; it is that 6 samples means one error costs 16.7 points. A validation set that small cannot support model selection, which is precisely the argument for $k$-fold cross-validation: it gives every point a turn as validation, so no single small fold dominates the estimate.

6. k-fold, written out by hand

from sklearn.model_selection import KFold
kf = KFold(n_splits=5)
Acc = []
for train_idx, test_idx in kf.split(X):
    X_train, y_train = X[train_idx], y[train_idx]
    X_test,  y_test  = X[test_idx],  y[test_idx]
    KNN_Model.fit(X_train, y_train)
    Acc.append(accuracy_score(y_test, KNN_Model.predict(X_test)).round(3))
Acc      # [1.0, 1.0, 0.833, 0.933, 0.8]

Mean 0.913, range 0.80–1.00. The hand-written loop is there to show that k-fold is nothing more than a for-loop over index sets — cross_val_score is a convenience wrapper.

The spread is the finding. Reporting "0.913" alone hides that the model is unstable across folds; reporting "0.913 ± 0.08" is honest. On 150 samples, that variance is real.

7. Hyperparameter sweep

ks = [3, 5, 7, 9, 11, 13, 15]
for k in ks:
    acc = cross_val_score(KNeighborsClassifier(k), X, y, cv=kf, scoring='accuracy')
    print('For k=%d, Accuracy (avg): %0.3f' % (k, np.mean(acc)))
k=3   0.907
k=5   0.913
k=7   0.920   <-- best
k=9   0.920   <-- best (tie)
k=11  0.913
k=13  0.907
k=15  0.900

A classic inverted-U: too small $k$ overfits, too large $k$ underfits, and the optimum sits in the middle. Here the curve is almost flat between 5 and 11, which itself says the choice is not critical on this dataset.

Two things to say: (i) the sweep is done with cv=kf on the full data X, y — no separate validation set — because cross-validation is the validation; (ii) the test set has still not been touched at this point, which is the whole discipline being demonstrated.

The subtle leak in this notebook. cross_val_score(KNeighborsClassifier(k), X, y, cv=kf) passes the whole dataset X, y. If you had earlier used X_train/X_test for a final evaluation and now tune on X, y, the "test" set has been used for selection and your final test accuracy is no longer unbiased. The correct pattern is: tune inside the training set with CV, then evaluate once on the held-out test set. This notebook demonstrates the techniques side by side rather than composing them correctly — which is itself worth noticing.

The comparison table to memorise

ProtocolUses all data for validation?Variance of estimateCostWhen
Single holdoutnohigh1 fitquick sanity check
Stratified holdoutnohigh1 fitimbalanced classes
Repeated holdoutpartiallymedium$k$ fitsmedium data, want error bars
3-way holdoutnohigh (if val small)few fitsneed a selection set
$k$-fold CVyeslow$k$ fitsdefault choice
LOOyeslow bias, high variance$n$ fitstiny datasets only