Sub topic 12
Using Curves in a Tuning Workflow
This chapter assumes you can compute a learning curve and a validation curve with scikit-learn. It also assumes you can read the gap between training and validation scores and know the difference between a hyperparameter and a learned parameter. Here the curves become steps in a repeatable tuning procedure, with a defined order, a stopping rule, and a protected test set.
Why order matters
A curve answers one question at a time. A learning curve tells you whether the current model is limited by bias or by variance, and whether more data would help. A validation curve tells you where along one hyperparameter the model moves from underfitting to overfitting. A tuning workflow uses them in sequence, because the answer to the first question decides which hyperparameters are worth searching.
Step 1: Protect a test set first
Every curve in this workflow is computed by cross-validation on the training portion only. If you tune using curves that include the test rows, the test score is no longer an honest estimate, because the choices you made were informed by those rows. Split before you plot anything, and do not look at the test set again until the final step.
Step 2: Put preprocessing in a pipeline
Scalers, imputers, and feature selectors must be refit inside each training split. Passing a pipeline to learning_curve, validation_curve, or a search object does this automatically. Hyperparameters of pipeline steps are addressed as stepname__parameter, for example svc__gamma. make_pipeline names each step after its lowercase class name.
Step 3: Diagnose with a learning curve
Draw the learning curve for a reasonable default model. Then act on what you see.
| What the curves show | Diagnosis | Next move |
|---|---|---|
| Both scores low and close together, flat | High bias | Search toward more flexibility. More data alone will not help. |
| Training score high, validation score much lower, gap narrowing slowly | High variance | Add regularization or simplify. More data is likely to help. |
| Validation score still rising at the largest size | Data-limited | Collect more data if the cost is acceptable. |
| Both scores high, small gap, validation flat | Good fit | Stop. Further tuning gains are within noise. |
The diagnosis chooses the direction of the search. Without it, you may spend an hour tuning regularization on a model that is underfitting.
Step 4: Adjust one hyperparameter with a validation curve
Pick the hyperparameter that controls flexibility in the direction your diagnosis calls for. For an RBF support vector machine, gamma and C both do. For a random forest, max_depth or min_samples_leaf. For a linear model, the regularization strength.
Use a wide, logarithmic range on the first pass. Then narrow the range around the region where the validation score peaks.
Choose the value, not just the maximum
The highest mean validation score is a noisy estimate. A value one step to its left may be statistically indistinguishable and yield a simpler model. The one-standard-error rule picks the simplest setting whose mean validation score is within one standard error of the best. The code below applies it to a pipeline.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import (
StratifiedKFold,
train_test_split,
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)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
model = make_pipeline(StandardScaler(), SVC(kernel="rbf"))
param_range = np.logspace(-4, -1, 7) # ascending: smaller gamma = smoother model
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
train_scores, val_scores = validation_curve(
model,
X_train,
y_train,
param_name="svc__gamma",
param_range=param_range,
cv=cv,
scoring="accuracy",
n_jobs=-1,
)
val_mean = val_scores.mean(axis=1)
val_se = val_scores.std(axis=1, ddof=1) / np.sqrt(val_scores.shape[1])
best = val_mean.argmax()
threshold = val_mean[best] - val_se[best]
chosen = np.flatnonzero(val_mean >= threshold)[0] # first = simplest here
print(f"best gamma: {param_range[best]:.2e} (mean {val_mean[best]:.3f})")
print(f"chosen gamma: {param_range[chosen]:.2e} (mean {val_mean[chosen]:.3f})")Taking the first index that clears the threshold works only because the range is sorted from simple to complex. If you search a parameter where larger means simpler, such as C in a regularized linear model read as inverse strength in the opposite direction, take the last index instead. Check the direction for every parameter.
The standard error here treats the five folds as independent, which they are not, since training sets overlap. Treat it as a rough guide to noise and not as a formal confidence interval.
Step 5: Redraw the learning curve
After changing the model, the earlier diagnosis may no longer hold. A model made more flexible may now overfit, and a model made more regularized may have closed the gap but lowered both curves. Redraw the learning curve with the chosen setting, using the same cross-validation splitter and metric as before so the two plots are comparable. Repeat steps 3 to 5 until a change no longer moves the validation score by more than its fold-to-fold spread.
Step 6: Refit and score once
When the loop ends, refit on the whole training set with the chosen values, and compute the test score one time.
final_model = model.set_params(svc__gamma=param_range[chosen])
final_model.fit(X_train, y_train)
print(f"test accuracy: {final_model.score(X_test, y_test):.3f}")If the test score is clearly lower than the validation score, suspect leakage or an over-tuned search. Do not go back and adjust further against the test set. Doing so converts it into a second validation set.
Interactions between hyperparameters
A validation curve varies one parameter while the others stay fixed. Parameters often interact. In an RBF SVM, the best gamma shifts when C changes, so the optimum found with default C need not be the joint optimum.
Two practical responses:
- Alternate. Tune one parameter with a curve, fix it, tune the second, then revisit the first with a narrower range.
- Switch to a search. Once curves have narrowed each range, use
GridSearchCVorRandomizedSearchCVover the narrowed ranges to handle interactions.
from sklearn.model_selection import GridSearchCV
param_grid = {
"svc__gamma": np.logspace(-4, -2, 5),
"svc__C": [0.1, 1, 10],
}
search = GridSearchCV(model, param_grid, cv=cv, scoring="accuracy", n_jobs=-1)
search.fit(X_train, y_train)
print(search.best_params_, round(search.best_score_, 3))The curves give you ranges that are small enough to search cheaply and a reason to trust them.
Knowing when to stop
Tuning has diminishing returns. Stop when any of these holds:
- The validation score changes by less than the fold standard deviation between candidate settings.
- The learning curve shows a small gap and a flat validation score, so neither flexibility nor data will help.
- The remaining gain is smaller than the gain you would get from a better metric, better features, or cleaner labels.
Record the final curves, the chosen values, and the splitter settings with a fixed random_state. A later reader can then see why the values were chosen and reproduce the result.
Cost control
Each point on a curve fits the model once per fold. A validation curve with 7 values and 5 folds fits 35 models. A learning curve with 5 sizes and 5 folds fits 25. Some ways to keep this affordable:
- Pass
n_jobs=-1to run fits in parallel. - Start with 3 folds and a coarse range, then refine.
- Draw the learning curve on a subsample while exploring, and on the full training set only for the final check.
- Use a cheaper model family for exploring ranges when the target model is slow.
Exercise
In the validation-curve code above, you change the parameter to C and generate param_range = np.logspace(-2, 2, 7). For SVC, a larger C means weaker regularization and a more flexible model. Which index from np.flatnonzero(val_mean >= threshold) should you take to apply the one-standard-error rule, and why?
Show answer
Take the first index. The range is sorted ascending, and a smaller C means stronger regularization, so the first value that meets the threshold is the simplest model within one standard error of the best. The direction would flip only for a parameter where larger values mean a simpler model.
Exercise
Your learning curve shows training accuracy of 0.99, validation accuracy of 0.78, and a gap that narrows slowly as training size grows. After you add regularization with a validation curve, the redrawn curve shows training 0.83 and validation 0.82. The test score is 0.81. What do you conclude, and is further tuning of this model worthwhile?
Show answer
The original model had high variance, and regularization closed the gap. The test score of 0.81 agrees with the validation score of 0.82, so the procedure did not leak or over-tune. Both curves are now close together and lower, so the model has moved toward bias. Further regularization tuning is unlikely to help. Gains must come from a more flexible model, better features, or more data, and the learning curve shows whether the validation score is still rising with size.