Sub topic 6
Computing a Learning Curve
This chapter assumes you know supervised learning basics (features, labels, training and test sets) and basic Python and NumPy. It also assumes you can use scikit-learn estimators through fit, predict, and score, and that you know overfitting and hyperparameters at a working level. Here you compute a learning curve. The next chapter covers how to read one.
What a learning curve measures
A learning curve answers one question: how does the score change as the model sees more training data? You pick several training set sizes. For each size, you train the model on that many samples and record two numbers:
- The training score, measured on the samples the model was fitted on.
- The validation score, measured on held-out samples the model never saw.
Plotting both scores against the training set size gives two curves. Their levels and their gap are what you diagnose later.
The validation score is not computed on a single split. scikit-learn repeats the procedure inside cross-validation, so each point on a curve is an average over several folds. That is why the function returns arrays with one column per fold.
How `learning_curve` works internally
For every cross-validation split, scikit-learn takes the training part of the split. It then fits the estimator on the first k samples of that part, once for each requested size k. Each fit is scored on both the k training samples and the full validation part of the split.
Three consequences follow from this design:
- The validation part stays the same for every size within a fold. The curve therefore changes only because the training size changes, not because the test data changed.
- The training subsets are nested within a fold. The 500-sample subset contains the 200-sample subset.
- The largest possible training size is the size of one training part, not the full dataset. With 5-fold cross-validation, that is about 80% of your data.
A first learning curve
The function returns three values: the absolute training sizes, the training scores, and the validation scores. The score arrays have shape (n_sizes, n_folds).
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.shape)
print(train_scores.mean(axis=1))
print(val_scores.mean(axis=1))Averaging over axis=1 collapses the fold dimension. You get one training score and one validation score per size. The train_sizes array holds integers, not the fractions you passed in.
Choosing training sizes
The train_sizes argument accepts two forms, and scikit-learn decides which one you used from the dtype:
| Form | Example | Meaning |
|---|---|---|
| Floats in (0, 1] | `np.linspace(0.1, 1.0, 5)` | Fractions of the largest training part in a split |
| Integers | `[100, 300, 600, 1000]` | Exact numbers of samples |
Fractions apply to the training part of a split, not the whole dataset. With 1,797 samples and cv=5, a fraction of 1.0 means roughly 1,437 samples. Integers must not exceed that maximum, or the call raises an error.
Some practical guidance on spacing:
- Use at least five sizes. Three points hide the shape of the curve.
- Start small, but not so small that a class is missing from a subset. A subset with fewer samples than classes can make some estimators fail.
- Linear spacing is fine for moderate datasets. For large datasets, use
np.logspaceor a hand-picked list of integers, because the interesting changes happen early.
Controlling the splits
By default, learning_curve does not shuffle. The subsets are the first k samples of each training part, in their original order. If your data is sorted by class or by time, the small subsets will be unrepresentative, and the early points on the curve will mislead you.
Set shuffle=True and a random_state to get reproducible, mixed subsets:
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, fit_times, score_times = learning_curve(
LogisticRegression(max_iter=2000),
X,
y,
train_sizes=np.linspace(0.1, 1.0, 5),
cv=5,
scoring="accuracy",
shuffle=True,
random_state=0,
n_jobs=-1,
return_times=True,
)
print("fit time per size (s):", fit_times.mean(axis=1).round(3))The shuffle option shuffles the data before the training subsets are taken. When you pass an integer cv, a classifier gets stratified folds automatically, and a regressor gets plain KFold. If you pass your own splitter, its settings decide how the folds are drawn.
Setting return_times=True adds two more arrays of the same shape: fit times and score times. They let you see how cost grows with data. That matters when the curve suggests collecting more data.
Key parameters
| Parameter | Role | Common choice |
|---|---|---|
| `estimator` | Model or pipeline, cloned for each fit | Any scikit-learn estimator |
| `train_sizes` | Sizes to evaluate | `np.linspace(0.1, 1.0, 5)` or more |
| `cv` | Splitting strategy | `5`, or a splitter object |
| `scoring` | Metric used for both curves | A scorer name or callable |
| `shuffle`, `random_state` | Mix the data before subsets are taken | `True` and a fixed seed |
| `n_jobs` | Parallel fits | `-1` for all cores |
| `groups` | Group labels for grouped splitters | Used with `GroupKFold` |
| `error_score` | Value recorded if a fit fails | `np.nan` to see failures instead of stopping |
The scoring argument applies to both curves. It uses the scorer's "greater is better" convention. For error metrics such as mean squared error, scikit-learn exposes negated versions like "neg_mean_squared_error". Your curves then show negative numbers, and a higher curve is still better.
Plotting the mean and the spread
Raw averages hide how much the folds disagree. Plot each mean with a band of one standard deviation across folds:
import numpy as np
import matplotlib.pyplot as plt
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",
shuffle=True,
random_state=0,
)
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 x-axis uses the absolute sizes returned by the function, not the fractions you requested. A narrow band means the folds agree. A wide band at small sizes is normal, because a few samples make each fit unstable.
Common errors and edge cases
- Wrong maximum size. Passing integers larger than one training part raises a
ValueError. Check the size of a training split first, or use fractions. - Duplicate sizes. Fractions that round to the same integer are merged, and scikit-learn warns that fewer sizes are returned. Your score arrays then have fewer rows than you planned.
- Preprocessing outside the estimator. If you scale or select features on all of
Xbefore callinglearning_curve, information from the validation parts leaks into training. Put those steps in aPipelineso they are refitted inside each split. The pitfalls chapter covers this in detail. - Dependent samples. If several rows come from the same patient, user, or device, ordinary folds put the same group on both sides of a split and inflate the validation score. Pass
groupstogether with a grouped splitter such asGroupKFold. - Unstable fits. A model that fails to converge on a small subset can raise an error or return poor scores. Setting
error_score=np.nanrecords the failure so you can see where it happened. - Cost. The number of fits is
n_sizes × n_folds. Five sizes and five folds mean 25 fits. For slow models, reduce the folds or sizes, or usen_jobs. - Incremental learners. For estimators with
partial_fit,exploit_incremental_learning=Truetrains each fold once and feeds it new data between sizes. It saves time, but the model then sees the data in a fixed order.
Exercises
Exercise
You call learningcurve with cv=5 on a dataset of 1,000 samples and pass trainsizes=[200, 500, 900]. What happens, and how would you fix it?
Show answer
It raises a ValueError. With 5-fold cross-validation, each training part has about 800 samples, so 900 exceeds the maximum. Either lower the largest size to 800 or less, or pass fractions such as np.linspace(0.25, 1.0, 4), which are scaled to the training part of a split.
Exercise
After running learningcurve, trainscores has shape (6, 5). What do the two numbers mean, and which expression gives one validation score per training size?
Show answer
The 6 is the number of training sizes and the 5 is the number of cross-validation folds. Averaging over the fold axis gives one value per size: val_scores.mean(axis=1).
Exercise
Your dataset is sorted by class label. You run learning_curve with the defaults, and the smallest training sizes give strange scores. Why does this happen, and which arguments help?
Show answer
Without shuffling, each subset is the first k samples of the training part, so with sorted data the small subsets contain only a few classes and are not representative. Set shuffle=True with a fixed random_state so the subsets are mixed and reproducible.