Skip to main content

Lesson 4 of 9

Learning Curves & Validation Curves: Diagnosing Overfitting vs Underfitting

Learning curves plot training score and validation score as a function of training dataset size N. They provide definitive empirical diagnosis of a model's bias-variance state: High Bias (underfitting: both training and validation scores plateau at an unacceptable low score) vs High Variance (overfitting: large persistent gap between high training score and lower validation score). Learning curves also reveal whether acquiring additional training data will improve model performance.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Generating & Interpreting Learning Curves in Scikit-Learn

Generating & Interpreting Learning Curves in Scikit-Learn
import numpy as np
import pandas as pd
from sklearn.model_selection import learning_curve, StratifiedKFold
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification

# Generate classification dataset
X, y = make_classification(n_samples=1500, n_features=20, n_informative=10, random_state=42)

def diagnose_learning_trajectory(model, name):
    train_sizes, train_scores, test_scores = learning_curve(
        estimator=model,
        X=X,
        y=y,
        train_sizes=np.linspace(0.1, 1.0, 5), # 10% to 100% of data
        cv=StratifiedKFold(5),
        scoring='roc_auc',
        n_jobs=-1
    )
    
    train_mean = np.mean(train_scores, axis=1)
    test_mean = np.mean(test_scores, axis=1)
    gap = train_mean - test_mean
    
    print(f"=== LEARNING TRAJECTORY DIAGNOSTICS: {name} ===")
    for size, tr, te, g in zip(train_sizes, train_mean, test_mean, gap):
        print(f"Train N={size:4d} | Train AUC: {tr:.4f} | Val AUC: {te:.4f} | Gap: {g:.4f}")
        
    final_gap = gap[-1]
    if final_gap > 0.08:
        print("DIAGNOSIS: High Variance (Overfitting) -> Add regularization, prune features, or gather more data.")
    elif test_mean[-1] < 0.75:
        print("DIAGNOSIS: High Bias (Underfitting) -> Increase model capacity or add non-linear features.")
    else:
        print("DIAGNOSIS: Well-Calibrated Generalization!")

# Model 1: High-Variance Unconstrained Random Forest
rf_deep = RandomForestClassifier(max_depth=15, n_estimators=50, random_state=42)
diagnose_learning_trajectory(rf_deep, "Deep Random Forest")

# Model 2: Well-Regularized Model
rf_reg = RandomForestClassifier(max_depth=4, n_estimators=50, random_state=42)
print()
diagnose_learning_trajectory(rf_reg, "Regularized Random Forest")

Pro Tip: The Plateau Rule for Data Acquisition Budgets

Before requesting an expensive human annotation campaign for 50,000 more samples, inspect the slope of the validation learning curve across your existing sample increments. If the validation curve has completely flattened between 80% and 100% of current data, adding more data will yield negligible gains. Focus on feature engineering instead.

Diagram
Loading diagramโ€ฆ

MlLearningCurves Visual Representation

Hands-On Challenge: Plotting Validation Curves on Hyperparameters

Use `sklearn.model_selection.validation_curve` to plot training and test scores for a `Ridge` regressor across alpha values spanning `np.logspace(-4, 4, 9)`. Identify the sweet spot where validation error is minimized.

Quick Quiz & Key Concept Checks

Common Pitfall: Evaluating Learning Curves Without K-Fold Averaging

Generating a learning curve on a single train-validation split produces noisy, unstable curves influenced by the specific split. Always average across 5-fold cross-validation.

Topics in This Module

0/9 done