Diagnosing High Variance from Error Plots

Hard · Machine Learning · Data Scientist · Onsite

Prompt

While evaluating a supervised machine learning pipeline, you inspect a diagnostic chart with training iterations (or model capacity) along the horizontal axis and prediction error along the vertical axis. As iterations or capacity increase, in-sample training error keeps falling, whereas validation error and held-out test error reach an early minimum and then turn upward—opening a steadily widening gap between training fit and out-of-sample accuracy.

Walk through the following four questions:

  1. Which generalization issue does this curve pattern indicate, and how do you separate it from look-alike failure modes?
  2. What common modeling, optimization, or dataset characteristics drive this behavior?
  3. How can you confirm the diagnosis rigorously without leaking signal from the held-out test split?
  4. What practical interventions—ordered from fastest wins to deeper structural changes—would you apply to improve out-of-sample generalization?

Scope & Expectations

  • Accurate diagnosis of high variance (overfitting) contrasted against high bias (underfitting) and train/validation distribution mismatch.
  • Clear explanation of underlying drivers: excess model capacity relative to sample size, over-long training, missing regularization, label noise, and spurious high-cardinality features.
  • Disciplined validation hygiene using validation curves, sample-size learning curves, cross-validation, and standard-error checks while keeping the test split strictly locked until one final check.
  • Actionable, prioritized remedies including early stopping, explicit penalties (weight decay, dropout, tree constraints), feature pruning, data cleaning/augmentation, and variance-reducing ensembles.

