Decision Trees
A decision tree splits the data recursively. Each internal node asks a question about one feature โ is this value below that threshold โ and each leaf carries a prediction. Training is greedy: at every node, try the candidate splits and take the one that reduces impurity most.
\[ G = 1 - \sum_{k} p_k^2 \]
That is Gini impurity, the usual criterion for classification; entropy is the alternative, and regression trees minimize squared error instead. The appeal is that the result is a flowchart anyone can read, tree methods can use numeric and categorical features, although the scikit-learn implementation used here requires categorical features to be encoded, it captures interactions without being told about them, and it does not care about feature scale โ a property normalization measures.
The standard caveat is that trees are “unstable.” It is worth seeing what that means in numbers, because it turns out to be the most important thing about them.
The same data, five different trees
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
rng = np.random.default_rng(0)
"""Instability means sensitivity to which rows you happened to collect. Five
bootstrap resamples of the same data, five trees."""
trees, roots = [], []
for seed in range(5):
r = np.random.default_rng(seed)
idx = r.integers(0, len(y), len(y))
t = DecisionTreeClassifier(random_state=0).fit(X[idx], y[idx])
trees.append(t.predict(X))
roots.append((t.tree_.feature[0], round(float(t.tree_.threshold[0]), 4), t.tree_.n_leaves))
for seed, (feat, thr, leaves) in enumerate(roots):
print(f" resample {seed}: root splits feature {feat} at {thr:+.4f}, {leaves} leaves")
pairs = [np.mean(trees[i] == trees[j]) for i in range(5) for j in range(i + 1, 5)]
print(f" the ten pairs of trees agree on {min(pairs):.4f} to {max(pairs):.4f} of rows")
lin = []
for seed in range(5):
r = np.random.default_rng(seed)
idx = r.integers(0, len(y), len(y))
lin.append(LogisticRegression(max_iter=2000).fit(X[idx], y[idx]).predict(X))
pairs_lin = [np.mean(lin[i] == lin[j]) for i in range(5) for j in range(i + 1, 5)]
print(f" logistic regression on the same resamples agrees on {min(pairs_lin):.4f} to {max(pairs_lin):.4f}")
print("\n depth against fit, and the choice of impurity measure")
print(f"{'max_depth':>10} {'gini train':>11} {'gini CV':>9} {'entropy train':>14} {'entropy CV':>11}")
for depth in (2, 5, 10, None):
row = [f"{str(depth):>10}"]
for criterion in ("gini", "entropy"):
t = DecisionTreeClassifier(max_depth=depth, criterion=criterion, random_state=0).fit(X, y)
cv = cross_val_score(DecisionTreeClassifier(max_depth=depth, criterion=criterion, random_state=0),
X, y, cv=5).mean()
row.append(f"{t.score(X, y):>11.4f} {cv:>9.4f}" if criterion == "gini"
else f"{t.score(X, y):>14.4f} {cv:>11.4f}")
print(" ".join(row))
# resample 0: root splits feature 7 at +0.0151, 101 leaves
# resample 1: root splits feature 7 at +0.1348, 103 leaves
# resample 2: root splits feature 7 at -0.4341, 111 leaves
# resample 3: root splits feature 7 at -0.0016, 105 leaves
# resample 4: root splits feature 7 at +0.0719, 98 leaves
# the ten pairs of trees agree on 0.9125 to 0.9305 of rows
# logistic regression on the same resamples agrees on 0.9585 to 0.9890
#
# depth against fit, and the choice of impurity measure
# max_depth gini train gini CV entropy train entropy CV
# 2 0.8355 0.8200 0.8355 0.8245
# 5 0.9160 0.8840 0.9100 0.8875
# 10 0.9670 0.8805 0.9815 0.8895
# None 1.0000 0.8800 1.0000 0.8810
Each resample is the same dataset, drawn with replacement โ the statistical equivalent of having collected the data on a different day. All five trees pick feature 7 for the root, but the threshold runs from โ0.4341 to +0.1348, and the number of leaves varies from 98 to 111.
More concretely, any two of these trees disagree about 7 to 9 percent of rows. Logistic regression on the identical resamples disagrees with itself on 1 to 4 percent. Trees are genuinely the less stable family, and this is on clean synthetic data โ with fewer rows or correlated features the spread widens.
The cause is the greedy split. When two candidate splits reduce impurity by nearly the same amount, a handful of rows decides which one wins, and everything below that node is then built on a different partition. Small perturbations propagate.
A displayed fitted tree faithfully describes how that particular model predicts. Resampling instability limits a different claim: that its exact branches describe a stable relationship that another training sample would recover. Show the current decision path and, when stability matters, report how paths and predictions vary under appropriate resampling.
Compare depth and the impurity criterion
The second table separates two knobs people spend unequal effort on.
Depth is the whole game. Unlimited depth gives perfect training accuracy โ 1.0000, because the tree can isolate every row โ against 0.8800 in cross-validation. Depth 5 gives 0.9160 and 0.8840. The gap between the two columns is the overfitting, and it is what pruning, max_depth and min_samples_leaf exist to control.
Gini and entropy give similar scores in this example. Their cross-validation scores differ by 0.0045 at depth 2 and 0.0090 at depth 10, without a consistent winner. They evaluate candidate splits with different impurity functions, so these small score differences do not establish identical split choices on other data. Compare the criteria within the same validation procedure rather than assuming the choice cannot matter.
Instability is why ensembles work
A single tree is a weak model, and the usual advice is to use a random forest or gradient boosting instead. The reason is the first block rather than a general preference for complexity.
Averaging can reduce variance when the base predictions are not perfectly correlated. Individual unbiasedness is not required: estimators with a common nonzero bias can retain that bias while averaging reduces variance and mean squared error. Bagging trees exploits variation across resampled fits, and random forests add feature randomization. The size of the benefit depends on their bias, variance and dependence.
Boosting uses trees for the opposite reason. Shallow stumps have high bias and low variance, and fitting them sequentially against the residuals drives the bias down. Same base learner, opposite deficiency being addressed.
Where a single tree still earns its place is where the flowchart itself is the deliverable โ a clinical rule to be applied by hand, a policy to be audited line by line. There, keep it shallow, prune it, and report how much it changes under resampling rather than presenting one fit as the answer.
An ensemble can reduce variation by averaging trees, without requiring every tree to be an unbiased estimator.
References
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
