Learning Curve and Validation Curve in Python: Diagnose Overfitting and Underfitting

Use scikit-learn's LearningCurveDisplay and ValidationCurveDisplay to tell whether a model is overfitting, underfitting, or needs more data, and to pick a hyperparameter such as max_depth.

A learning curve plots training and cross-validated scores against the size of the training set, and a validation curve plots them against one hyperparameter. In scikit-learn, LearningCurveDisplay.from_estimator(model, X, y) and ValidationCurveDisplay.from_estimator(model, X, y, param_name=..., param_range=...) draw them, and the gap between the two lines tells you whether the model is overfitting or underfitting. The code targets scikit-learn 1.9.

Quick Example

This draws a learning curve for an unpruned decision tree on a noisy synthetic dataset. It runs without downloads.

import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import LearningCurveDisplay
from sklearn.tree import DecisionTreeClassifier

X, y = make_classification(n_samples=4000, n_features=10, n_informative=5, n_redundant=0,
                           n_clusters_per_class=3, flip_y=0.08, class_sep=1.0, random_state=11)

tree = DecisionTreeClassifier(random_state=0)
fig, ax = plt.subplots(figsize=(6.5, 4.2))
LearningCurveDisplay.from_estimator(
    tree, X, y, train_sizes=np.linspace(0.1, 1.0, 8), cv=5, scoring="accuracy",
    score_type="both", ax=ax, random_state=0,
)
ax.set_ylim(0.5, 1.02)
ax.legend(["Training score", "Validation score"], loc="lower right")
plt.show()

Learning curve of an unpruned decision tree: training accuracy stays at 1.0 while validation accuracy rises slowly from 0.68 to 0.73

The training score is 1.0 at every size because an unpruned tree memorizes its training data. Validation accuracy rises from about 0.68 at 320 training samples to 0.73 at 3,200. The big gap is the signature of overfitting.

How Do I Read a Learning Curve?

What you see Diagnosis What to try
Both curves low and close together High bias (underfitting) A more flexible model, better features
Training high, validation much lower High variance (overfitting) More data, regularization, a simpler or averaged model
Validation still rising at the right edge More data would help Collect more data
Validation flat at the right edge More data will not help Change the model or the features

Three models on the same data show the first two cases:

Three learning curves: logistic regression with training and validation both near 0.74, an unpruned tree with training 1.0 and validation 0.73, and a random forest with training 0.97 and validation 0.82

  • Logistic regression is stuck at about 0.74 training and 0.74 validation. The lines meet, and more data will not lift them, since a linear boundary cannot represent this data.
  • The unpruned tree has training accuracy 1.0 and validation accuracy of 0.73. It has the capacity but memorizes noise.
  • A random forest (n_estimators=200, min_samples_leaf=3) reaches 0.82 validation accuracy. Training accuracy is 0.97, so a gap remains, but the validation line is clearly higher and still rising, which suggests more data would help.

Choose a Hyperparameter with a Validation Curve

A validation curve scores the model across a range of one setting. ValidationCurveDisplay.from_estimator needs param_name and param_range:

from sklearn.model_selection import ValidationCurveDisplay, validation_curve

depths = np.arange(1, 21)
fig, ax = plt.subplots(figsize=(6.5, 4.2))
ValidationCurveDisplay.from_estimator(
    DecisionTreeClassifier(random_state=0), X, y,
    param_name="max_depth", param_range=depths, cv=5, ax=ax,
)
ax.set_ylim(0.5, 1.02)
plt.show()

train_scores, val_scores = validation_curve(
    DecisionTreeClassifier(random_state=0), X=X, y=y,
    param_name="max_depth", param_range=depths, cv=5,
)
best = depths[val_scores.mean(axis=1).argmax()]
print("best max_depth:", best, "validation accuracy:", round(val_scores.mean(axis=1).max(), 3))

Validation curve for decision tree max_depth: training accuracy climbs to 1.0 while validation accuracy peaks near depth 7 at 0.77 and then declines to 0.73

Training accuracy climbs to 1.0 as max_depth grows. Validation accuracy peaks at max_depth=7 (0.766) and drifts down to 0.732 at depth 20. The left side of the curve is underfitting, the right side is overfitting, and the best setting is where validation peaks. The peak is flat and the bands overlap, so depths of 6 to 9 are about equally good. Prefer the simpler one.

Learning Curve vs Validation Curve

Learning curve Validation curve
X-axis Training set size One hyperparameter
Answers Do I need more data? Is it bias or variance? Which setting balances bias and variance?
Function LearningCurveDisplay, learning_curve ValidationCurveDisplay, validation_curve
Cost Refits the model at each size and fold Refits the model at each value and fold

Practical Tips

  • The Display classes draw a mean line and a band of one standard deviation across the folds by default. Pass std_display_style="errorbar" for error bars.
  • Use scoring= to match the metric you care about, such as "roc_auc" or "neg_mean_squared_error". For error scores, pass negate_score=True to plot them as positive numbers.
  • For time-ordered data, pass a time-series splitter such as TimeSeriesSplit as cv. Shuffled folds leak the future.
  • Use n_jobs=-1 for expensive models. The functions refit once per fold and size.
  • Choose the hyperparameter on the validation curve, then confirm on a separate test set. The validation curve has already seen the data you tuned on.

Similar Topics