Step-by-step walkthrough

  1. Read the curves: identify overfitting and rule out look-alikes

    First define the axes clearly: an epoch is one complete training pass over the training dataset (more generally, the x-axis measures optimization time or model flexibility), training error measures mistakes on the exact rows the model fitted, and out-of-sample error (validation and test error) measures mistakes on held-out rows the model never trained on.

    Visualizing the described plot side by side with illustrative numbers makes the pattern unmistakable:

    Prediction
      Error ^
       0.40 |                                          *  Test error (0.39)
            |   * (0.34)                             o    Validation error (0.38)
       0.30 |   o (0.33)      * (0.30)
            |   x (0.30)      o (0.29)  <- sweet spot (validation minimum at epoch 20)
       0.20 |
            |                 x (0.12)
       0.10 |
            |                                          x  Training error (0.02)
       0.00 +---+-------------+------------------------+-----> Epoch / Complexity
                5            20                       60
    
    Epoch   Training error   Validation error   Test error   Generalization gap (val - train)
    -----   --------------   ----------------   ----------   --------------------------------
      5          0.30              0.33            0.34                   0.03
     20          0.12              0.29            0.30                   0.17  <- best generalization
     60          0.02              0.38            0.39                   0.36  <- severe overfitting
    

    The diagnosis is overfitting (also called high variance): past epoch 20, the model stops learning true underlying signal that transfers to new examples and starts memorizing sample-specific quirks and random noise inside the training set.

    Check the curve shapes to rule out common look-alikes before acting:

    • Not underfitting (high bias): Underfitting means the model is too rigid to capture the real pattern, which shows up as both training error and validation error plateauing high and close together (for example, 0.31 and 0.33).
    • Not a pure train/validation distribution shift: When validation data comes from a different population or broken preprocessing pipeline, a wide gap typically appears right at epoch 1, or validation error never improves cleanly alongside training error. Here, all three curves drop together from epoch 5 to epoch 20 and only diverge afterward.
    • Not a fluke in a single split: Validation error (0.29 -> 0.38) and test error (0.30 -> 0.39) move in lockstep, confirming the degradation reflects genuine out-of-sample generalization loss.
  2. Pinpoint the common root causes with a concrete polynomial trace

    Overfitting happens whenever a model has more degrees of freedom than the signal in the training data can constrain:

    • Excessive model capacity for the dataset size: Fitting a deep neural network on 2,000 rows, growing decision trees with unlimited depth until every leaf holds 1 row, or feeding 5,000 engineered features into 400 samples.
    • Training for too many epochs: Iterative optimizers like gradient descent fit coarse global structure in early epochs and increasingly fit tiny idiosyncratic residuals in late epochs.
    • Missing or weak regularization: Training without regularization—explicit penalties or structural limits (such as weight decay, dropout, or minimum leaf size) that discourage extreme weights and sharp decision boundaries.
    • Noisy or mislabeled training targets: A high-capacity model bends its boundary sharply around mislabeled training rows to force training error toward 0, hurting predictions on clean neighbors in validation/test.
    • Spurious or high-cardinality features: Columns like raw timestamps, session hashes, or rare ZIP codes act like row lookup keys that correlate with the target purely by chance in small samples.
    • Repeated hyperparameter tuning on the validation set: Running hundreds of manual experiments against one small validation split eventually overfits the validation set itself (which shows up when test error drifts noticeably above validation error).

    We can watch overfitting happen in 20 lines of NumPy by fitting polynomials of increasing degree to 20 noisy points sampled from y = sin(3x) + noise, where the random Gaussian noise has standard deviation 0.3 (so the irreducible population MSE floor is 0.3^2 = 0.090):

    import numpy as np
    
    rng = np.random.default_rng(5)
    
    
    def make_data(sample_count):
        x = rng.uniform(-1.0, 1.0, sample_count)
        y = np.sin(3.0 * x) + rng.normal(0.0, 0.3, sample_count)
        return x, y
    
    
    x_train, y_train = make_data(20)
    x_val, y_val = make_data(200)
    
    for degree in [1, 3, 5, 9, 12, 15]:
        coefs = np.polyfit(x_train, y_train, degree)
        train_mse = np.mean((np.polyval(coefs, x_train) - y_train) ** 2)
        val_mse = np.mean((np.polyval(coefs, x_val) - y_val) ** 2)
        print(f"degree {degree:2d}   train {train_mse:.3f}   val {val_mse:.3f}")
    
    degree  1   train 0.212   val 0.275   <- underfit (straight line cannot bend like sin(3x))
    degree  3   train 0.044   val 0.100   <- sweet spot (near the 0.090 irreducible noise floor)
    degree  5   train 0.039   val 0.103
    degree  9   train 0.035   val 0.160
    degree 12   train 0.035   val 0.778   <- overfit (wild oscillations between training points)
    degree 15   train 0.028   val 1.508   <- severe overfit (train MSE way below true 0.090 noise!)
    

    Notice the smoking gun: no real model can beat 0.090 MSE on fresh data because 0.3^2 = 0.090 is pure unforecastable noise, yet degree 15 drives training MSE down to 0.028 by memorizing the exact random noise values on those 20 training points.

  3. Confirm the diagnosis without touching the test set

    The golden rule of model evaluation is that the test set is a locked vault opened once at the very end. Even if someone hands you a diagnostic chart showing the test curve, you must never pick your stopping epoch, model family, or regularization strength by reading where the test curve bottoms out—doing so causes test-set leakage, turning the test set into a second validation set whose reported error is optimistically biased. Lock the test set away and confirm the diagnosis strictly on training and validation splits:

    1. Plot validation curves across one complexity knob at a time (stopping epoch, tree max_depth, polynomial degree, or 1 / lambda regularization). Genuine overfitting produces monotonically falling training error paired with a U-shaped validation curve.
    2. Plot a learning curve against training sample size (holding the model architecture fixed while training on 5%, 25%, 50%, 100% of the training pool):
    Training rows   Training error   Validation error   Gap (val - train)
    -------------   --------------   ----------------   -----------------
        1,000            0.02              0.30               0.28
        5,000            0.05              0.22               0.17
       20,000            0.08              0.15               0.07
    
    When training error creeps up slightly while validation error drops steadily and the gap narrows as `n` grows, high variance (overfitting) is confirmed—and the slope tells you whether collecting more data is worth the cost.
    
    1. Verify the rise exceeds statistical sampling noise. On a validation set of n examples with binary error rate p, the standard error—the typical random wiggle from finite sample size alone—is SE = sqrt(p * (1 - p) / n). For p = 0.20 and n = 500, SE = sqrt(0.16 / 500) = 0.018 (1.8 percentage points). A 0.01 uptick (0.29 -> 0.30) is inside normal noise; a 0.09 jump (0.29 -> 0.38) is 5 standard errors and unmistakably real.
    2. Run k-fold cross-validation—partitioning the non-test data into k equal folds (say k = 5) and rotating which fold validates—when datasets are small. Across 5 folds with validation errors [0.21, 0.19, 0.24, 0.20, 0.22], the mean is 0.212 with a fold-to-fold sample standard deviation of 0.019, confirming stability across splits. If you tune many hyperparameters on small data, use nested cross-validation (an inner loop selects hyperparameters; an outer loop measures unbiased error).
    3. Audit split hygiene and run a shuffled-label sanity check. Ensure grouped entities (all sessions from one user, all visits from one patient) or future timestamps never straddle train and validation. Optionally shuffle y_train at random and retrain: if training error still plunges near 0.00, your architecture has enough raw capacity to memorize pure noise.
  4. Apply practical fixes in order of cost and leverage

    Judge every intervention strictly on validation (or cross-validation) error, starting with the fastest, highest-leverage levers:

    • Early stopping (immediate zero-architecture fix): Save model checkpoints during training, monitor validation loss/error each epoch, stop when validation fails to improve for patience epochs (say 5–10 epochs), and restore the weights from the validation minimum (epoch 20 in our table, cutting validation error from 0.38 back to 0.29).
    • Explicit regularization:
      • Linear / neural models: Add L2 weight decay (Ridge) (lambda * sum(w_j^2), shrinking large weights smoothly toward zero), L1 regularization (Lasso) (lambda * sum(|w_j|), driving weak feature weights to exact zero), dropout (randomly zeroing a fraction of hidden activations each training batch so neurons cannot co-adapt to memorize specific examples), or label smoothing / batch normalization.
      • Decision trees and gradient boosting: Cap max_depth (e.g., 3–6), raise min_samples_leaf (so no leaf makes predictions from 2 noisy rows), subsample rows (subsample < 1.0) and columns (colsample_bytree < 1.0) per tree, add leaf L1/L2 penalties, and pair a smaller learning_rate with early stopping.
    • Right-size capacity and prune spurious features: Use a smaller network or shallower model, drop ID-like or near-zero-variance columns, and retain only features that improve cross-validation score.
    • Expand effective sample size and clean noisy labels: Gather more labeled examples, apply domain-valid data augmentation (label-preserving transforms like image crops/rotations or audio time-shifts), and inspect the training rows with the highest loss—correcting or removing mislabeled rows removes sharp noisy kinks in the learned boundary.
    • Reduce variance via ensembling: Bagging (training models on bootstrap resamples and averaging their predictions, as in a Random Forest) or averaging 5 independently seeded models cancels out uncorrelated individual model variance without increasing bias.
  5. Lock in the fix and run a single clean test evaluation

    Close the workflow without contaminating your final generalization estimate:

    1. Freeze all modeling choices (architecture, feature set, regularization strength lambda, and early-stopping rule) using only training and validation / cross-validation results.
    2. Fit the final model on the combined train + validation data using those frozen settings (or keep a tiny 5%–10% validation slice solely to trigger the early-stopping checkpoint).
    3. Evaluate on the locked test set exactly once and report that test metric alongside its confidence interval (+- 1.96 * SE).
    4. Never iterate backward from the test number. If the one-shot test error turns out much worse than validation error (beyond 2 * SE), treat it as a pipeline diagnostic—investigate whether you over-tuned hundreds of trials on a small validation set or whether a time/population shift separates validation and test—and collect a fresh holdout test set if another modeling cycle is required.

