Sub topic 6
Computing a learning curve
This chapter assumes you know how to fit a scikit-learn estimator and how training and validation scores differ. It also assumes you know what cross-validation does. Here you compute the curve. The next chapter covers how to read it.
What a learning curve measures
A learning curve answers one question: how do the training score and the cross-validated score change as the model sees more training samples? For each training size, the model is refit from scratch and scored twice. One score comes from the data it trained on. The other comes from held-out data.
Calling learning_curve
import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import learning_curve
X, y = load_digits(return_X_y=True)
train_sizes, train_scores, val_scores = learning_curve(
LogisticRegression(max_iter=2000),
X,
y,
train_sizes=np.linspace(0.1, 1.0, 5),
cv=5,
scoring="accuracy",
)
print(train_sizes)
print(train_scores.mean(axis=1))
print(val_scores.mean(axis=1))Three details of the return values matter.
train_sizesholds absolute sample counts, not the fractions you passed in. Fractions are taken relative to the training portion of one split. With 5 folds on 1,797 digits, the largest size is about 1,437, not 1,797.train_scoresandval_scoreshave shape(n_sizes, n_folds). Each row is one size and each column is one fold.- Averaging over
axis=1gives one number per size. Averaging overaxis=0would mix different sizes, which is a common mistake.
Parameters worth knowing
| Parameter | Effect |
|---|---|
| `train_sizes` | Fractions (floats in 0 to 1) or absolute counts (integers). More points give a smoother curve but cost more fits. |
| `cv` | An integer uses stratified folds for classifiers. Pass a splitter object for grouped or time-ordered data. |
| `scoring` | The metric for both curves. Use the same one you will use to judge the final model. |
| `shuffle` | Defaults to `False`. Set it to `True`, with a `random_state`, if your rows are ordered by class or by time and you are not using a time-aware splitter. |
| `n_jobs` | Runs fits in parallel. |
The total cost is roughly len(train_sizes) × n_folds model fits. Five sizes and five folds already means 25 fits, so start coarse.
Plotting the mean and spread
import matplotlib.pyplot as plt
train_mean = train_scores.mean(axis=1)
train_std = train_scores.std(axis=1)
val_mean = val_scores.mean(axis=1)
val_std = val_scores.std(axis=1)
fig, ax = plt.subplots()
ax.plot(train_sizes, train_mean, marker="o", label="Training score")
ax.fill_between(train_sizes, train_mean - train_std, train_mean + train_std, alpha=0.2)
ax.plot(train_sizes, val_mean, marker="o", label="Cross-validation score")
ax.fill_between(train_sizes, val_mean - val_std, val_mean + val_std, alpha=0.2)
ax.set_xlabel("Number of training samples")
ax.set_ylabel("Accuracy")
ax.legend()
plt.show()The shaded bands show one standard deviation across folds. They tell you how much a single curve point can be trusted.
Avoiding leakage in the curve
If you scale or otherwise preprocess data, put those steps inside a pipeline. The pipeline refits them on each training subset. Scaling the full dataset first leaks information from the validation folds into the curve.
import numpy as np
from sklearn.model_selection import GroupKFold, learning_curve
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
# X, y as before; groups holds one group label per sample (for example a patient or user ID).
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000))
train_sizes, train_scores, val_scores = learning_curve(
model,
X,
y,
groups=groups,
cv=GroupKFold(n_splits=5),
train_sizes=np.linspace(0.2, 1.0, 5),
scoring="accuracy",
)GroupKFold keeps all samples from one group on the same side of a split. Without it, related samples such as several records from one patient appear in both training and validation. That makes the validation score look better than it is.
Exercise
A call to learningcurve with 6 training sizes and cv=4 returns valscores. What is its shape, and which axis do you average to get one score per training size?
Show answer
The shape is (6, 4): six sizes by four folds. Average over axis=1, which collapses the folds and leaves one mean per size.