Hands-On Machine Learning
Chapter 3

Classification: Beyond Accuracy — The Full Evaluator's Toolkit

Machine learning3 min readUpdated 1 Apr 2026

SGDClassifier binary classification with cross_val_predict; confusion matrix TP/FP/FN/TN; precision_score=0.837, recall=0.651, f1=0.733; precision_recall_curve + ROC + AUC; RandomForest PR AUC=0.998 vs SGD=0.960; OvR/OvO multiclass strategies; multilabel with KNN + ClassifierChain; multioutput image denoising.

The MNIST Playground

MNIST: 70,000 images, 28×28 = 784 features per instance, 10 classes. Standard split: 60,000 training / 10,000 test. The dataset is already shuffled, so cross-validation folds are IID. Chapter 3 creates a binary classification task — "is this a 5?" — to explore metrics in depth before generalising to multiclass and multilabel settings. The base classifier is SGDClassifier (linear, stochastic gradient descent, handles large datasets well).

The Accuracy Trap

Accuracy seems like the obvious metric. It's not. On the MNIST "5 detector", only ~10% of images are actually 5s. A classifier that always predicts "not 5" achieves 90%+ accuracy — better than many real models — while being completely worthless.

The imbalance problem: cross_val_score(SGDClassifier, accuracy) returns ~96%. Then cross_val_score(DummyClassifier(strategy="most_frequent"), accuracy) returns 91%. The SGD model is barely 5 points better than always predicting "not 5". Accuracy is always misleading on skewed datasets.

The Confusion Matrix

Generate out-of-sample predictions with cross_val_predict(sgd_clf, X_train, y_train_5, cv=3), then call confusion_matrix(y_train_5, y_train_pred). Each row is the actual class; each column is the predicted class.

53,892

True Negative

Correctly said "not 5"

687

False Positive

Said "5" — it wasn't

1,891

False Negative

Said "not 5" — it was

3,530

True Positive

Correctly said "5"

Precision, Recall, and the F1 Score

Three metrics derived from the confusion matrix tell the story that accuracy hides.

Precision

TP / (TP + FP)0.837

precision = TP/(TP+FP) = 3530/(3530+687) = 0.837. precision_score(y_train_5, y_train_pred). Sensitive to threshold: raising the decision threshold increases precision at the cost of recall.

Recall

TP / (TP + FN)0.651

recall = TP/(TP+FN) = 3530/(3530+1891) = 0.651. recall_score(y_train_5, y_train_pred). There is always a precision-recall trade-off: predicting positive for everything achieves perfect recall but precision collapses to the base rate.

F1 Score

2 × P×R / (P+R)0.733

f1 = 2*P*R/(P+R) = 0.733. f1_score(y_train_5, y_train_pred). For imbalanced classes, consider F_β = (1+β²)·P·R/(β²·P+R): β<1 favours precision, β>1 favours recall. Use macro/micro/weighted averaging for multiclass.

The Precision / Recall Trade-off

Every classifier has a decision threshold. Raising it increases precision (fewer false alarms) but decreases recall (more misses). The precision-recall curve plots this trade-off across all thresholds. The right threshold depends entirely on the business cost of each error type — there is no universally correct setting.

ROC Curve and AUC

ROC plots TPR (recall) vs FPR (1 − specificity) across all thresholds. AUC = area under the ROC curve: 1.0 perfect, 0.5 random. Prefer the PR curve when the positive class is rare; prefer ROC when you care about the negative class too. The RandomForest dominates on both curves.

SGDClassifier

F10.733

Roc auc: 0.960

Linear, fast, handles large data

RandomForest

F10.924

Roc auc: 0.998

Ensemble, much stronger baseline

Beyond Binary: Multiclass, Multilabel, Multioutput

Multiclass (OvR / OvO)

SGDClassifier auto-wraps in OneVsRestClassifier. SVC auto-uses OvO. Force either: OneVsRestClassifier(SVC()). Error analysis: cm / cm.sum(axis=1, keepdims=True) normalises rows. Off-diagonal hotspots identify digit pairs that need discriminating features (e.g., counting closed loops in 3 vs 8).

Multilabel Classification

y_multilabel = np.c_[(y_train >= 7), (y_train % 2 == 1)]. KNeighborsClassifier().fit(X_train, y_multilabel). Evaluate with f1_score(y_multilabel, y_pred, average="macro") or "weighted" for imbalanced label frequencies. ClassifierChain(SVC()) exploits label correlations for improved accuracy.

Multioutput Classification

noise = np.random.randint(0, 100, (len(X_train), 784)); X_train_mod = X_train + noise. KNeighborsClassifier().fit(X_train_mod, X_train). Predict on noisy test image → recover clean digit. This is a toy denoising approach using memorisation rather than learned representations.

The Mental Models Worth Keeping

1.

Never report accuracy alone on imbalanced data.

Always accompany it with precision, recall, and F1. A classifier that ignores the minority class can achieve excellent accuracy. The confusion matrix exposes this immediately.

2.

The threshold is a business decision, not a model decision.

The model learns to rank — it outputs scores or probabilities. Where you set the threshold depends on the relative cost of false positives vs false negatives in your specific application.

3.

AUC measures ranking quality, not calibration.

A high AUC means the model ranks positives above negatives on average, but says nothing about whether probability estimates are well-calibrated. For production systems acting on probabilities, calibration matters separately.

4.

Error analysis drives feature engineering.

Plotting the normalised confusion matrix for multiclass problems shows exactly which class pairs confuse the model. That tells you where to focus preprocessing effort — not hyperparameter tuning.

HOML Reading Notes — Chapter 3 of 19

Chapter 4 covers how models are actually trained — the Normal Equation, gradient descent variants (Batch, SGD, Mini-batch), and the regularisation techniques (Ridge, Lasso, Elastic Net) that prevent overfitting.