Sub topic 8
Evaluating a tree with cross-validation
This chapter assumes you can train a DecisionTreeClassifier in scikit-learn, and that you know what training and test sets are and why a deep tree overfits. Here you will learn how to measure a tree's generalization honestly, how to use that measurement to choose hyperparameters, and which mistakes make the numbers look better than they are.
Why one train/test split is not enough
A single split gives one accuracy number. Trees make that number noisy. A small change in the training data can change the root split, and everything below it changes with it. Two splits of the same dataset can therefore produce quite different test scores.
Reusing the test set to tune the tree creates a second problem. If you try twenty values of max_depth and keep the one with the best test score, you have chosen the winner using the test labels. That score is now optimistic, because the test set is no longer unseen.
Cross-validation addresses both problems. It averages over several train/validation splits, so you also get an estimate of how much the score varies. The test set stays untouched until the end.
How k-fold cross-validation works
In k-fold cross-validation, you split the training data into k folds of roughly equal size. You train k times. Each time, one fold is held out for validation and the other k-1 folds are used for fitting. The k validation scores are averaged.
Five or ten folds are the usual choices. More folds give each model more training data but cost more fits, and the fold scores become more correlated with each other. For a single tree, fitting is cheap, so 10 folds is rarely a problem.
Stratification and shuffling
For classification, use stratified folds. Each fold keeps roughly the same class proportions as the full training set. Without stratification, a rare class can be nearly absent from a fold, which makes the validation score erratic.
scikit-learn uses stratified folds by default when you pass an integer cv to a classifier. Data that is sorted by label or by time is a different matter. For that data, pass StratifiedKFold(shuffle=True, random_state=...) explicitly so the fold boundaries do not follow the file order.
Comparing depths with cross_validate
cross_validate returns the validation scores and, if you ask for them, the training scores. Comparing the two shows overfitting directly, which connects back to the previous chapter.
from sklearn.datasets import load_iris
from sklearn.model_selection import StratifiedKFold, cross_validate, 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)
print("depth train valid valid_std")
for depth in [1, 2, 3, 4, None]:
clf = DecisionTreeClassifier(max_depth=depth, random_state=0)
res = cross_validate(clf, X_train, y_train, cv=cv, return_train_score=True)
print(
depth,
round(res["train_score"].mean(), 3),
round(res["test_score"].mean(), 3),
round(res["test_score"].std(), 3),
)Note that cross_validate names the validation scores test_score. These are the held-out fold scores, not your real test set.
Read the output like this:
- A very shallow tree has low training and low validation scores. It underfits.
- As depth grows, the training score climbs toward 1.0.
- The validation score rises, then flattens or dips. The gap between training and validation scores widens as the tree starts memorizing noise.
Choose the simplest tree whose validation score is close to the best. A common rule is to take the smallest tree within one standard deviation of the top mean score. On iris the standard deviations are large relative to the differences between depths, so several depths are statistically indistinguishable. Prefer the smaller one.
Always report the spread
A mean of 0.95 with a standard deviation of 0.04 says something different from 0.95 with 0.01. With only 105 training rows, as in iris here, each fold holds 21 samples, so one misclassified flower moves a fold score by about 0.05. Differences smaller than the fold-to-fold spread are not evidence that one setting is better.
The folds are also not independent, since they share training data. The standard deviation is therefore a rough guide, not a confidence interval.
Tuning without fooling yourself
GridSearchCV runs cross-validation for each hyperparameter combination and picks the best. Its best_score_ is still biased upward, because the winner was selected on those same folds. To estimate how well the whole procedure (search plus refit) generalizes, wrap the search in an outer cross-validation loop. This is nested cross-validation.
from sklearn.datasets import load_iris
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score
from sklearn.tree import DecisionTreeClassifier
data = load_iris()
param_grid = {
"max_depth": [2, 3, 4, 5, None],
"min_samples_leaf": [1, 3, 5, 10],
}
inner = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=2)
search = GridSearchCV(DecisionTreeClassifier(random_state=0), param_grid, cv=inner)
scores = cross_val_score(search, data.data, data.target, cv=outer)
print("nested scores:", scores.round(3))
print("mean:", round(scores.mean(), 3), "std:", round(scores.std(), 3))Each outer round hands its training portion to the search, which runs its own inner cross-validation, refits the best tree on that portion, and scores it on the outer held-out fold. The outer scores never influenced the choice of hyperparameters.
Nested cross-validation fits many trees: 5 outer folds, 20 grid points, and 5 inner folds is 500 fits plus 5 refits. That is fine for a tree on small data, but plan for it on large data.
You use nested cross-validation to estimate performance, not to produce the final model. For the final model, run the plain search on all training data, then evaluate the refit tree once on the test set.
Preventing leakage with a Pipeline
Leakage happens when information from a validation fold influences training. Trees do not need feature scaling, but real data often needs imputation, encoding, or feature selection. If you fit those steps on the whole dataset before cross-validating, each validation fold has already contributed to the statistics, such as the imputation median.
Put every fitted preprocessing step inside a Pipeline. Cross-validation then refits the whole pipeline on each training fold.
from sklearn.datasets import load_breast_cancer
from sklearn.impute import SimpleImputer
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
pipe = Pipeline([
("impute", SimpleImputer(strategy="median")),
("tree", DecisionTreeClassifier(max_depth=4, min_samples_leaf=5, random_state=0)),
])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(pipe, X, y, cv=cv, scoring="roc_auc")
print("AUC per fold:", scores.round(3))
print("mean AUC:", round(scores.mean(), 3))This dataset has no missing values, so the imputer changes nothing here. The point is the structure: the imputer is fitted separately on each training fold.
Choosing the metric
The default scoring for a classifier is accuracy. That misleads when classes are imbalanced. A tree on data with 95% negatives can score 0.95 by predicting only the majority class. Pass scoring= to change the metric:
| Situation | Suggested `scoring` |
|---|---|
| Balanced classes | `"accuracy"` |
| Imbalanced binary problem | `"roc_auc"` or `"average_precision"` |
| Cost of missed positives matters | `"recall"` or `"f1"` |
| Multiclass with uneven classes | `"f1_macro"` or `"balanced_accuracy"` |
| Regression tree | `"neg_mean_squared_error"` or `"r2"` |
Scores prefixed with neg_ are negated so that higher is always better. Take the negative of the value if you want the plain error.
Be careful with ROC AUC on a tree. A tree's predicted probability in a leaf is the class fraction among its training samples. Small leaves give coarse values like 0 or 1, so the ranking is crude. Setting min_samples_leaf above 1 usually gives smoother probabilities.
When plain k-fold is wrong
Standard k-fold assumes rows are independent. Check this before trusting a score.
- Grouped data. If several rows come from the same patient, customer, or device, a random split puts siblings in both training and validation. The tree memorizes the group and the score is inflated. Use
GroupKFoldand passgroups=. - Time series. A random split lets the model train on the future. Use
TimeSeriesSplitso validation always comes after training. - Duplicates. Exact duplicate rows have the same effect as groups. Deduplicate first.
- Very small classes. With fewer samples in a class than folds, stratification fails or warns. Reduce
n_splits. - Repeated randomness. Trees break ties between equally good splits using the random state. Set
random_statein the estimator and the splitter so results are reproducible. For a steadier estimate, useRepeatedStratifiedKFold.
A practical workflow
- Hold out a test set and do not look at it.
- Run stratified k-fold on the training set, with preprocessing inside a pipeline.
- Compare training and validation scores across a range of depths or
ccp_alphavalues to see where the gap opens. - Pick the simplest setting within one standard deviation of the best mean.
- Optionally run nested cross-validation to report an honest estimate for the whole tuning procedure.
- Refit on the full training set and score the test set once.
Exercise
You run GridSearchCV over maxdepth and minsamplesleaf on your whole dataset and report bestscore_ as your expected accuracy on new data. Give two reasons it is optimistic and one way to get a fairer estimate.
Show answer
First, the best setting was chosen because it scored highest on those same folds, so the score includes selection luck. Second, if any preprocessing or feature selection was fitted on the full data before the search, validation folds leaked into training. A fairer estimate comes from nested cross-validation, with the search inside an outer loop and preprocessing inside a Pipeline, or from scoring a refit tree once on a held-out test set.
Exercise
Five-fold cross-validation of a depth-limited tree gives validation accuracy 0.91 with a standard deviation of 0.05, and a second setting gives 0.93 with a standard deviation of 0.05. The second tree has three times as many leaves. Which would you choose, and why?
Show answer
Choose the smaller tree. The 0.02 difference is well inside the 0.05 fold-to-fold spread, so it is not reliable evidence of improvement, and the simpler tree is easier to read and less likely to overfit.