Sub topic 8
Computing a Validation Curve
This chapter assumes you know how to fit a scikit-learn estimator, that you understand k-fold cross-validation at a basic level, and that you can tell a hyperparameter from a learned parameter. It covers how to compute a validation curve. The next chapter covers how to read one.
What a validation curve measures
A validation curve shows how the training score and the cross-validated score change as you vary one hyperparameter. Every other setting stays fixed. A learning curve varies the amount of data. A validation curve varies model flexibility.
For each value in your range, scikit-learn clones the estimator, sets the hyperparameter, and runs cross-validation. It records the score on the training part and on the validation part of every fold.
Computing the curve
The example below varies gamma of an RBF support vector classifier on the digits dataset. gamma sets 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.
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}")The call returns two arrays. Each has shape (n_values, n_folds). Here that is (6, 5): one row per gamma value and one column per fold. Averaging over axis=1 collapses the folds and leaves one number per hyperparameter value. Use axis=1, not the default of averaging everything, or you will lose the dimension you want to plot.
The arguments that matter
| Argument | Role |
|---|---|
| `param_name` | The name of the hyperparameter, as a string. For a pipeline, use the prefixed name such as `svc__gamma`. |
| `param_range` | The values to try. Order them from simple to complex so the curve is easy to read. |
| `cv` | Number of folds or a splitter object. For classifiers, an integer gives stratified folds. |
| `scoring` | The metric. Higher must mean better, so error metrics use the `neg_` forms. |
| `n_jobs` | Parallel workers. The folds and values are independent, so this speeds things up. |
Choosing the range
Many hyperparameters, such as gamma, C, and alpha, act on a multiplicative scale. Use np.logspace for these so each step changes the model by a similar amount. A linear range such as np.linspace(0.001, 0.1, 6) would put almost all points at the high end. Integer settings such as tree depth or n_neighbors use plain range values.
Pick a range wide enough that the curve shows both a clearly too simple region and a clearly too flexible region. If the best value sits at the edge of your range, extend the range and rerun.
Plotting it
Plot the mean for each score against the parameter. Use a logarithmic x-axis when the range is logarithmic.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.semilogx(param_range, train_scores.mean(axis=1), marker="o", label="Training score")
ax.semilogx(param_range, val_scores.mean(axis=1), marker="o", label="Cross-validation score")
ax.set_xlabel("gamma")
ax.set_ylabel("Accuracy")
ax.legend()
plt.show()Common errors
- Wrong parameter name. A misspelled
param_nameraises an error when the estimator is cloned. Check the spelling withestimator.get_params().keys(). - Varying more than one hyperparameter. The function accepts only one. For two, use a grid search and plot a heat map instead.
- Unscaled inputs in a pipeline outside the call. If you scale the data before calling the function, the scaler sees the validation folds. Put the scaler in a pipeline so it refits on each training split.
- Reading a single point. Each value comes from a few folds. Look at the shape of the curve, not one number.
Exercise
You call validationcurve with paramrange of 8 values and cv=4. What shape do trainscores and valscores have, and how many model fits does the call perform?
Show answer
Each array has shape (8, 4), one row per value and one column per fold. The call performs 8 × 4 = 32 fits.
Exercise
You want to vary the regularization strength C of a LogisticRegression, trying values from 0.0001 to 100. Which NumPy function should you use to build param_range, and why?
Show answer
Use np.logspace, for example np.logspace(-4, 2, 7). C acts on a multiplicative scale, so log spacing changes the model by a similar amount at each step. A linear range would place nearly every point at the high end.