Sub topic 10
Evaluating a model on data it has not seen
This chapter assumes you can read basic Python and NumPy and have used scikit-learn's fit and predict. It also assumes you know the earlier ideas in this tutorial: features, labels, loss, and overfitting. Here you will learn how to measure whether a trained model will work on new data, and which metric to pick.
Why training performance is not enough
A model is fit by minimizing loss on its training examples. A model with enough flexibility can memorize those examples, so a good training score says little about how it will behave later. The quantity you care about is the error on future data drawn from the same source. You cannot observe that error directly, so you estimate it on examples that were kept out of training.
An estimate is only honest if the held-out examples played no part in fitting the model. That includes indirect roles, such as choosing hyperparameters by looking at them. The rest of this chapter follows from that rule.
Train, validation, and test sets
The common arrangement uses three disjoint subsets of the data.
| Subset | Used for | How often you look at it |
|---|---|---|
| Training | Fitting parameters | Constantly |
| Validation | Choosing between models and hyperparameters | Many times |
| Test | Reporting the final estimate | Once, at the end |
Each time you choose something because it scored well on the validation set, the validation score becomes slightly optimistic. The test set stays untouched so that one unbiased number remains for the final report.
Splitting correctly
Three details cause most split errors:
- Stratification. For classification, pass
stratify=yso each subset keeps the class proportions. Rare classes can otherwise vanish from the test set. - Randomness. Set
random_stateso results can be reproduced. - Leakage. Any preprocessing that learns from data, such as scaling or imputing missing values, must be fit on the training portion only. Fitting a scaler on the full dataset lets test-set statistics influence training. A scikit-learn
Pipelineavoids this, because it refits each step inside every training fold.
For time-ordered data, do not shuffle. Train on the past and test on the future, for example with TimeSeriesSplit. Also keep related rows together. If one patient or user contributes many rows, put all of that person's rows on one side of the split, for example with GroupKFold. Otherwise the model is tested on near-copies of what it has already seen.
Metrics for classification
Accuracy is the fraction of correct predictions. It is easy to read, but it can mislead. The more informative tools start from the confusion matrix, which counts predictions by true class and predicted class. In the binary case the four cells are:
- True positives (TP): positives predicted as positive.
- False positives (FP): negatives predicted as positive.
- False negatives (FN): positives predicted as negative.
- True negatives (TN): negatives predicted as negative.
From these cells:
- Precision is TP / (TP + FP). Of the items the model flagged, how many were really positive.
- Recall is TP / (TP + FN). Of the real positives, how many the model found.
- F1 is the harmonic mean of precision and recall. It is low if either one is low.
The code below trains on iris and prints the confusion matrix and a per-class report.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, classification_report
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(confusion_matrix(y_test, pred))
print(classification_report(y_test, pred))Rows of the matrix are true classes and columns are predicted classes, so off-diagonal entries show exactly which classes get confused.
When accuracy lies
Suppose 95% of examples are negative. A model that always answers "negative" scores 95% accuracy and finds no positives at all. The next example makes this concrete by comparing such a baseline with a real model.
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
X, y = make_classification(
n_samples=2000, weights=[0.95, 0.05], flip_y=0,
class_sep=1.5, random_state=0
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
models = [
("always majority", DummyClassifier(strategy="most_frequent")),
("logistic", LogisticRegression(max_iter=500)),
]
for name, m in models:
m.fit(X_train, y_train)
pred = m.predict(X_test)
print(
name,
"accuracy", round(accuracy_score(y_test, pred), 3),
"precision", round(precision_score(y_test, pred, zero_division=0), 3),
"recall", round(recall_score(y_test, pred), 3),
)The baseline has high accuracy and zero recall. Always compare against a trivial baseline like this one. If your model barely beats it, the model has learned little.
Choosing between precision and recall
The right trade-off depends on the cost of each error type.
- Screening for a serious disease: a false negative is costly, so favor recall.
- Flagging emails for automatic deletion: a false positive is costly, so favor precision.
- No strong preference: F1 balances them.
Many classifiers output a probability, and the default 0.5 cutoff is a choice, not a law. Lowering the threshold raises recall and lowers precision. Metrics that look at all thresholds, such as ROC AUC and average precision (the area under the precision-recall curve), are useful for comparing models before you fix a threshold. On heavily imbalanced data, average precision is usually more informative than ROC AUC.
Metrics for regression
For regression, the error on each example is the prediction minus the true value. Common summaries:
- Mean absolute error (MAE) is the average of the absolute errors. It is in the units of the target and treats all errors in proportion to their size.
- Root mean squared error (RMSE) squares errors before averaging, then takes the square root. It is also in the target's units but punishes large errors more, so a few big misses raise it sharply.
- R² compares your model to always predicting the mean of the target. A value of 1 is perfect, 0 matches the mean predictor, and negative values are worse than that predictor.
Use MAE when outliers should not dominate, and RMSE when large errors are especially bad. R² is unitless, which helps when comparing across targets. It can still look fine while the errors are too large for your application, so report an error in real units as well.
Cross-validation
A single split gives a noisy estimate, especially on small datasets. The score depends on which rows landed in the test set. K-fold cross-validation reduces this noise. It splits the training data into k folds. For each fold, it trains on the other k−1 folds and scores on the held-out one. The k scores give you both a mean and a spread.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFold, cross_val_score
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
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
)
cv = KFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(
LinearRegression(), X_train, y_train,
cv=cv, scoring="neg_mean_absolute_error",
)
print("CV MAE:", -scores.mean(), "+/-", scores.std())
model = LinearRegression().fit(X_train, y_train)
pred = model.predict(X_test)
print("test MAE:", mean_absolute_error(y_test, pred))
print("test RMSE:", np.sqrt(mean_squared_error(y_test, pred)))
print("test R2:", r2_score(y_test, pred))Scikit-learn scorers follow a "higher is better" convention, so error metrics appear with a neg_ prefix and you flip the sign. For classification, use StratifiedKFold so every fold keeps the class balance.
The workflow here is the one from the diagram. Cross-validate on the training portion to compare models and tune settings. Then fit the chosen model on all training data and score it once on the test set.
Diagnosing problems from the numbers
Comparing scores across subsets tells you what is wrong:
- Low training score, low validation score. The model underfits. Try more features or a more flexible model.
- High training score, much lower validation score. The model overfits. Try more data, a simpler model, or regularization.
- Cross-validation scores vary widely between folds. The data is small or uneven, and any single number is unreliable.
- Validation score is good but the test score is much worse. You probably tuned too hard against the validation data, or leakage exists somewhere in the pipeline.
Finally, remember that held-out data only represents the future if the future resembles it. If the real-world data shifts, for example new user behavior or a new sensor, the test score will overstate real performance. Monitor the model after deployment as well.
Exercise
A fraud model is tested on 10,000 transactions, of which 100 are fraudulent. It labels every transaction "not fraud" and reports 99% accuracy. Which metric exposes the problem, what value does it take for this model, and what would you also do to the data split?
Show answer
Recall on the fraud class exposes it. The model finds none of the 100 fraud cases, so TP is 0 and recall is 0 (precision is undefined, and scikit-learn reports 0 with zero_division=0). Accuracy is high only because 99% of the data is the majority class. Use a stratified split so the rare class appears in every training, validation, and test subset, and compare the model against a most-frequent-class baseline.
Exercise
You standardize all features with the mean and standard deviation of the full dataset, then split into train and test sets and report the test score. What is wrong, and how do you fix it?
Show answer
The scaler used test-set statistics, so information from the test data leaked into training and the score is optimistic. Split first, fit the scaler on the training data only, and apply it to the test data. A Pipeline that contains the scaler and the model does this automatically, including inside each cross-validation fold.