Sub topic 10
Tuning the main hyperparameters
This chapter assumes you can train a scikit-learn DecisionTreeClassifier, and that you know what overfitting is, how cross-validation works, and how pruning and stopping rules limit tree growth. Here we turn those ideas into a tuning procedure.
What a hyperparameter is here
A tree learns its splits and thresholds from data. A hyperparameter is a setting you choose before training, and it controls how far that learning goes. Almost every tree hyperparameter limits complexity in one of three ways:
- It caps the size of the tree (
max_depth,max_leaf_nodes). - It demands evidence before a split is allowed (
min_samples_split,min_samples_leaf,min_impurity_decrease). - It removes branches after growth (
ccp_alpha).
A fourth group changes how each split is searched, not how big the tree gets (criterion, max_features, splitter).
The parameters that matter most
| Hyperparameter | Default | Effect | Typical range to try |
|---|---|---|---|
| `max_depth` | `None` | Hard cap on the number of splits from root to any leaf | 2 to 12, plus `None` |
| `min_samples_leaf` | 1 | Every leaf must hold at least this many training samples | 1, 5, 10, 20, 50 |
| `min_samples_split` | 2 | A node needs at least this many samples to be considered for a split | 2, 10, 20, 50 |
| `max_leaf_nodes` | `None` | Grows the tree best-first until it has this many leaves | 5 to 100 |
| `min_impurity_decrease` | 0.0 | A split must reduce weighted impurity by at least this amount | 0.0 to 0.05 |
| `ccp_alpha` | 0.0 | Post-pruning strength from the cost-complexity path | Taken from the pruning path |
| `criterion` | `"gini"` | Impurity measure used to score splits | `"gini"`, `"entropy"` |
| `max_features` | `None` | Number of features examined at each split | `None`, `"sqrt"`, `"log2"` |
| `class_weight` | `None` | Reweights classes in the impurity calculation | `None`, `"balanced"` |
Depth and leaf size do most of the work
max_depth is the blunt tool. A depth-3 tree has at most 8 leaves, and a depth-10 tree can have up to 1024. It treats every branch the same, so it cuts off a promising branch as readily as a noisy one.
min_samples_leaf is usually the better first choice. It reacts to the data, so dense regions can still be split finely while sparse regions stay coarse. It also gives each leaf's prediction a minimum sample size. A leaf holding one sample reports a probability of exactly 0 or 1, which is rarely trustworthy. With min_samples_leaf=10, class probabilities from predict_proba are estimated from at least ten samples.
For regression, the same parameter keeps leaf means from being driven by one or two noisy targets.
Split-count thresholds interact with leaf size
min_samples_split and min_samples_leaf overlap. If min_samples_leaf=10, a node with fewer than 20 samples can never be split anyway, because both children would need at least 10. Setting min_samples_split=15 in that case does nothing. Tune one of them, normally min_samples_leaf, and leave the other at its default unless you have a reason.
Both accept a float between 0 and 1, which is treated as a fraction of the training set. Fractions keep a setting meaningful when the dataset size changes.
Impurity decrease and leaf count
min_impurity_decrease rejects splits whose weighted impurity gain is below a threshold. The gain is weighted by the fraction of all training samples reaching the node. Because of that weighting, the same threshold is stricter deep in the tree, where nodes hold few samples. It is a pre-pruning rule with a known weakness: a split with a small gain can unlock a very useful split below it, and this rule never sees that.
max_leaf_nodes changes the growth order. The tree expands the node with the largest impurity reduction first, instead of growing level by level. The leaf budget is then spent where it helps most. It is a good single knob when you need a model of a known size, for example a tree a person must read.
Criterion rarely matters
Gini and entropy give similar trees on most datasets. Treat criterion as a low-priority option. Entropy is slightly slower because of the logarithm. Putting it in the grid is cheap, but do not expect a large gain from it.
Features and class weights
max_features limits how many randomly chosen features are examined at each split. For one tree it usually hurts or does nothing. Its value shows up in random forests, where it makes the trees differ from each other. Leave it at None for a single tree unless you have many noisy features.
class_weight="balanced" multiplies sample counts by weights inversely proportional to class frequency. This changes the impurity calculation, so it changes which splits are chosen. It helps when a rare class matters, but it also lowers plain accuracy, so choose a scoring metric that reflects your goal.
A tuning procedure
Tune against cross-validation on the training set only. Keep the test set untouched until you have one final model. If you pick hyperparameters by looking at test scores, the test score is no longer an honest estimate.
Step 1: see the shape of the problem
A validation curve varies one hyperparameter and records training and cross-validated scores. The point where the validation score peaks and then falls while the training score keeps rising marks the start of overfitting.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import validation_curve, 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
)
depths = [1, 2, 3, 4, 5, 6, 8, 10]
train_scores, val_scores = validation_curve(
DecisionTreeClassifier(random_state=0),
X_train,
y_train,
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}")Look for the depth where validation stops improving. Beyond it, extra depth only memorizes the training set.
Step 2: search several parameters together
Hyperparameters interact. A depth limit of 6 behaves differently with min_samples_leaf=1 than with min_samples_leaf=20. A grid search covers combinations.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold, 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"],
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
search = GridSearchCV(
DecisionTreeClassifier(random_state=0),
param_grid,
cv=cv,
scoring="accuracy",
)
search.fit(X_train, y_train)
results = search.cv_results_
for i in np.argsort(results["rank_test_score"])[:5]:
print(
results["params"][i],
"mean=%.3f" % results["mean_test_score"][i],
"std=%.3f" % results["std_test_score"][i],
)
print("best params:", search.best_params_)
print("cv score:", round(search.best_score_, 3))
print("test score:", round(search.score(X_test, y_test), 3))This grid has 5 × 4 × 2 = 40 combinations, and 5-fold cross-validation fits each one five times, so the search trains 200 trees. The cost multiplies as you add parameters, which is why you should choose parameters by importance and not add all of them.
Step 3: read the results, not just the winner
Several things deserve a look in cv_results_:
- Ties and near-ties. With small data, the top five configurations often differ by less than one standard deviation. Their differences are noise. Among near-ties, prefer the simplest tree: it is easier to read and less likely to be an accident of the folds.
- Edge values. If the best
min_samples_leafis 20, the largest value you tried, the true optimum may be higher. Extend the grid. - The train-validation gap. Use
return_train_score=TrueinGridSearchCVto see it. A gap near zero with low scores suggests underfitting, so loosen the constraints. A large gap suggests overfitting, so tighten them.
Step 4: combine with pruning
ccp_alpha can be searched like any other numeric parameter, using values from cost_complexity_pruning_path. A practical pattern is to fix a mild pre-pruning rule, such as min_samples_leaf=5, and then search ccp_alpha. Pre-pruning keeps tree construction fast, and cost-complexity pruning does the fine adjustment. Searching a wide max_depth grid and a wide ccp_alpha grid together is redundant, because both control size.
Common errors
- Tuning on the test set. Repeated peeks at test accuracy leak information. Do all selection with cross-validation.
- Forgetting
random_state. Ties between equally good splits are broken at random, so trees can differ between runs. Fixrandom_stateto make comparisons repeatable. - Unstratified or unshuffled folds. If the data is sorted by class, plain k-fold can produce folds with missing classes. Use
StratifiedKFoldwithshuffle=Truefor classification. - Accuracy on imbalanced data. A tree that always predicts the majority class can score well. Choose
scoringsuch as"f1","balanced_accuracy", or"roc_auc". - Preprocessing leaks. If you scale or impute before splitting folds, put those steps in a
Pipeline. Trees do not need scaling, but imputers and encoders fit on all the data would still leak. - Over-wide searches on small data. With a few hundred rows, a huge grid will find a configuration that is lucky on the folds. Keep grids small, and report the cross-validated standard deviation.
Exercise
A grid search over max_depth in [3, 5, 8, None] and min_samples_leaf in [1, 10, 25] with 5-fold cross-validation reports best parameters max_depth=None, min_samples_leaf=25, and the second-best score is within one standard deviation. How many trees are trained during the search, and what should you check or do next?
Show answer
There are 4 × 3 = 12 combinations, and each is fit 5 times, so the search trains 60 trees (plus one more refit on the full training set by default). The best min_samples_leaf=25 sits at the top edge of the grid, so the optimum may be larger. Extend the grid with values such as 50 and 100. Because max_depth=None won, depth is not the active constraint, and leaf size is doing the regularizing. Since the runner-up is within one standard deviation, prefer the simpler configuration among the near-ties. Finally, score the chosen model once on the held-out test set.