Intuition & how it works

Imagine a student preparing for a math exam using a deck of 20 practice problems. For the first hour, the student learns the underlying algebra rules, so scores improve on both the 20 practice cards and brand-new problems. By hour five, instead of practicing rules, the student memorizes superficial trivia—"whenever question #7 mentions apples and has a typo in line 2, the answer is 42." Their error on the 20 practice cards drops to 0%, while their error on fresh exam problems gets worse because those memorized coincidences mislead them on new inputs. That widening divergence—falling training error paired with U-shaped, rising validation and test error—is overfitting (also called high variance).

Relying naively on training error fails because a sufficiently flexible model can drive training error near zero simply by memorizing noise. Just as dangerously, picking your favorite epoch or model by looking at where the test curve hits its lowest point fails too: using the test set to make modeling choices causes test-set leakage (turning the test set into a second validation set so your reported performance is optimistically biased).

Walk through three concrete checkpoints from the plot (n = 500 validation examples) to see how diagnosis and fixing work step by step:

  1. Epoch 5 (train = 0.30, val = 0.33): Both errors are high and only 0.03 apart—the model is still underfitting (has not finished learning the core signal).
  2. Epoch 20 (train = 0.12, val = 0.29): Validation error reaches its minimum (0.29), while training error is lower (0.12).
  3. Epoch 60 (train = 0.02, val = 0.38): Training error nearly vanishes, while validation error climbs +0.09 above its epoch-20 minimum. Since the random sampling standard error on n = 500 examples near p = 0.29 is sqrt(0.29 * 0.71 / 500) = 0.020, a +0.09 jump is 4.5 standard errors—real overfitting, not random luck. Restoring the early stopping checkpoint from epoch 20 (using only the validation curve!) recovers 0.29 validation error and is verified once on the locked test set (0.30).

