Sub topic 10
Evaluating a model on data it has not seen
This chapter assumes you can train a scikit-learn model with fit and predict, and that you know the terms features, labels, and overfitting from earlier chapters. A model that scores well on the data it trained on may still fail on new data. Evaluation measures how it performs on examples it has never seen.
Why a held-out test set
A model can memorize its training examples, so its training score tells you little about future performance. The fix is to set aside part of the data before training and use it only for scoring. This part is the test set. The score on it estimates how the model will behave in use.
Metrics for classification
Accuracy is the fraction of predictions that are correct. It misleads when classes are imbalanced. A model that always predicts "not fraud" scores 99% accuracy if only 1% of transactions are fraud.
A confusion matrix counts predictions for each pair of true and predicted class. For one class treated as "positive", two metrics are common:
- Precision is the share of predicted positives that are truly positive.
- Recall is the share of true positives that the model finds.
The F1 score is the harmonic mean of precision and recall. It is low if either one is low.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix, f1_score
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
model = LogisticRegression(max_iter=200).fit(X_train, y_train)
pred = model.predict(X_test)
print(accuracy_score(y_test, pred))
print(confusion_matrix(y_test, pred))
print(f1_score(y_test, pred, average="macro"))Rows of the confusion matrix are true classes and columns are predicted classes. Off-diagonal entries show which classes the model confuses. The stratify=y argument keeps the class proportions the same in both splits. With several classes, average="macro" computes F1 per class and averages the results equally.
Metrics for regression
Regression metrics measure the size of the error between predicted and true numbers.
| Metric | Meaning | Note |
|---|---|---|
| MAE | Mean absolute error | Same units as the target. Treats all errors equally. |
| RMSE | Square root of mean squared error | Same units as the target. Penalizes large errors more. |
| R² | Share of variance explained | 1 is perfect. 0 matches always predicting the mean. It can be negative. |
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
rng = np.random.default_rng(0)
X = rng.uniform(0, 10, size=(100, 1))
y = 3 * X[:, 0] + 2 + rng.normal(0, 1, size=100)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
pred = LinearRegression().fit(X_train, y_train).predict(X_test)
print(mean_absolute_error(y_test, pred))
print(np.sqrt(mean_squared_error(y_test, pred)))
print(r2_score(y_test, pred))The noise in the data has standard deviation 1, so an RMSE near 1 is about the best any model can do here.
Common errors
- Fitting scalers or other preprocessing on the full dataset before splitting. Fit them on the training set only.
- Reporting training accuracy as if it were test accuracy.
- Trusting accuracy on imbalanced classes.
- Drawing conclusions from a small test set. One split gives a noisy estimate, so repeat with cross-validation when data is scarce.
Exercise
A disease affects 2% of patients. A model that predicts "healthy" for everyone has 98% accuracy. Which metric exposes the problem, and what value does it take for the disease class?
Show answer
Recall for the disease class exposes it. The model finds none of the sick patients, so recall is 0, even though accuracy is 98%.