Sub topic 6
Common hyperparameters and what they control
This chapter assumes you can train and evaluate a scikit-learn model, know the difference between overfitting and underfitting, and understand train/validation/test splits. Here you will learn which hyperparameters matter for the model families you will meet most often, and what each one does to the model. Chapter 7 covers how to turn them into a search space.
Why know what a setting does before you tune it
A hyperparameter is a setting you choose before training. The learning algorithm does not adjust it. Tuning every setting a model exposes wastes compute. Most models have a few settings that dominate performance and many that barely matter.
Knowing what each setting controls gives you three things:
- A sensible starting range, so the search does not spend trials on settings that are obviously too extreme.
- A direction to move when you see overfitting or underfitting.
- A way to spot settings that interact, so you search them together.
Almost every hyperparameter acts on one idea: model capacity, meaning how flexible the model is. High capacity fits the training data closely and risks overfitting. Low capacity risks underfitting. Many hyperparameters either raise capacity or restrain it.
Regularization strength
Regularization adds a penalty that discourages large or complex solutions. It restrains capacity.
In linear models and support vector machines, scikit-learn exposes this as C (in LogisticRegression and SVC) or alpha (in Ridge, Lasso, and SGDClassifier).
Cis the inverse of regularization strength. A smallCmeans strong regularization and a simpler model. A largeCmeans weak regularization and a more flexible one.alphaworks the other way around. A largealphameans strong regularization.
Mixing up these two directions is a common error. Check the documentation for the direction before you reason about a result.
The penalty type is also a hyperparameter. penalty="l2" shrinks all weights toward zero. penalty="l1" can set some weights exactly to zero, which acts as feature selection. ElasticNet mixes both, controlled by l1_ratio.
Regularization strengths usually span several orders of magnitude, for example 0.001 to 1000. That is why they are searched on a log scale.
Kernel and kernel parameters (support vector machines)
A support vector machine with a non-linear kernel has two settings that work together.
kernelchooses the shape of the decision boundary."linear"gives a flat boundary."rbf"(radial basis function) gives a flexible, curved one.gammacontrols how far the influence of a single training point reaches in therbfkernel. A smallgammagives a smooth boundary that changes slowly. A largegammamakes each point influence only its close neighbors, which produces a wiggly boundary that can overfit.
C and gamma interact. A large gamma with a large C is a common recipe for overfitting. A good value of one often depends on the other, so tune them jointly and not one at a time.
Tree depth and leaf size
Decision trees grow by splitting the data. Without limits, a tree keeps splitting until each leaf holds a single training example, which memorizes the data. Several settings limit growth.
| Hyperparameter | What it controls | Effect of increasing it |
|---|---|---|
| `max_depth` | Longest path from root to leaf | More capacity, more overfitting risk |
| `min_samples_leaf` | Fewest samples allowed in a leaf | Less capacity, smoother predictions |
| `min_samples_split` | Fewest samples needed to split a node | Less capacity |
| `max_leaf_nodes` | Total number of leaves | More capacity |
| `ccp_alpha` | Cost-complexity pruning strength | Less capacity |
Notice that the direction differs. Raising max_depth adds capacity, while raising min_samples_leaf removes it. For a first search, max_depth and min_samples_leaf are usually enough, because they overlap in effect with the others.
Ensemble settings: forests and boosting
Ensembles combine many trees. Their settings fall into two groups.
Random forests train many independent trees and average them.
n_estimatorsis the number of trees. More trees reduce variance and never meaningfully hurt accuracy, but they cost time and memory. Treat it as a budget choice and not as something to tune carefully. Pick a value large enough that the score stops improving.max_featuresis how many features each split may consider. Smaller values make trees more different from each other, which improves the average but weakens each tree.- Tree settings such as
max_depthandmin_samples_leafstill apply.
Gradient boosting trains trees one after another, each correcting the errors of the previous ones. Here n_estimators behaves differently. Adding more trees keeps fitting the training data more closely, so too many leads to overfitting.
learning_ratescales how much each new tree contributes. A small rate needs more trees but usually generalizes better.n_estimatorsandlearning_ratetrade off against each other. Halving the rate roughly calls for doubling the trees. Tune them as a pair, or fix a small rate and use early stopping (Chapter 12) to find the tree count.max_depthis typically small in boosting, often 3 to 8, because each tree only needs to be a weak learner.subsampletrains each tree on a random fraction of the rows. Values below 1.0 add regularization.
Neighbors, learning rate, and batch size
k-nearest neighbors has one dominant setting, n_neighbors. A small k gives a flexible, noisy model. A large k gives a smooth model that can underfit. weights ("uniform" or "distance") and the distance metric also matter. Because neighbors rely on distance, scale your features inside a pipeline first.
Models trained by gradient descent, such as neural networks and SGDClassifier, add optimization settings.
learning_rate(oreta0) is the step size of each update. Too large and training diverges or oscillates. Too small and training is slow or stalls. It is often the single most important setting, and it is searched on a log scale.batch_sizeis how many examples feed each update. Small batches give noisy updates that can help generalization. Large batches give stable updates and faster hardware use. The best learning rate often shifts when you change batch size.epochs(ormax_iter) is how many passes over the data to make. Too many leads to overfitting. This setting is better handled by early stopping than by a fixed grid.- Architecture settings such as the number and width of layers (
hidden_layer_sizesinMLPClassifier) set capacity.dropoutandweight decayregularize.
Seeing the effect: a validation curve
You can check what a single hyperparameter does before searching. validation_curve scores a model across values of one setting, with cross-validation, and returns training and validation scores.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import validation_curve
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
depths = np.arange(1, 11)
train_scores, val_scores = validation_curve(
DecisionTreeClassifier(random_state=0),
X,
y,
param_name="max_depth",
param_range=depths,
cv=5,
)
for d, tr, va in zip(depths, train_scores.mean(axis=1), val_scores.mean(axis=1)):
print(f"max_depth={d:2d} train={tr:.3f} validation={va:.3f}")Read the output as follows. At small depths both scores are low, which is underfitting. As depth grows, the training score climbs toward 1.0. The validation score rises and then flattens or falls. The gap between the two columns is the overfitting signal. A good depth sits near the best validation score, before the gap grows large.
The same curve shape appears for most capacity-raising settings. The reverse shape appears for restraining settings such as C in a small range or min_samples_leaf.
Common errors
- Tuning too many settings at once. The search space grows multiplicatively. Pick the two to four settings with the largest effect, such as
Candgamma, orlearning_rateandmax_depth. - Misreading direction.
Candalphapoint in opposite directions.n_estimatorsis harmless in a forest and risky in boosting. - Ignoring interactions.
Cwithgamma, andlearning_ratewithn_estimators, are linked pairs. Search them together. - Tuning a setting that is really a budget. The number of trees in a forest is chosen by cost, not by search.
- Forgetting scale. Distance-based and gradient-based models need scaled features. Put the scaler inside the pipeline so tuning does not leak information.
- Trusting defaults blindly. Defaults are reasonable general choices, not optimal ones for your data. They are a good baseline to compare tuned results against.
Summary table
| Model family | Settings that usually matter most |
|---|---|
| Logistic regression, linear SVM | `C`, `penalty` |
| RBF support vector machine | `C`, `gamma` |
| Decision tree | `max_depth`, `min_samples_leaf` |
| Random forest | `max_features`, `min_samples_leaf`, `max_depth` |
| Gradient boosting | `learning_rate`, `n_estimators`, `max_depth`, `subsample` |
| k-nearest neighbors | `n_neighbors`, `weights` |
| Neural network | `learning_rate`, `batch_size`, layer width, regularization |
Exercise
A gradient boosting model reaches 0.99 accuracy on the training folds and 0.88 on the validation folds. You can change learning_rate, n_estimators, max_depth, and subsample. Name two changes that should reduce the overfitting, and explain why lowering learning_rate alone may not help unless you also change n_estimators.
Show answer
Two options are to lower max_depth (each tree has less capacity) and to set subsample below 1.0 (each tree sees only part of the rows, which regularizes). You could also stop adding trees earlier by reducing n_estimators. Lowering learning_rate alone makes each tree contribute less, so the model fits more slowly. If n_estimators stays the same, the model may then underfit instead. The two settings trade off, so lower the rate and raise the tree count together, or use early stopping to choose the count.
Exercise
You tune an RBF support vector machine and find that the best result sits at the largest gamma and largest C in your grid, and the training score is near 1.0 with a much lower validation score. What does this suggest, and what would you do next?
Show answer
Large gamma and large C both raise capacity, so the pattern points to overfitting. A best value at the edge of the grid also means the search range may be too narrow, but here the gap between train and validation scores says the edge is not truly best. Check the validation scores near that edge, since the best score may be a noisy peak. Shift the search toward smaller gamma and C, using log-spaced values, and compare against the default model.