Sub topic 2
Common Hyperparameters and What They Control
Assume you know basic Python, supervised learning, and scikit-learn. A hyperparameter is a setting chosen before training. A learned parameter is fitted from the training data. For example, a decision tree’s maximum depth is a hyperparameter, while its split rules are learned parameters.
Common hyperparameters
| Model | Hyperparameter | What it controls |
|---|---|---|
| Decision tree | `max_depth` | Maximum number of levels |
| Random forest | `n_estimators` | Number of trees |
| SVM | `C` | Penalty for training errors |
| SVM with an RBF kernel | `gamma` | How far each training example influences others |
| Neural network | `learning_rate` | Size of each weight update |
| K-nearest neighbors | `n_neighbors` | Number of examples used for a prediction |
A high-capacity setting, such as a deep tree, can fit training data closely but overfit. A restrictive setting, such as a very shallow tree, can underfit. Tuning searches for settings that generalize well to unseen data.
Defining a search space
A search space lists the values or distributions that tuning may try. Use values that match the hyperparameter’s type:
- Use integers for counts such as
n_estimators. - Use categorical values for choices such as a kernel type.
- Use a logarithmic scale for values spanning orders of magnitude, such as
learning_rate,C, andgamma.
Grid search
Grid search evaluates every combination in a fixed list. It is easy to understand and works well when the space is small.
Random search
Random search samples combinations from distributions. It often explores large spaces more efficiently because some hyperparameters matter more than others.
from scipy.stats import loguniform
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
pipe = make_pipeline(StandardScaler(), SVC())
grid = GridSearchCV(
pipe,
{"svc__C": [0.1, 1, 10], "svc__gamma": [0.001, 0.01, 0.1]},
cv=5,
)
random = RandomizedSearchCV(
pipe,
{"svc__C": loguniform(1e-2, 1e2),
"svc__gamma": loguniform(1e-4, 1e0)},
n_iter=20,
cv=5,
random_state=0,
)Exercise
When is random search usually preferable to grid search?
Show answer
Use random search when the search space is large or contains continuous values across several orders of magnitude.