Sub topic 8
Computing a Validation Curve
A validation curve shows how training and cross-validated scores change as one hyperparameter changes and everything else stays fixed. This chapter covers how to compute one with scikit-learn, what the output arrays contain, and how to set up the call so the numbers are trustworthy. The next chapter covers reading the curve.
You should already know how to fit a scikit-learn estimator, what cross-validation does, and what a hyperparameter is. You should also be comfortable with NumPy arrays and axis-wise means.
What `validation_curve` does
sklearn.model_selection.validation_curve runs cross-validation once for each value in a list of candidate values for one hyperparameter. For every value and every fold, it clones the estimator, sets the parameter, fits on the training part of the fold, and scores on both the training part and the held-out part.
The function does not pick a best value for you. It only returns the raw scores, and you decide what to do with them.
A first validation curve
This example varies gamma of an RBF support vector classifier on the digits dataset. gamma controls how far the influence of a single training sample reaches. A small value gives a smooth, simple decision boundary. A large value gives a wiggly one that can memorize the training set.
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",
)
for gamma, tr, va in zip(param_range, train_scores.mean(axis=1), val_scores.mean(axis=1)):
print(f"gamma={gamma:.0e} train={tr:.3f} validation={va:.3f}")Run it and you should see six lines. At the smallest gamma both scores are low and close together. Around 1e-3 both are high. At 1e-1 the training score is near 1.0 while the validation score collapses. Exact values depend on your scikit-learn version, so compare the pattern, not the digits.
The shape of the output
Both returned arrays have shape (n_values, n_folds). Row i holds the scores for param_range[i], and column j holds fold j.
print(train_scores.shape) # (6, 5)
print(val_scores.shape) # (6, 5)
train_mean = train_scores.mean(axis=1)
val_mean = val_scores.mean(axis=1)
best = param_range[val_mean.argmax()]
print("Best mean validation score at gamma =", best)Averaging over axis=1 collapses the folds and leaves one number per hyperparameter value. Averaging over axis=0 is a common slip. It mixes different hyperparameter values and gives one number per fold, which is not what you want.
Choosing the parameter range
The range determines whether the curve shows anything useful. Some guidance:
- Use a log scale for scale-like parameters.
gamma,C,alpha, and learning rates act multiplicatively.np.logspacespaces candidates evenly on that scale. - Cover the transition. A good range reaches into underfitting at one end and overfitting at the other. If both scores are still rising at the end of your range, extend it.
- Use integers for count-like parameters. For
max_depthorn_neighbors, pass something likerange(1, 21). - Vary one parameter at a time. The other hyperparameters stay at their defaults or at the values you set on the estimator. Changing one often moves the best value of another, so a curve is a one-dimensional slice, not a full search.
The parameter does not have to be numeric. A list of strings, such as kernel names, works, though the plot then needs a bar or categorical axis rather than a line.
Curves for a pipeline
If your model includes preprocessing, put it in a Pipeline so each fold fits the scaler on its own training part only. Reach the parameter with the step name and a double underscore.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import validation_curve
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_digits(return_X_y=True)
model = make_pipeline(StandardScaler(), SVC(kernel="rbf"))
param_range = np.logspace(-5, 0, 6)
train_scores, val_scores = validation_curve(
model,
X,
y,
param_name="svc__gamma",
param_range=param_range,
cv=5,
scoring="accuracy",
n_jobs=-1,
)
print(val_scores.mean(axis=1).round(3))make_pipeline names each step after its lowercase class name, so the SVC step is svc. If you misspell the name, scikit-learn raises an error about an invalid parameter. You can list valid names with model.get_params().keys().
Standardizing the features changes where the good gamma values sit. The earlier curve and this one are not directly comparable on the x-axis.
Plotting the curve
The plot puts the parameter on the x-axis, on a log scale when the range is logarithmic, and draws one line for each score with a band of one standard deviation across folds.
import matplotlib.pyplot as plt
train_mean = train_scores.mean(axis=1)
train_std = train_scores.std(axis=1)
val_mean = val_scores.mean(axis=1)
val_std = val_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()Run this directly after the pipeline example, since it reuses param_range, train_scores, and val_scores.
Choosing `cv` and `scoring`
Both arguments change what the curve means.
cv: An integer uses stratified k-fold for classifiers and plain k-fold otherwise. More folds give each fit more training data and a lower-bias estimate, at the cost of more fits. Five or ten is typical.- Splitters for special data: Ordered data needs a time-aware splitter such as
TimeSeriesSplit. Samples that belong to the same entity needGroupKFoldwith agroupsargument. Without this, related samples land on both sides of a split and the validation score is inflated. scoring: The default is the estimator's ownscoremethod, which is accuracy for classifiers and R² for regressors. Pass a scoring name to match your goal, for example"f1_macro"for imbalanced classes or"neg_mean_squared_error"for regression. Scorers that start withneg_return negated errors so that higher is always better. Remember to flip the sign if you want to display the error itself.
Cost and failure handling
The total number of fits is len(param_range) * n_folds, plus the scoring passes. Six values and five folds mean 30 fits. Expensive models and wide ranges grow this quickly. Three things help:
- Set
n_jobs=-1to run fits in parallel. - Start with a coarse range, then zoom in on the interesting region with a second call.
- Work on a subsample while you explore, then confirm on the full data.
Some parameter values make a fit fail, for example a solver that does not support a chosen penalty. By default error_score=np.nan records nan and emits a warning instead of stopping. Check for nan in your arrays before taking means, or argmax will give a misleading answer. Use np.nanmean if you accept the gaps, or set error_score="raise" while debugging.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Averaging over `axis=0` | One value per fold instead of per parameter value | Use `axis=1` |
| Linear spacing for `C` or `gamma` | Most points crowd at the large end | Use `np.logspace` |
| Scaling the data before the call | Validation folds influence the scaler | Put the scaler in a pipeline |
| Ignoring groups | Inflated validation score | Pass `groups` and use `GroupKFold` |
| Wrong pipeline parameter name | Invalid parameter error | Check `get_params()` |
| Range too narrow | Curve never shows both regimes | Widen the range |
Exercise
You call validationcurve with paramrange = np.logspace(-3, 2, 11) and cv=4. What is the shape of val_scores, how many model fits are run for the training and validation scores, and which line of code gives the index of the best mean validation score?
Show answer
valscores has shape (11, 4), because there are 11 parameter values and 4 folds. validationcurve runs 11 * 4 = 44 fits, and each fit is scored on both its training part and its held-out part. The index of the best value is valscores.mean(axis=1).argmax(), and paramrange[that index] is the chosen hyperparameter value.
Exercise
Your data contains several rows per patient. You compute a validation curve with cv=5 and get a validation score almost as high as the training score at every hyperparameter value. What is the likely cause, and how do you change the call?
Show answer
Rows from the same patient appear in both the training and held-out parts of a split, so the model is partly scored on patients it has already seen. Pass a groups array with one patient ID per row and set cv=GroupKFold(n_splits=5), so that every patient falls entirely on one side of each split.