Key points

  • Recognize the exact curve signature. Monotonically decreasing training error combined with validation and test errors that dip to a minimum and then climb upward diagnoses overfitting (high variance)—distinct from underfitting / high bias (both curves flat and high) and data shift (a wide gap already present at epoch 1).
  • Trace overfitting back to excess freedom vs signal. Primary root causes are model capacity too large for sample size n, training too many epochs, weak regularization (penalties/constraints on model complexity), noisy/mislabeled targets, spurious ID-like features, and running too many hyperparameter trials against one validation split.
  • Confirm strictly on train + validation data. Use validation curves (varying one complexity parameter), learning curves (varying training sample size to watch the train/val gap shrink), k-fold or nested cross-validation, entity/time-aware splits, and a standard error check (sqrt(p * (1 - p) / n)) to separate real degradation from sampling noise.
  • Keep the test set untouched until one final check. Never select epochs, features, architectures, or regularization weights from the test curve; evaluate the frozen final model on the test set once.
  • Fix by constraining freedom or adding clean signal. Apply early stopping, L1/L2 weight decay, dropout, tree depth and minimum-leaf limits, feature pruning, label cleaning, data augmentation, or variance-reducing ensembles (bagging / Random Forests).

Common mistakes

  • Selecting the stopping epoch or hyperparameters from the test curve. Even if a benchmark tool plots test error per epoch, choosing "epoch 20 because test error was 0.30" leaks test data into model selection and invalidates the test metric.
  • Labeling every train-vs-validation gap as overfitting. If training error is 0.15 and validation error is 0.35 right from epoch 1 and never converges, suspect a preprocessing bug, target leakage, or temporal/population distribution shift before shrinking the model.
  • Chasing single-split statistical noise. On a 300-row validation set, +-2% swings between adjacent epochs happen purely by chance; check standard errors or k-fold cross-validation before concluding a model overfit.
  • Using random row splits on time-series or grouped user data. Letting Tuesday's rows predict Monday's, or putting five rows from the same customer in both train and validation, lets an overfitted model memorize user/date quirks and look artificially accurate offline.
  • Collecting more rows when the real bottleneck is high bias. If training error and validation error have already converged at a poor 0.34, adding 10x more rows barely moves the needle—you need richer features or higher model capacity first.
  • Over-regularizing purely to make train_error == val_error. Some positive generalization gap at the validation minimum (such as 0.12 train vs 0.29 val at epoch 20) is completely normal; cranking regularization until both sit at 0.34 makes out-of-sample predictions worse.

Follow-up questions

  • How do you distinguish true overfitting from a distribution shift between the training and validation sets? First inspect early training: pure overfitting usually starts with train and validation errors moving downward together before diverging, whereas distribution shift creates an immediate gap from the earliest epochs. For a direct quantitative check, run adversarial validation—assign label 0 to training feature rows and label 1 to validation feature rows, shuffle them together, and train a classifier to tell them apart. A cross-validated ROC-AUC near 0.50 confirms the two sets come from the same distribution; an AUC of 0.75+ proves a shift exists, and the top-ranked features immediately pinpoint which columns drifted.
  • What if validation log-loss starts rising after epoch 20 while validation accuracy keeps improving through epoch 50—is the model overfitting, and which metric do you stop on? Yes, this is confidence overfitting: on the majority of examples the model keeps nudging borderline predictions across the 0.50 boundary (lifting accuracy), while on a handful of hard or mislabeled examples its wrong predictions grow extreme (0.999 confidence on the wrong class), which cross-entropy (log-loss) penalizes logarithmically. Stop and tune on whichever metric governs your downstream system: if downstream code consumes calibrated probabilities (expected-profit lending cutoffs, medical risk scores, ranking), stop on log-loss or apply temperature scaling (rescaling logits by a scalar T > 1 on validation data to soften overconfident probabilities); if only hard top-1 labels ever matter, accuracy/F1 can guide selection alongside calibration monitoring.
  • Can increasing model size or training epochs past the overfitting peak ever make test error go back down again? Yes—in heavily overparameterized neural networks and random-feature models, double descent (documented across architectures and training epochs by Belkin et al., 2019 and Nakkiran et al., 2019) can cause validation/test error to spike near the interpolation threshold—the exact capacity or epoch where the model first achieves near-zero training error by straining to fit noisy labels—and then decrease again as even larger capacity allows smoother minimum-norm interpolating solutions. Double descent is prominent mainly when label noise is present and regularization is very weak; with well-tuned weight decay and early stopping, the single U-shaped validation curve usually dominates, and either way you verify candidate regimes strictly on held-out validation data rather than assuming the curve moves one way forever.

Follow-up questions

Similar questions

More Zest AI interview questions

All 3 Zest AI questions →