Sub topic 4
Hyperparameters and what tuning means
This chapter separates two kinds of numbers in a model: the ones the training algorithm learns, and the ones you set before training starts. It assumes you know supervised learning basics, overfitting, and the scikit-learn fit/predict/score interface. You should also remember k-fold cross-validation from the previous chapter. Later chapters build on the definition here to explain why tuning needs its own honest evaluation.
Two kinds of numbers
A model has learned parameters. These are values the training algorithm computes from the data. Examples are the coefficients of a linear model, the split thresholds in a decision tree, and the mean and variance stored by a scaler. You never type them in. They are the output of fit.
A model also has hyperparameters. These are values you choose before fit runs. They control how the algorithm works or how flexible the model is. Examples are the regularization strength C in logistic regression, the max_depth of a tree, the n_neighbors of a k-nearest-neighbors classifier, and the gamma of an RBF kernel.
| Row | Learned parameters | Hyperparameters |
|---|---|---|
| Set by | The training algorithm | You, or a search procedure |
| When | During `fit` | Before `fit` |
| scikit-learn naming | Trailing underscore, such as `coef_` | Constructor arguments, such as `C` |
| Chosen by minimizing | The training loss | Validation performance |
The trailing-underscore convention helps in practice. If an attribute ends in _ and exists only after fitting, it was learned. If you can pass it to the constructor, it is a hyperparameter.
The code below shows both on one pipeline.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
pipe = make_pipeline(StandardScaler(), LogisticRegression(C=1.0, max_iter=1000))
# Hyperparameters exist before fitting.
print("C before fit:", pipe.get_params()["logisticregression__C"])
pipe.fit(X, y)
# Learned parameters exist only after fitting.
print("scaler mean_ shape:", pipe.named_steps["standardscaler"].mean_.shape)
print("coef_ shape:", pipe.named_steps["logisticregression"].coef_.shape)Fitting this pipeline learns 30 means and 30 coefficients from the data. C stays at 1.0 because the training algorithm does not change it.
Why hyperparameters cannot be learned the same way
Training minimizes a loss on the training data. If the training loss were allowed to choose a hyperparameter such as max_depth, it would always pick the most flexible setting, because a more flexible model fits the training data at least as well. That choice leads straight to overfitting.
Hyperparameters therefore need a different signal: performance on data the model was not fitted on. Cross-validation supplies this. For each candidate setting, you fit on some folds and score on the held-out fold. You then keep the setting with the best held-out score.
This procedure is tuning (also called hyperparameter optimization or model selection). Tuning is a second layer of fitting: the first layer fits parameters to training data, and the second layer fits hyperparameters to validation scores. The second layer has the same weakness as the first. It can overfit the data it uses. The chapter on optimistic bias covers that in detail.
Seeing a hyperparameter at work
A validation curve shows how the score changes as one hyperparameter varies. Here we vary C for the pipeline above. In scikit-learn, smaller C means stronger regularization.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, validation_curve
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
C_range = np.logspace(-3, 3, 7)
train_scores, val_scores = validation_curve(
pipe, X, y,
param_name="logisticregression__C",
param_range=C_range,
cv=cv,
)
for C, tr, va in zip(C_range, train_scores.mean(axis=1), val_scores.mean(axis=1)):
print(f"C={C:>8.3f} train={tr:.3f} validation={va:.3f}")Expect the training score to rise or stay flat as C grows, since weaker regularization fits the training folds more closely. The validation score typically peaks at a moderate value and then stops improving or drops slightly. The exact numbers depend on your scikit-learn version, so read the shape of the curve rather than any single value.
Naming hyperparameters inside a pipeline
When an estimator sits inside a Pipeline, you address its hyperparameters as stepname__paramname, with two underscores. make_pipeline builds the step name by lowercasing the class name, so SVC becomes svc and LogisticRegression becomes logisticregression.
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
pipe = make_pipeline(StandardScaler(), SVC())
for name in sorted(pipe.get_params()):
if name.startswith("svc__"):
print(name)get_params() is the reliable way to find a name. A misspelled key in a grid fails with a ValueError listing the valid parameters.
Preprocessing steps have hyperparameters too, such as with_mean on StandardScaler or the number of components in PCA. Putting them in the pipeline lets you tune them with the model, and keeps them inside the folds.
Choosing what to tune and how to search
Not every constructor argument deserves a search. Consider these points before you define a grid.
- Tune what matters. For an SVM,
Candgammausually dominate. For gradient boosting, learning rate, number of trees, and tree depth interact strongly. Tuning many minor settings adds cost and adds chances to overfit the validation scores. - Do not tune
random_state. It controls randomness and has no meaning as a model setting. A search over seeds only rewards luck. - Use log-spaced ranges for scale parameters.
C,gamma, and learning rates act multiplicatively. The values 0.1, 1, 10 span the range better than 1, 2, 3. Usenp.logspaceor a log-uniform distribution. - Watch the grid edges. If the best value sits at the edge of your range, the true optimum may lie outside it. Extend the range and search again.
- Some hyperparameters are conditional.
gammaonly matters for some SVM kernels, andl1_ratioonly matters with the elastic-net penalty. A flat grid wastes fits on meaningless combinations. A list of grids, as inGridSearchCV(pipe, [grid_a, grid_b]), handles this. - Defaults are a candidate. The library defaults are a reasonable starting point. A tuned model should beat them on validation data. If it does not, the defaults may be fine.
The number of candidates multiplies quickly. A grid of 3 values for C and 3 for gamma has 9 combinations. Each combination is fitted once per fold, so 5-fold cross-validation means 45 fits. Adding a third hyperparameter with 4 values raises that to 180 fits.
What tuning produces, and what it does not
After the search, you hold a chosen setting and a score for it. Two statements are easy to confuse:
- "This setting scored best among the candidates I tried."
- "A model built with this setting will score this well on new data."
The first is a fact about your search. The second is a prediction. The score in the first statement was used to make the choice, so it tends to overstate the second. With few candidates and a large dataset the gap is small. With many candidates, noisy folds, or a small dataset it can be large.
The next chapters show how to measure that gap. For now, keep the vocabulary clear: hyperparameters are chosen by validation performance, and a score used for choosing cannot also serve as an unbiased test.
Exercise
You fit a decision tree and then print tree.tree_.max_depth, tree.max_depth, and tree.feature_importances_. Which of these are hyperparameters and which are learned? Why can't you pick max_depth by minimizing training error?
Show answer
tree.max_depth is a hyperparameter, because it is a constructor argument you set before fitting. tree.tree_.max_depth (the actual depth reached) and feature_importances_ are learned from the data during fit. Minimizing training error would always favor the deepest tree, since a deeper tree fits the training data at least as well. That choice overfits, so max_depth must be picked using held-out validation scores such as cross-validation.
Exercise
A pipeline is built with make_pipeline(StandardScaler(), KNeighborsClassifier()). Write the grid key that tunes the number of neighbors. Then say what the best value of 25 should make you do if your grid was [1, 5, 10, 15, 20, 25].
Show answer
The key is kneighborsclassifier__n_neighbors. A best value of 25 sits at the upper edge of the grid, so the true optimum may be larger. You should extend the grid, for example to 30, 40, 50, and search again.