TATECHATLAS
◎ English
Math & models / Guide

Analyzing Model Performance: Using Validation Curves to Diagnose Underfitting and Overfitting

This guide explains how to use scikit-learn's validation_curve and ValidationCurveDisplay to visualize the impact of a single hyperparameter on training and validation scores, enabling precise diagnosis of model bias and variance.

On this page

A validation curve is a diagnostic tool used to observe how the performance of a machine learning model changes as a specific hyperparameter is varied. By plotting both the training score and the validation score across a range of hyperparameter values, one can identify whether the model is suffering from high bias (underfitting) or high variance (overfitting). Underfitting is characterized by low scores on both training and validation sets, indicating the model is too simple. Conversely, overfitting is indicated when the training score is high, but the validation score is significantly lower, meaning the model has learned the training data too well but fails to generalize. The validation curve helps pinpoint the optimal hyperparameter range where both scores are high and close together, representing a well-generalized model.

The Role of Validation Curves vs. Learning Curves

The primary purpose of a validation curve is to assess the influence of a single hyperparameter on the model's generalization capability. It plots the training score and the validation score as the hyperparameter is systematically adjusted across a defined range. This differs fundamentally from a learning curve, which examines how the model's performance changes as the size of the training dataset increases.

Understanding these curves requires grasping the Bias-Variance tradeoff. Bias refers to the average error of an estimator across different training sets; a high bias suggests the model is too simple to capture the underlying patterns (underfitting). Variance indicates how sensitive the model is to changes in the training data; high variance suggests the model is too complex and is fitting noise (overfitting). Noise is an inherent property of the data itself.

When using validation curves to select a hyperparameter, remember that the resulting validation score is inherently biased because the hyperparameter selection process itself is influenced by the validation set. Always follow up the selection of the best hyperparameter with an evaluation on a completely held-out test set to obtain an unbiased estimate of the model's true generalization performance.

Decomposing Error: Bias, Variance, and Noise

The generalization error of any estimator can be decomposed into three components: bias, variance, and noise. Bias is the error introduced by approximating a real-world problem with a simplified model. Variance is the error introduced by the model's sensitivity to the specific training data it receives. Noise is the irreducible error present in the data itself. The goal of model tuning is to select algorithms and hyperparameters that minimize both bias and variance simultaneously, achieving the best possible fit to the true function without memorizing the training examples.

Invoking validation_curve: Parameters and Output Structure

The validation_curve function requires the estimator, the dataset, the name of the hyperparameter to tune (param_name), and the range of values to test (param_range). For instance, when tuning the regularization strength 'C' in an SVC model, you provide a logarithmic range of C values. The function returns two arrays: train_scores and valid_scores. These arrays contain the scores calculated across multiple cross-validation folds for every hyperparameter value tested. This structure allows for a robust assessment of performance across different data splits, rather than relying on a single train/test split.

import numpy as np
from sklearn.datasets import load_iris
from sklearn.svm import SVC
from sklearn.model_selection import validation_curve

X, y = load_iris(return_X_y=True)
# Assuming X and y are already split into training data
indices = np.arange(y.shape[0])
train_scores, valid_scores = validation_curve(
    SVC(kernel='linear'),
    X,
    y,
    param_name='C',
    param_range=np.logspace(-7, 3, 3),
)
print(f'Train Scores Shape: {train_scores.shape}')
print(f'Valid Scores Shape: {valid_scores.shape}')

Visualization using ValidationCurveDisplay

While the raw arrays returned by validation_curve are useful for programmatic analysis, the ValidationCurveDisplay class provides a streamlined, high-level interface for visualization. Using ValidationCurveDisplay.from_estimator is often preferred as it handles the entire process of fitting the model across the hyperparameter range and plotting the results automatically, simplifying the workflow significantly. This approach abstracts away the manual handling of cross-validation scores and plotting libraries like Matplotlib.

from sklearn.datasets import load_iris
from sklearn.model_selection import ValidationCurveDisplay
from sklearn.svm import SVC
from sklearn.utils import shuffle
import numpy as np

X, y = load_iris(return_X_y=True)
X, y = shuffle(X, y, random_state=0)
ValidationCurveDisplay.from_estimator(
    SVC(kernel='linear'),
    X,
    y,
    param_name='C',
    param_range=np.logspace(-7, 3, 10),
)

Interpreting the Gap: Underfitting, Overfitting, and Optimal Fit

The decision to classify a model as underfitting or overfitting relies on the relationship between the training and validation scores. If both the training score and the validation score are low, the model is underfitting (high bias); it is too simple to capture the complexity of the data. If the training score is high, but the validation score is significantly lower, the model is overfitting (high variance); it has memorized the training data but fails to generalize. A healthy, well-generalized model will show both scores converging to high values and remaining close to each other across the hyperparameter range.

The Bias of Validation Scores and Generalization

It is crucial to understand that when you optimize a hyperparameter based on the validation score, that validation score becomes biased. This is because the selection process itself has influenced the model's configuration. Therefore, the validation curve is a diagnostic tool for model selection, not a definitive measure of generalization. For a proper, unbiased estimate of how the model will perform on unseen data, the final chosen model must always be evaluated on a separate, completely held-out test set. Furthermore, for complex models or multiple hyperparameters, grid search is often necessary to explore the parameter space systematically.

Common Pitfalls and Data Leakage Prevention

A critical mistake is data leakage, which occurs when information from the validation or test set inadvertently influences the model training process. For example, calculating the mean or standard deviation of features using the entire dataset before splitting it will cause the model to 'see' information about the test set. To prevent this, always use scikit-learn Pipelines. Pipelines ensure that preprocessing steps (like scaling or feature selection) are fitted only on the training folds within the cross-validation loop and then applied consistently to the validation folds, thereby maintaining data integrity.

Controlling Randomness for Reproducible Results

Since many scikit-learn components, including estimators and cross-validation splitters, involve randomness, reproducibility is key. To ensure that results are comparable across different runs, you must control randomness using the random_state parameter. For cross-validation splitters, passing an integer (e.g., random_state=0) ensures that the data splits are identical every time. For estimators, passing a RandomState instance is often preferred to ensure that each fold uses a different random seed, leading to more robust cross-validation results, which is vital for fair comparison between different algorithms.

Things to check

  • The validation curve must be interpreted in the context of the Bias-Variance tradeoff.
  • The validation score is biased when used for hyperparameter tuning; a separate test set is required for final generalization assessment.
  • Data leakage must be prevented by using Pipelines to ensure preprocessing is fitted only on training folds within cross-validation.
  • The interpretation of underfitting (low train/valid scores) and overfitting (high train/low valid scores) must be applied correctly.

The validation curve is limited to assessing the impact of one hyperparameter at a time. For models with many interacting hyperparameters, a grid search or randomized search is necessary. Furthermore, visual inspection of the curve does not always perfectly capture performance in extremely high-dimensional feature spaces, and the choice of metric (e.g., accuracy vs. F1 score) significantly affects the curve's interpretation.

Sources

  1. scikit-learn: learning curves ↗
  2. scikit-learn: common pitfalls ↗
Back to top ↑