Sub topic 4
Hyperparameters and what tuning means
This chapter assumes you know supervised learning basics, the idea of overfitting, and how to call fit, predict, and score on a scikit-learn estimator. It covers the difference between the two kinds of values a model has, and what it means to tune one of them.
Two kinds of values in a model
A model has values of two kinds, and they are set in different ways.
- Learned parameters are set by
fit. Examples are the coefficients of a linear model and the split thresholds in a decision tree. The training data determines them. - Hyperparameters are set by you before
fitis called. Examples are the regularization strengthCof an SVM, the depth limit of a tree, and the number of neighbors in k-nearest neighbors. Training does not change them.
Hyperparameters control how flexible the model can be. A large max_depth lets a tree fit fine detail, and it also lets the tree memorize noise. A small one forces a simpler model that may miss real structure. Choosing a hyperparameter is therefore a choice about the trade-off between underfitting and overfitting.
| Property | Learned parameter | Hyperparameter |
|---|---|---|
| Set by | `fit`, from training data | You, before `fit` |
| Example | Tree split thresholds | `max_depth` |
| Found with | Optimization on the training set | Trying values and comparing scores |
Seeing hyperparameters in scikit-learn
Every estimator stores its hyperparameters as constructor arguments. get_params lists them, and set_params changes them.
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
pipe = make_pipeline(StandardScaler(), SVC())
print(pipe.get_params()["svc__C"])
print(pipe.get_params()["svc__gamma"])
pipe.set_params(svc__C=10, svc__gamma=0.01)
print(pipe.get_params()["svc__C"])In a pipeline, each name has the step name, two underscores, and the parameter name. So svc__C is the C of the step called svc. You will use these names in every search grid in this tutorial.
What tuning means
Tuning is a search. You pick candidate hyperparameter settings, estimate how well each one generalizes, and keep the best. The candidates form a grid, such as three values of C times three values of gamma, which gives nine settings.
The estimate for each setting cannot come from the training data. A flexible model scores very well on data it has already seen, so training scores always favor the most complex setting. The estimate must come from data the model did not fit on. Cross-validation, from the previous chapter, supplies this: each candidate is fitted and scored on several train and validation splits, and the scores are averaged.
A first look at tuning by hand
This loop does by hand what the next chapter automates. It scores three values of C and prints each mean accuracy.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
for C in [0.1, 1, 10]:
pipe = make_pipeline(StandardScaler(), SVC(C=C))
scores = cross_val_score(pipe, X, y, cv=cv)
print(f"C={C}: mean accuracy {scores.mean():.3f}")Tuning here means picking the C with the highest printed mean. That choice is the step this tutorial examines. The winning score was used to make the choice, so it is no longer a clean measurement of how the model will do on new data.
Common mistakes
- Treating a hyperparameter as something
fitwill find. It will not. Only your search changes it. - Scoring candidates on the training set. Complex settings will always win.
- Tuning many hyperparameters with a wide grid on a small dataset. More candidates give more chances for one of them to look good by luck.
Exercise
In make_pipeline(StandardScaler(), SVC()), what is the name of the parameter you would set to change the SVM's regularization strength, and is it a hyperparameter or a learned parameter?
Show answer
The name is svc__C. It is a hyperparameter, because you set it before fit and training does not change it. The support vectors and their weights, by contrast, are learned parameters.