Your model scores 0.69. Should you collect more data, pick a more flexible model, or simplify the one you have? Guessing wastes weeks: collecting data takes time, and if the model can't use it, nothing improves. Two plots answer the question with evidence. A validation curve shows how the score changes as you turn one setting up and down. A learning curve shows how it changes as the model gets more training data. Learning curves and validation curves both plot a training score next to a validation score, and the gap between the two lines, and where they're heading, tells you what to do next.
What you need first: the bias-variance trade-off, cross-validation, decision trees explained and R² from regression metrics.
Key terms
- Validation curve: training and validation scores plotted against one setting of the model, such as tree depth.
- Learning curve: training and validation scores plotted against the number of training rows.
- Generalisation gap: the training score minus the validation score; a large gap means overfitting.
- High bias: both scores low and close together; the model is too simple (underfitting).
- High variance: training score high, validation score much lower; the model memorises (overfitting).
The data
The California housing data: 20,640 districts, 8 numeric features such as median income and house age, and the median house value in units of $100,000. R² is the score: 1 is perfect, 0 is no better than predicting the average.
Download the data: california-housing.csv (1.9 MB), or from the original source, the StatLib repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("california-housing.csv").
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import KFold
housing = fetch_california_housing(as_frame=True)
X, y = housing.data, housing.target
cv = KFold(n_splits=5, shuffle=True, random_state=0)
print(X.shape)
(20640, 8)
fetch_california_housing downloads the data the first time and keeps a copy. KFold(..., shuffle=True) makes 5 cross-validation folds from shuffled rows; every curve below uses the same folds, so the curves are comparable.
Validation curve: one setting, many values
A decision tree's max_depth controls how many questions it may ask in a row. Predict first: as depth goes from 1 to 20, the training score will keep rising. What will the validation score do?
from sklearn.model_selection import validation_curve
from sklearn.tree import DecisionTreeRegressor
depths = range(1, 21)
train_scores, val_scores = validation_curve(
DecisionTreeRegressor(random_state=0), X, y,
param_name="max_depth", param_range=depths, cv=cv, scoring="r2", n_jobs=-1)
train_mean, val_mean = train_scores.mean(axis=1), val_scores.mean(axis=1)
best = depths[int(np.argmax(val_mean))]
for d in [2, 5, best, 20]:
print(f"depth {d:2}: train R² {train_mean[d - 1]:.3f}, validation R² {val_mean[d - 1]:.3f}")
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(depths, train_mean, marker="o", label="Training")
ax.plot(depths, val_mean, marker="o", label="Validation")
ax.axvline(best, color="grey", linestyle="--")
ax.set_xlabel("max_depth")
ax.set_ylabel("R²")
ax.set_title("Validation curve for a decision tree")
ax.legend()
plt.show()
depth 2: train R² 0.448, validation R² 0.443
depth 5: train R² 0.633, validation R² 0.615
depth 9: train R² 0.795, validation R² 0.695
depth 20: train R² 0.996, validation R² 0.615
validation_curve trains one model per depth per fold (20 × 5 = 100 trees) and returns two tables of scores, one row per depth and one column per fold; .mean(axis=1) averages across the folds. n_jobs=-1 uses every processor core.
The two lines tell a story in three parts. Up to about depth 5 they rise together and stay close: the tree is too simple, and both scores are low (high bias). From depth 6 the training line pulls away: the tree is starting to fit details of the training rows. The validation line peaks at depth 9 with R² 0.695 and then falls, down to 0.615 at depth 20, while training reaches 0.996. A depth-20 tree has nearly memorised the training districts, and that memory doesn't carry over. The best depth is where validation peaks, not where training does.
Learning curve: more and more data
A learning curve keeps the model fixed and trains it on growing slices of the data: 2% of the training rows, then 5%, and so on up to all of them. Each size is cross-validated, so every point is an average of 5 fits.
from sklearn.model_selection import learning_curve
def plot_learning_curve(model, X, y, title, ax):
sizes, train_scores, val_scores = learning_curve(
model, X, y, train_sizes=[0.02, 0.05, 0.1, 0.25, 0.5, 1.0],
cv=cv, scoring="r2", shuffle=True, random_state=0, n_jobs=-1)
ax.plot(sizes, train_scores.mean(axis=1), marker="o", label="Training")
ax.plot(sizes, val_scores.mean(axis=1), marker="o", label="Validation")
ax.set_xscale("log")
ax.set_xlabel("Training rows (log scale)")
ax.set_ylabel("R²")
ax.set_title(title)
ax.legend()
return sizes, train_scores.mean(axis=1), val_scores.mean(axis=1)
train_sizes are shares of the training part of each fold (16,512 rows), so 0.02 means 330 rows. shuffle=True makes the small slices random rows rather than the first rows in the file. A log scale spreads out the small sizes, where most of the change happens.
Experiment: draw learning curves for the depth-8 tree and for histogram gradient boosting. Predict first: for which model will more data help more?
from sklearn.ensemble import HistGradientBoostingRegressor
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5), sharey=True)
for model, title, ax in [(DecisionTreeRegressor(max_depth=8, random_state=0), "Decision tree, depth 8", axes[0]),
(HistGradientBoostingRegressor(random_state=0), "Gradient boosting", axes[1])]:
sizes, train_mean, val_mean = plot_learning_curve(model, X, y, title, ax)
print(f"{title}: rows {sizes[0]} -> {sizes[-1]}")
print(f" train {train_mean[0]:.3f} -> {train_mean[-1]:.3f}, validation {val_mean[0]:.3f} -> {val_mean[-1]:.3f}")
plt.tight_layout()
plt.show()
Decision tree, depth 8: rows 330 -> 16512
train 0.947 -> 0.756, validation 0.426 -> 0.688
Gradient boosting: rows 330 -> 16512
train 0.961 -> 0.880, validation 0.685 -> 0.837
Both pictures show the same shape: the training line falls as the rows grow, because memorising 16,512 rows is harder than memorising 330, and the validation line rises, because more examples teach patterns that hold. Where they differ is what that means for you:
- The tree has a large gap at every size (0.756 against 0.688 at the end) and validation is still climbing: more data would help a little, but most of the gap is the tree's fixed limit of 256 leaves. Changing the model will help more.
- Gradient boosting is better at every size: with only 330 rows it already matches the tree trained on all 16,512, and its validation score is still rising at the right edge (0.837). This model could use more data, and it's the better model to invest in.
See it fail: a curve that makes no sense
Try the same with plain linear regression, which should give the dullest learning curve there is:
from sklearn.linear_model import LinearRegression
sizes, train_scores, val_scores = learning_curve(
LinearRegression(), X, y, train_sizes=[0.02, 0.05, 0.25, 1.0],
cv=cv, scoring="r2", shuffle=True, random_state=0)
print("validation R², one row per size, one column per fold:")
print(val_scores.round(2))
validation R², one row per size, one column per fold:
[[ 0.59 0.59 -5.06 -8.68 0.64]
[ 0.59 0.62 -5.15 -5.72 0.64]
[ 0.59 0.63 -3.17 -5.27 0.64]
[ 0.59 0.6 0.6 0.6 0.62]]
Folds 3 and 4 score R² of −5 to −9 with up to 4,128 training rows: far worse than predicting the average for every district. The other three folds score about 0.6. With all 16,512 training rows, every fold is back to 0.6. One model, one dataset, and the curve depends almost entirely on which fold you look at.
The cause is a handful of districts with impossible averages. Some census districts contain a hotel, prison or holiday homes, so "average rooms per household" or "average occupants" comes out absurd:
print(X[["AveRooms", "AveBedrms", "AveOccup"]].describe().loc[["50%", "max"]].round(1))
sensible = (X["AveOccup"] < 10) & (X["AveRooms"] < 20) & (X["AveBedrms"] < 5)
print(f"keeping {sensible.sum()} of {len(X)} districts")
fig, ax = plt.subplots(figsize=(7, 4.5))
sizes, train_mean, val_mean = plot_learning_curve(
LinearRegression(), X[sensible], y[sensible], "Linear regression, extreme rows removed", ax)
ax.set_ylim(0.4, 1.0)
plt.show()
print(f"train {train_mean[0]:.3f} -> {train_mean[-1]:.3f}, validation {val_mean[0]:.3f} -> {val_mean[-1]:.3f}")
AveRooms AveBedrms AveOccup
50% 5.2 1.0 2.8
max 141.9 34.1 1243.3
keeping 20532 of 20640 districts
train 0.676 -> 0.660, validation 0.647 -> 0.660
describe() summarises each column; .loc[["50%", "max"]] keeps the median and the largest value. sensible is True for districts with believable averages. ax.set_ylim(0.4, 1.0) puts the chart on the same scale as the tree charts, so small wiggles don't look like big changes.
The median district has 2.8 occupants per household; the most extreme has 1,243. Those few rows sit in validation folds 3 and 4. A linear model multiplies each feature by a fixed coefficient, so a value 400 times the usual one produces an absurd prediction, and one absurd prediction is enough to sink R² for the whole fold. A tree just sends such a row to its outermost leaf, which is why the tree curves above were unaffected. With all training rows, some extreme districts also land in training, which seems to rein the coefficients in.
With the 108 extreme districts removed, the real learning curve appears: training and validation start close (0.676 and 0.647) and meet at 0.660. That's high bias, textbook clear. A straight-line model has learned nearly all it can within the first couple of thousand rows; the rest add about 0.004. More data won't help this model; a more flexible one will, as gradient boosting's 0.837 shows.
The broader lesson: when a curve looks strange, print the scores for each fold before believing the average.
Reading learning curves and validation curves
| What you see | Diagnosis | What helps | What won't help |
|---|---|---|---|
| Both scores low and close together | High bias (underfitting) | A more flexible model, better features | More data |
| Training high, validation much lower, gap shrinking as rows grow | High variance, data-hungry | More data, regularisation, a simpler model | A more flexible model |
| Training high, validation much lower, gap not shrinking | High variance | Regularisation, a simpler model, fewer noisy features | More of the same data |
| Validation still rising at the right edge | The model can use more data | More data | |
| Validation flat at the right edge | More data won't change much | A different model or better features | More data |
| Validation falls as a setting grows | The setting causes overfitting | Choose the value at the validation peak |
Practice
- Without running code: a learning curve shows training R² 0.62 and validation R² 0.61, both flat from 2,000 rows onwards. Your manager offers to buy ten times more data. What do you say?
Show the answer
Don't buy it. Both curves have met and are flat, so the model has learned all it can: that's high bias. Spend the effort on a more flexible model or better features instead.
- Draw a validation curve for
min_samples_leafof a decision tree with no depth limit, using values 1, 2, 5, 10, 20, 50, 100 and 200. Which value is best?
Show the answer
leaves = [1, 2, 5, 10, 20, 50, 100, 200]
tr, va = validation_curve(DecisionTreeRegressor(random_state=0), X, y,
param_name="min_samples_leaf", param_range=leaves, cv=cv, scoring="r2", n_jobs=-1)
for leaf, a, b in zip(leaves, tr.mean(axis=1), va.mean(axis=1)):
print(f"min_samples_leaf {leaf:3}: train {a:.3f}, validation {b:.3f}")
min_samples_leaf 1: train 1.000, validation 0.614
min_samples_leaf 2: train 0.976, validation 0.644
min_samples_leaf 5: train 0.910, validation 0.694
min_samples_leaf 10: train 0.857, validation 0.721
min_samples_leaf 20: train 0.810, validation 0.726
min_samples_leaf 50: train 0.754, validation 0.708
min_samples_leaf 100: train 0.716, validation 0.687
min_samples_leaf 200: train 0.670, validation 0.652
A leaf size of 20 scores best (0.726), better than the best depth limit (0.695). With a leaf size of 1 the tree memorises everything (training 1.000); at 200 it's too coarse and both scores fall. Limiting the leaf size lets the tree grow deep where there's a lot of data and stay shallow where there's little, which a single depth limit can't do.
- Why does the training score of the depth-8 tree go down as the training set grows?
Show the answer
With 330 rows, a tree with up to 256 leaves can almost memorise them. With 16,512 rows, the same number of leaves must each cover many rows, so it can't fit each one exactly. The training score falls towards the validation score as memorising gets harder.
- Why use cross-validation for these curves instead of one train/validation split?
Show the answer
With one split, every point on the curve depends on which rows landed in the validation set, and with small training sizes that noise can be bigger than the effect you're looking for. Averaging 5 folds smooths it out. The linear regression example shows how much one fold can differ from the others.
- A validation curve's best depth is 9, but depths 8 to 11 score within 0.01 of it. Which would you choose, and why?
Show the answer
Usually the smallest of the near-best values, depth 8: it scores almost the same, is simpler, trains faster and is less likely to have been picked for noise. Differences of 0.01 are within the fold-to-fold variation.
Interview questions
What is a learning curve and what does it tell you?
A plot of training and validation scores against training set size. If both are low and converge, the model has high bias and more data won't help. If there's a large gap that narrows with more data, the model has high variance and more data or regularisation will help.
What's the difference between a learning curve and a validation curve?
A learning curve varies the amount of training data with the model fixed. A validation curve varies one hyperparameter with the data fixed. Both plot training and validation scores.
Why does training error usually increase with more data?
A model of fixed flexibility can fit a few rows almost perfectly, but as rows are added it can't fit them all exactly, so training error rises towards the true error level, while validation error falls towards it.
Key takeaways
- A validation curve shows the effect of one setting; a learning curve shows the effect of more data.
- The gap between training and validation scores measures overfitting; low, close scores mean underfitting.
- If the validation curve is still rising at the right edge, more data helps; if it's flat, change the model or features instead.
- Build the curves with cross-validation, and look at the folds when a curve looks strange.
- A few extreme rows can wreck a linear model's validation score; tree models aren't affected the same way.
Frequently asked questions
How many training sizes should a learning curve use?
Five or six, spread on a log scale from a few hundred rows to all of them, is enough to see the shape. Each size costs one fit per fold, so more points mainly cost time.
Can I draw learning curves for classification?
Yes: pass a classification model and a classification scoring rule, such as scoring="accuracy" or "roc_auc". Use StratifiedKFold so every fold keeps the class balance.
What if the validation score is higher than the training score?
It happens with heavy regularisation, dropout in neural networks, or by chance with small validation sets. If it persists, check that the two sets come from the same population and that nothing leaks between them.
What to learn next
- Find out which rows the model gets wrong, and why, in error analysis, the next lesson.
- Revisit the theory behind the curves in the bias-variance trade-off.
- Tune many settings at once in hyperparameter tuning with grid search.