Sub topic 9
Reading a Validation Curve
This chapter assumes you can already compute a validation curve with validation_curve and that you know the underfitting and overfitting vocabulary from earlier chapters. Here you will learn to read the curve: find the regions, judge how far to trust the peak, and pick a value.
What the curve shows
A validation curve varies one hyperparameter and holds everything else fixed. For each value, scikit-learn refits the model on each cross-validation training split. It records the score on that training split and on the held-out fold. Averaging over folds gives one training point and one validation point per value.
The x-axis is a model-flexibility knob, and the two lines show how flexibility changes fit. The code below reuses the digits example and adds the quantities you need for reading the curve.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import validation_curve
from sklearn.svm import SVC
X, y = load_digits(return_X_y=True)
param_range = np.logspace(-6, -1, 6)
train_scores, val_scores = validation_curve(
SVC(kernel="rbf"),
X,
y,
param_name="gamma",
param_range=param_range,
cv=5,
scoring="accuracy",
)
train_mean = train_scores.mean(axis=1)
val_mean = val_scores.mean(axis=1)
val_std = val_scores.std(axis=1)
gap = train_mean - val_mean
for g, tr, va, gp in zip(param_range, train_mean, val_mean, gap):
print(f"gamma={g:.0e} train={tr:.3f} val={va:.3f} gap={gp:.3f}")Direction depends on the parameter
Before you read anything, work out which end of the axis is the flexible end. It differs between hyperparameters.
| Hyperparameter | Increasing it makes the model | Flexible end |
|---|---|---|
| `gamma` in an RBF `SVC` | more flexible | right |
| `C` in `SVC` or `LogisticRegression` | more flexible (weaker regularization) | right |
| `max_depth` of a tree | more flexible | right |
| `n_neighbors` in k-NN | smoother, less flexible | left |
| `alpha` in `Ridge` or `Lasso` | more regularized, less flexible | left |
| `min_samples_leaf` in a tree | less flexible | left |
Treat "complexity" as a statement about the axis direction for this parameter. It is not a property of the number itself. Many people misread n_neighbors curves because they assume the right side means overfitting.
The three regions
Take a parameter where the right side is more flexible, such as gamma. A typical curve has three regions.
- Underfitting region (left). Both curves are low and close together. The model is too constrained to capture the signal, so even the data it trained on is poorly fit. Changing the parameter in this region raises both scores.
- Sweet spot (middle). The validation score reaches its maximum or a plateau. The training score is usually somewhat higher.
- Overfitting region (right). The training score keeps rising or stays near its ceiling. The validation score falls, so the gap widens. The model fits noise in the training folds that does not carry over to held-out data.
"Low" and "large" are relative. A training score of 0.70 is low for digits classification, where 0.99 is reachable. It may be excellent for a noisy medical outcome. Judge the level against a baseline, such as a dummy classifier or the score of a simple model, and against the error you could tolerate in practice.
Plotting the curve
A table of numbers hides the shape. Plot both lines with their spread, using a log axis when the range spans orders of magnitude.
import matplotlib.pyplot as plt
train_std = train_scores.std(axis=1)
fig, ax = plt.subplots()
ax.semilogx(param_range, train_mean, marker="o", label="Training score")
ax.fill_between(param_range, train_mean - train_std, train_mean + train_std, alpha=0.2)
ax.semilogx(param_range, val_mean, marker="o", label="Cross-validation score")
ax.fill_between(param_range, val_mean - val_std, val_mean + val_std, alpha=0.2)
ax.set_xlabel("gamma")
ax.set_ylabel("Accuracy")
ax.legend()
plt.show()On the digits data you should see the training score reach about 1.0 at the largest gamma while the validation score drops sharply. That divergence is the overfitting signature. At the smallest gamma both scores are well below their peak, which is the underfitting signature.
What the gap tells you
The gap is train_mean - val_mean. It is a useful second axis, but do not use it alone.
- A small gap with low scores means high bias. The model cannot fit even the training data.
- A growing gap with a falling validation score means high variance. The model is memorizing training folds.
- A large gap whose validation score is still near its maximum is not necessarily a problem. Many strong models, such as random forests, score near 1.0 on training data by construction. Choose by the validation score, and use the gap to understand why the score behaves as it does.
Choosing a value, and the limits of that choice
The simplest rule is the argmax of the validation mean. It is noisy, because each point is an average over a few folds with its own spread. Two values whose validation scores differ by less than the fold-to-fold standard deviation are effectively tied.
A common alternative is the one-standard-error rule. Find the best mean, compute its standard error, and pick the simplest setting whose mean is within one standard error of the best.
best = val_mean.argmax()
n_folds = val_scores.shape[1]
threshold = val_mean[best] - val_std[best] / np.sqrt(n_folds)
# param_range is ascending and smaller gamma means a smoother model,
# so the simplest acceptable value is the smallest index above the threshold.
candidates = np.where(val_mean >= threshold)[0]
chosen = candidates.min()
print(f"argmax gamma = {param_range[best]:.0e}")
print(f"one-SE gamma = {param_range[chosen]:.0e}")Here "simplest" means the smallest gamma. For a parameter like n_neighbors, the simplest model sits at the large end, so you would take candidates.max(). Remember the direction table above.
The fold standard deviation understates uncertainty. The folds share training data, so their scores are correlated, and the true error of the estimate is larger than a naive standard error suggests. Treat the rule as a tie-breaker that favors simplicity. Do not read it as a formal confidence interval.
Limits you should keep in mind
- Other hyperparameters are frozen. The best
gammadepends onC. A curve forgammaatC=1can mislead if the best model needsC=100. Use the curve to understand one axis, then use a grid or random search for joint choices. - The peak is an optimistic estimate. You picked the maximum of several noisy scores, so the validation score at that point is biased upward. For an honest final estimate, evaluate on a test set that played no part in the curve, or use nested cross-validation.
- The range matters. If the best value sits at the edge of
param_range, the curve has not shown you the peak. Extend the range in that direction and recompute. - The metric matters. A curve built with accuracy on an imbalanced problem can look flat and healthy while the model ignores the rare class. Recompute with a metric such as
f1orroc_aucif the cost of errors is uneven. - Plateaus are information. A wide flat top means the model is insensitive to the parameter over that range. You can pick the value that is cheapest to train or most stable.
- Training scores are not always monotone. With randomized learners, such as forests or SGD-based models, a lack of smoothness can come from the random seed. Fix
random_stateand compare the spread of the curve with its trend.
Quick reference
| What you see | Likely reading | First thing to try |
|---|---|---|
| Both curves low, close together, rising toward the flexible end | Underfitting | Move toward the flexible end; try a richer model |
| Training near ceiling, validation falling toward the flexible end | Overfitting | Move toward the simple end; add regularization |
| Both curves flat across the whole range | The parameter has little effect | Tune a different hyperparameter |
| Validation peak at the edge of the range | The range is too narrow | Extend the range and rerun |
| Overlapping bands around the peak | Several values are effectively tied | Pick the simplest or cheapest |
Exercise
You compute a validation curve for the n_neighbors parameter of a k-NN classifier over the values 1, 3, 5, 9, 15, 25, 51. The training score is 1.00 at nneighbors=1 and falls steadily as the value grows. The validation score is lowest at nneighbors=1, peaks around 9 to 15, and declines slowly after that. Which end of the axis is overfitting, where would you choose a value, and why might you not pick the exact argmax?
Show answer
Overfitting is at the left, small n_neighbors: with 1 neighbor the model memorizes each training point, so the training score is 1.00 while the validation score is low. Larger values give smoother, less flexible models, so the right end is the underfitting end. The peak is around 9 to 15. If the validation means for 9, 15, and nearby values lie within one standard error of each other, apply the one-standard-error rule. Because larger n_neighbors is simpler, take the largest value still within one standard error of the best. That is a more stable choice than the exact argmax, which is partly noise from a few folds.
Exercise
A colleague shows a validation curve where the validation score keeps rising up to the last point of param_range for the regularization parameter C of a logistic regression, and says "C=100 is optimal, we are done." What is wrong with this conclusion, and what do you do?
Show answer
The best value sits at the edge of the tested range, so the curve has not shown where the peak is or whether a peak exists. Extend param_range upward (for example to 1e3 or 1e4) and recompute. Also check whether the gain over smaller C values is larger than the fold spread. If the curve flattens, choose the smallest C on the plateau. Finally, confirm the score on held-out data that was not used for the selection.