Sub topic 8
Reading learning curves
This chapter assumes you can fit scikit-learn models, know the bias-variance trade-off, and have used k-fold cross-validation. A single training and validation score tells you how a model does at one dataset size. A learning curve shows how both scores change as the training set grows. The extra information helps you decide what to do next.
What a learning curve plots
A learning curve has the number of training examples on the x-axis and an error (or score) on the y-axis. It usually has two lines:
- The training error, measured on the examples the model was fitted to.
- The validation error, measured on held-out examples. With cross-validation, each point is the mean over the folds.
Two quantities matter more than the exact values:
- The gap between the two lines.
- The level where the lines flatten out.
A learning curve is different from a validation curve. A validation curve varies a hyperparameter such as model degree or alpha at a fixed dataset size. A learning curve varies the dataset size and fixes the model.
How the lines behave
With very few examples, a flexible model can fit the training set almost perfectly, so training error starts low. As you add examples, the model can no longer fit every point, so training error rises. Validation error usually starts high, because a model fitted to a handful of points generalises poorly, and falls as the data grows.
The two lines move toward each other. Where they end up tells you which problem you have.
The two patterns
| Pattern | Training error | Validation error | Gap | Diagnosis |
|---|---|---|---|---|
| Both curves plateau high and close together | High | High | Small | High bias (underfitting) |
| Training error low, validation error much higher | Low | High | Large | High variance (overfitting) |
| Both low and close together | Low | Low | Small | Good fit |
"High" and "low" are relative to something. Compare against the noise level of the problem, a simple baseline such as predicting the mean, or the error you need for the application. A training MSE of 0.3 is high if the irreducible noise is 0.04, and fine if it is 0.3.
Computing a learning curve
scikit-learn provides learning_curve. It refits the model on increasing fractions of the training data and returns the scores for each cross-validation fold. The example below compares a degree-1 polynomial (too simple) with a degree-15 polynomial (very flexible) on noisy sine data.
import numpy as np
from sklearn.model_selection import learning_curve
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(300, 1))
y = np.sin(X).ravel() + rng.normal(0, 0.2, size=300)
for degree in (1, 15):
model = make_pipeline(
PolynomialFeatures(degree), StandardScaler(), LinearRegression()
)
sizes, train_scores, val_scores = learning_curve(
model,
X,
y,
train_sizes=np.linspace(0.1, 1.0, 6),
cv=5,
scoring="neg_mean_squared_error",
shuffle=True,
random_state=0,
)
train_mse = -train_scores.mean(axis=1)
val_mse = -val_scores.mean(axis=1)
print(f"degree {degree}")
for n, tr, va in zip(sizes, train_mse, val_mse):
print(f" n={n:4d} train={tr:.3f} val={va:.3f}")Three details of this call matter:
scoringuses the "negative MSE" convention, so higher is better. Negate the scores to get an error, as the code does.shuffle=Truerandomises the order before splitting. Without it, data stored in sorted order gives folds that differ systematically.- The scaler is inside the pipeline. Each fit then scales using only its own training portion, which avoids leakage.
You should see the degree-1 model's training and validation errors converge to a similar, fairly high value. The degree-15 model should show a smaller training error with a visible gap, and its validation error should be unstable at the smallest sizes. The exact numbers depend on your library versions, so look at the shape, not the digits.
Interpreting the high-bias case
If both curves flatten at a high error close together, the model cannot represent the pattern. More data does not help. The training error is already high, and the validation error cannot fall below it by much. Collecting more data is the most expensive remedy and the least useful here.
Useful remedies are:
- Increase capacity, for example a higher polynomial degree or a deeper tree.
- Add or engineer features that capture the missing structure.
- Reduce regularisation, since a penalty that is too strong creates bias.
Interpreting the high-variance case
If training error is low and validation error sits well above it, the model is fitting noise. Look at the slope of the validation curve at the largest training size:
- If it is still falling, the gap is closing and more data (or augmentation) should help.
- If it is flat, more data of the same kind will give little. Reduce variance by other means: regularisation, a simpler model, early stopping, dropout, or fewer features.
This slope check is the main thing a learning curve tells you that a single train/validation pair cannot. It lets you estimate the benefit of data collection before you pay for it.
Common errors when reading curves
- Ignoring noise in the estimates. With 5 folds and small data, each point is noisy. Plot the standard deviation across folds as a band. If the bands overlap, do not read a difference into the lines.
- Comparing curves on different scales. An error that looks high on one plot may be near the noise floor. Always mark a baseline or the target error.
- Using the test set. Learning curves are a tuning and diagnosis tool, so compute them on training and validation data only. If you pick a model by looking at test error, the test set no longer gives an unbiased estimate.
- Leakage inflating the validation line. If preprocessing is fitted on all the data before splitting, the validation curve looks better than it should. A suspiciously small gap, or validation error below training error, can signal this.
- Validation error below training error. This can be legitimate. Dropout is active only during training, and regularisation terms inflate the training loss. Compare like with like before suspecting a bug.
- Mixing up score and error. With a score metric such as accuracy, the curves invert. A high training score and lower validation score indicates overfitting.
Cost considerations
learning_curve fits the model cv × len(train_sizes) times. For slow models, use fewer sizes, fewer folds, or a subsample, and pass n_jobs=-1 to run fits in parallel. For neural networks, plot loss against epochs on a fixed training set instead. That is a different curve, and it is the one used by early stopping. Use learning curves for data-size questions and epoch curves for training-length questions.
Exercise
A model has training MSE 0.05 and validation MSE 0.40 at the largest training size. The validation curve is still falling with each added chunk of data. Which problem does it have, and what are two sensible next steps?
Show answer
It has high variance (overfitting), because the training error is low and the gap to validation error is large. Since the validation curve is still falling, collecting more data or augmenting the existing data should help. Strengthening regularisation or reducing model capacity are also reasonable. Adding capacity would be the wrong move.
Exercise
Both the training and validation errors plateau at about 0.45, close together, while the noise level of the problem is about 0.04. A colleague suggests collecting ten times more data. Is that a good idea?
Show answer
No. Both curves are high and close together, which indicates high bias. The model is too simple for the pattern, and more data will not lower the plateau. A better plan is to increase capacity, add features, or reduce regularisation, then recompute the curve.