Sub topic 2
Why settings matter: generalization, overfitting, and underfitting
This chapter assumes you can train and score a scikit-learn model, and that you know the basic idea of a train/test split. It covers how hyperparameter values change a model's ability to generalize, and how to diagnose which direction a setting is pushing the model. Later chapters cover the splits, the metrics, and the search methods in detail.
Generalization is the goal
A model is trained on a finite sample, but it is used on data it has never seen. Generalization is how well its performance on the training sample carries over to new data drawn from the same source. The quantity you care about is the generalization error, the expected error on fresh data. You can't measure it exactly. You estimate it with data the model did not train on.
Training error is a poor estimate of generalization error, because the training procedure is built to reduce it. A flexible model can reduce it all the way to zero by memorizing the sample, noise included.
Hyperparameters set how flexible the model is and how hard the training procedure pushes against that flexibility. They don't change what the model learns from a given example. They change the range of things it is able to learn, and how strongly it is discouraged from using that range.
Two ways to fail
Underfitting happens when the model is too constrained to capture the real pattern. Training error is high, validation error is similar, and both are bad. Adding data will not help much, because the model can't use it.
Overfitting happens when the model is flexible enough to fit noise that is specific to the training sample. Training error is low, validation error is clearly higher, and the gap between them is large.
These two cases are the ends of the bias-variance trade-off:
- Bias is error from wrong or overly rigid assumptions. High bias produces underfitting.
- Variance is error from sensitivity to the particular training sample. If you retrained on a different sample and got a very different model, variance is high. High variance produces overfitting.
Making a model more flexible usually lowers bias and raises variance. Tuning looks for the setting where the sum of the two, measured on held-out data, is smallest.
Hyperparameters as a complexity dial
Most of the common hyperparameters act as a dial between those two failure modes. The table shows the direction of the effect for a few well-known ones.
| Hyperparameter | Model | Increasing it tends to |
|---|---|---|
| `max_depth` | Decision tree, random forest | Raise complexity, risk overfitting |
| `min_samples_leaf` | Decision tree, random forest | Lower complexity, risk underfitting |
| `C` | SVC, logistic regression | Weaken regularization, raise complexity |
| `alpha` | Ridge, Lasso | Strengthen regularization, lower complexity |
| `n_neighbors` | k-nearest neighbors | Smooth the decision boundary, lower complexity |
| `gamma` | RBF-kernel SVC | Make the boundary more local, raise complexity |
Check the direction in the library documentation before you rely on it. C in scikit-learn is the inverse of regularization strength, while alpha is the regularization strength itself. Mixing these up is a common source of searches that run in the wrong direction.
Not every hyperparameter is a complexity dial. Some, such as the learning rate, mostly affect whether and how fast training converges. Others, such as n_estimators in a random forest, have diminishing returns instead of a sweet spot. The next chapters on common hyperparameters and search spaces separate these cases.
Seeing the trade-off: a validation curve
A validation curve plots training and cross-validated scores as one hyperparameter varies and the rest stay fixed. It is the quickest way to see where a model sits between underfitting and overfitting. Here the dial is max_depth of a decision tree.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, validation_curve
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
depths = np.arange(1, 13)
train_scores, val_scores = validation_curve(
DecisionTreeClassifier(random_state=0),
X_train,
y_train,
param_name="max_depth",
param_range=depths,
cv=5,
scoring="accuracy",
)
train_mean = train_scores.mean(axis=1)
val_mean = val_scores.mean(axis=1)
for d, tr, va in zip(depths, train_mean, val_mean):
print(f"max_depth={d:2d} train={tr:.3f} validation={va:.3f} gap={tr - va:.3f}")
best = depths[val_mean.argmax()]
print("Best validation score at max_depth =", best)Read the output in three parts:
- At very small depths, both scores are low and close together. That is underfitting.
- As depth grows, both scores rise until the validation score peaks.
- Past the peak, the training score keeps climbing toward 1.0 while the validation score flattens or drops. The widening gap is overfitting.
The test set is split off here but never scored. It stays untouched until the setting is chosen. The next chapters explain why.
Exact numbers depend on your scikit-learn version and the split, so rely on the shape of the curves. Because five folds each give a noisy estimate, small differences between neighboring depths are often not meaningful. A flat region near the top is common, and any setting in it is about equally good.
Diagnosing from the two scores
Two numbers, training score and validation score, are enough for a first diagnosis. The figure shows how to read them.
"Poor" and "much worse" need a reference point. A useful reference is a trivial baseline, such as DummyClassifier, or a known human or business target. A training accuracy of 0.80 is poor on a task where a simple model reaches 0.95, and excellent on one where the baseline is 0.55.
Limits of this picture
The simple U-shaped story has exceptions that matter when you design a search.
- Hyperparameters interact. A deeper tree may need a larger
min_samples_leafto stay well behaved. The best value ofgammadepends onC. A one-dimensional curve with the others fixed can be misleading, which is why searches vary several values at once. - More flexible does not always mean worse. Large neural networks and boosted ensembles can keep improving on validation data after reaching zero training error. A large gap alone does not prove a setting is bad. Only the validation score decides.
- Data size changes the best setting. With more data, the same model overfits less, so the best complexity usually rises. Settings tuned on a small subsample may not carry over to the full dataset.
- Noise sets a floor. If labels are noisy, even the best model has a nonzero error. Chasing the last fraction of a percent of validation score can mean fitting noise in the validation folds.
That last point leads to the main risk in tuning. Every time you compare settings on the same validation data and keep the best one, you select partly for luck. With many candidates, the winner's validation score is optimistic. Hyperparameters can overfit the validation data just as parameters overfit the training data. This is why the final test set must be scored once, after all choices are made, and why later chapters introduce cross-validation and nested cross-validation.
Practical habits
- Always record both training and validation scores for each setting. Looking only at the validation score hides whether a model underfits or overfits.
- Compare against a baseline before tuning. If a tuned model barely beats
DummyClassifier, the problem is likely features or labels, not hyperparameters. - Treat differences smaller than the fold-to-fold spread as ties, and prefer the simpler model among them.
- Change the complexity dial first. Settings that control optimization details, such as solver tolerance, rarely fix a large train-validation gap.
Exercise
A random forest has training accuracy 0.99 and 5-fold validation accuracy 0.82. A baseline that always predicts the majority class scores 0.60. Which failure mode does this suggest, and name two hyperparameter changes you would try first.
Show answer
The large gap between training and validation scores suggests overfitting (high variance), and 0.82 is well above the baseline so the model has learned real signal. Reduce complexity by lowering max_depth and by raising min_samples_leaf. Lowering max_features is another option. Then check whether the validation score rises and the gap narrows.
Exercise
In the validation curve code, why is the test set created with train_test_split but never scored?
Show answer
The test set is reserved for one final estimate of generalization after all hyperparameter choices are made. Scoring it while comparing depths would let test results influence the choice, making the final score optimistic.