Diagnose models with learning curves

scikit-learn 1.9.1

Compare training and validation scores as the amount of training data grows.

On this page

Plot scores across training sizes

learning_curve fits a fresh model with different training-set sizes in each cross-validation split. Plot the mean training and validation accuracy at each size. Shuffling the subset selection here suits the independent records in this example. Choose a splitter that matches time ordering or grouped data when those structures exist.

import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, learning_curve
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_iris(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
sizes, train, valid = learning_curve(
    model, X, y, train_sizes=[0.15, 0.35, 0.60, 1.0], cv=cv,
    scoring="accuracy", shuffle=True, random_state=42,
)

fig, ax = plt.subplots(layout="constrained")
ax.plot(sizes, train.mean(axis=1), "o-", label="Training")
ax.plot(sizes, valid.mean(axis=1), "s--", label="Validation")
ax.set(xlabel="Training examples per fold", ylabel="Mean accuracy")
ax.legend()
plt.show()
A plot shows mean training and validation accuracy at four increasing training sizes, with one line for each score. Download image
At each training size, compare the two scores and the gap between them.

Interpret the gap and the score levels

A persistent gap with a high training score can suggest overfitting. Two similarly low curves can suggest underfitting or limited predictive features. Compare against a baseline and check variation across folds. Keep a separate test set for the final evaluation when choosing models based on validation results.

Official references