Sub topic 10
Tuning the main hyperparameters
This chapter assumes you can train a scikit-learn classifier, know what cross-validation is, and have seen how stopping rules and cost-complexity pruning limit tree size. Here we focus on which settings to tune and how to search them without fooling yourself.
The settings that matter
A hyperparameter is a setting you choose before training. The learning algorithm does not set it. Most tree hyperparameters limit complexity, so they trade variance for bias.
| Hyperparameter | Effect | Typical range |
|---|---|---|
| `max_depth` | Caps the number of questions on any path | 2 to 12, or `None` |
| `min_samples_leaf` | Smallest number of samples allowed in a leaf | 1 to 50 |
| `min_samples_split` | Smallest node size that may still be split | 2 to 100 |
| `ccp_alpha` | Strength of cost-complexity pruning | from the pruning path |
| `criterion` | Impurity measure: `gini` or `entropy` | usually matters little |
| `max_features` | Features considered at each split | `None`, `sqrt`, or an integer |
In practice, max_depth, min_samples_leaf, and ccp_alpha do most of the work. Changing criterion rarely moves accuracy much, so tune it last.
Choosing a search strategy
Several of these settings interact. A shallow tree may not need a large min_samples_leaf, because depth already limits leaf count. Searching one setting at a time can miss good combinations. A grid search tries every combination and scores each one with cross-validation.
A working example
GridSearchCV runs the search. It refits the best model on the whole training set by default.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.tree import DecisionTreeClassifier
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
data.data, data.target, test_size=0.3, random_state=0, stratify=data.target
)
param_grid = {
"max_depth": [2, 3, 4, 6, None],
"min_samples_leaf": [1, 5, 10, 20],
"criterion": ["gini", "entropy"],
}
search = GridSearchCV(
DecisionTreeClassifier(random_state=0),
param_grid,
cv=5,
scoring="accuracy",
)
search.fit(X_train, y_train)
print("best params:", search.best_params_)
print("best CV accuracy:", round(search.best_score_, 3))
print("test accuracy:", round(search.score(X_test, y_test), 3))This grid has 5 × 4 × 2 = 40 combinations. With 5 folds, that is 200 tree fits. Trees train quickly, so this is cheap here. On large data, use RandomizedSearchCV to sample combinations instead.
Common errors
- Tuning on the test set. If you pick settings by test score, the test score is no longer an honest estimate. Select with cross-validation on the training data and look at the test set once.
- Trusting small differences. With 5 folds, two settings that differ by 0.5% are often tied. Check
search.cv_results_["std_test_score"]. Prefer the simpler tree when scores are within one standard deviation. - Forgetting stratification and seeds. Set
random_stateon the tree. Ties between equally good splits are broken randomly, so results can shift between runs. - Using only
max_depth. A depth limit still allows tiny leaves in a deep branch. Pair it withmin_samples_leaf. - Searching ranges that are too narrow. If the best value sits at the edge of your grid, extend the grid in that direction.
Exercise
A grid has max_depth with 4 values, min_samples_leaf with 5 values, and criterion with 2 values. You use 5-fold cross-validation. How many trees does GridSearchCV fit during the search, not counting the final refit? Why is it a mistake to choose the winner by test accuracy?
Show answer
4 × 5 × 2 = 40 combinations, and 40 × 5 folds = 200 fits. Choosing by test accuracy leaks information from the test set into the model choice. The test score then overestimates how the tree will do on new data. Choose by cross-validation score on the training data and use the test set once at the end.