Sub topic 8
Evaluating a tree with cross-validation
This chapter assumes you can train a scikit-learn classifier and know what training and test sets are. It also assumes you know why an unrestricted tree overfits. Here you will learn to estimate how well a tree generalizes without spending your test set on every tuning decision.
Why one split is not enough
A single train/validation split gives one accuracy number. On small datasets that number depends heavily on which rows landed in the validation set. Trees make this worse because they have high variance. A few changed rows can produce a different root split and a different tree.
K-fold cross-validation reduces this noise. It splits the training data into k folds and trains k times. Each time, one fold is held out for scoring and the other k-1 folds are used for fitting. You then average the k scores.
Cross-validating a tree
The code below compares several values of max_depth using stratified folds. Stratified folds keep the class proportions roughly equal in every fold. After choosing a depth, it refits on the whole training set and scores the test set once.
from sklearn.datasets import load_iris
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.tree import DecisionTreeClassifier
data = load_iris()
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
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
results = {}
for depth in [1, 2, 3, 5, None]:
tree = DecisionTreeClassifier(max_depth=depth, random_state=0)
scores = cross_val_score(tree, X_train, y_train, cv=cv)
results[depth] = (scores.mean(), scores.std())
print(f"max_depth={depth}: mean={scores.mean():.3f} std={scores.std():.3f}")
best_depth = max(results, key=lambda d: results[d][0])
final = DecisionTreeClassifier(max_depth=best_depth, random_state=0)
final.fit(X_train, y_train)
print("chosen max_depth:", best_depth)
print("test accuracy:", final.score(X_test, y_test))Read both columns. The mean tells you the expected performance. The standard deviation tells you how much the score moves between folds. If two depths have nearly equal means, prefer the shallower one. It is simpler and easier to read.
Common errors
- Tuning on the test set. If you pick hyperparameters by looking at test accuracy, the test score is no longer an honest estimate. Tune with cross-validation on the training data only.
- Comparing training accuracy. An unrestricted tree usually reaches 100% training accuracy. That number says nothing about generalization. Compare it with the cross-validated score to see the gap.
- Unshuffled folds on ordered data. The iris file is sorted by class. Without
shuffle=True, plain k-fold can put a whole class in one fold. Passing an integercv=5to a classifier already uses stratified folds without shuffling, so set up the splitter yourself when order matters. - Preprocessing outside the folds. Steps that learn from data, such as imputing or encoding, must be fitted inside each fold. Put them in a
Pipelineand pass the pipeline tocross_val_score. Trees do not need feature scaling, but they still need this rule for other steps. - Ignoring the metric. Accuracy misleads on imbalanced classes. Pass
scoring="f1_macro"orscoring="balanced_accuracy"when classes are uneven.
Exercise
Five-fold cross-validation on a tree gives scores with a mean of 0.94 and a standard deviation of 0.01 for maxdepth=3, and a mean of 0.94 with a standard deviation of 0.04 for maxdepth=None. Which setting would you choose, and why?
Show answer
Choose max_depth=3. The means are equal, but the shallower tree has much lower variation between folds, so its performance is more stable. It is also smaller and easier to interpret as rules.