Sub topic 1
Decision trees as the building block
A random forest is built from decision trees. This chapter covers what a decision tree is, how it makes predictions, how it is grown, and which properties of trees motivate the forest. Later chapters cover split criteria in detail, the bias and variance trade-off, and the forest itself.
Prerequisites
This chapter assumes you know the following:
- Basic supervised learning: features, labels, and the split into training and test sets.
- Python and NumPy basics, and the scikit-learn
fitandpredictpattern. - Classification and regression metrics such as accuracy and mean squared error.
- Basic probability and averaging.
What a decision tree is
A decision tree is a model that predicts by asking a sequence of yes/no questions about the features. Each question compares one feature with a threshold, for example "is mean radius at most 15.0?". The answers lead you down the tree until you reach a leaf, which holds the prediction.
A tree has three kinds of parts:
- The root node is the first question. Every sample starts here.
- Internal nodes each hold one question and have two children, one for "yes" and one for "no".
- Leaf nodes hold the output. For classification, a leaf stores the class counts of the training samples that ended up there, and the prediction is the majority class. For regression, a leaf stores the mean target value of those samples.
The tree is a set of nested rules. Each leaf corresponds to one rectangular region of feature space, and every sample that falls in that region gets the same prediction.
How a tree makes a prediction
Prediction is a walk from the root to a leaf. At each internal node you test one feature of the sample and follow the matching branch. The cost is proportional to the depth of the tree, not to the number of training samples, so prediction is fast.
Two properties follow from this:
- Trees need no feature scaling. Each question looks at a single feature and a threshold, so multiplying a feature by a constant only moves the threshold.
- Trees capture interactions. A leaf at depth three is reached by three conditions together, so the model can represent "A is large and B is small" without you building that feature.
How a tree is grown
Training builds the tree top-down with a greedy procedure called recursive partitioning:
- Start with all training samples at the root.
- For every candidate feature and every candidate threshold, compute how much the split would reduce the impurity of the child nodes compared with the parent. Impurity measures how mixed the labels are in a node.
- Choose the single split with the largest reduction.
- Send the samples to the left or right child according to the split, and repeat steps 2 and 3 on each child.
- Stop a branch when a stopping rule applies and make it a leaf.
The method is greedy because it picks the best split for the current node only. It never looks ahead, so it can miss a combination of splits that would be better overall. Finding the optimal tree is computationally intractable, which is why every practical library uses this greedy approach.
The next chapter explains the impurity measures (Gini impurity, entropy, variance reduction). For now, treat impurity as a number that is zero when a node contains one class only and grows as the classes mix.
Candidate thresholds
For a numeric feature, the only thresholds worth testing are midpoints between consecutive distinct sorted values in the node. Any threshold between the same two neighbouring values sends the same samples left and right. With n samples and p features, a node therefore has at most about n * (p - 1)-scale candidate splits, and this search is what dominates training time.
Stopping rules
If you give a tree no limits, it keeps splitting until every leaf is pure, meaning it holds samples of one class only, or until it cannot split further because the remaining samples have identical feature values. You can stop earlier with these controls, which scikit-learn exposes as hyperparameters:
| Parameter | Effect |
|---|---|
| `max_depth` | Limits the number of questions between the root and any leaf. |
| `min_samples_split` | A node with fewer samples than this is not split. |
| `min_samples_leaf` | A split is rejected if it would leave a child with fewer samples than this. |
| `max_leaf_nodes` | Grows the tree until it has this many leaves. |
| `min_impurity_decrease` | Rejects splits that reduce impurity by less than this amount. |
A first tree in scikit-learn
The following program trains one tree with a depth limit and prints its rules as text. The export_text function shows the questions and the leaf class at each end.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
data.data, data.target, test_size=0.2, random_state=0, stratify=data.target
)
tree = DecisionTreeClassifier(max_depth=3, random_state=0)
tree.fit(X_train, y_train)
print(export_text(tree, feature_names=list(data.feature_names)))
print("Train accuracy:", tree.score(X_train, y_train))
print("Test accuracy: ", tree.score(X_test, y_test))
print("Depth:", tree.get_depth(), "Leaves:", tree.get_n_leaves())The printed rules read as nested if statements. You can follow any test sample through them by hand, which is the main reason trees are called interpretable.
Strengths of a single tree
- Mixed feature types are easy to handle, and scaling is unnecessary.
- The model can represent non-linear relationships and feature interactions.
- The fitted rules can be read and explained.
- Prediction is cheap.
Weaknesses that lead to the forest
Overfitting with deep trees
A tree with no depth limit can reach 100% training accuracy because it keeps splitting until each leaf is pure. In the extreme case it memorises the training set, noise included. Test accuracy is then lower than training accuracy. The following code shows the gap as depth grows.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
for depth in [1, 2, 3, 5, 8, None]:
tree = DecisionTreeClassifier(max_depth=depth, random_state=0)
tree.fit(X_train, y_train)
print(
f"max_depth={str(depth):<4} "
f"train={tree.score(X_train, y_train):.3f} "
f"test={tree.score(X_test, y_test):.3f}"
)Expect training accuracy to reach 1.000 once the depth is unrestricted, while test accuracy stays lower. The exact test numbers depend on the split.
Instability
Small changes in the training data can change an early split, and everything below that split changes with it. Two trees trained on slightly different samples of the same data can look very different and make different predictions on the same point. This is called high variance. A single tree is therefore an unreliable estimator, even though each tree has low bias when grown deep.
Axis-aligned boundaries
Every question uses one feature, so decision boundaries are made of segments parallel to the axes. A diagonal boundary, such as "A greater than B", needs many small steps to approximate. Linear models handle such boundaries with one coefficient pair.
No extrapolation
A regression tree predicts the mean of the training targets in a leaf. Outside the range of the training data it predicts a constant equal to the nearest leaf's value, so it cannot continue a trend.
Greedy choices
Because each split is chosen without looking ahead, the tree can be sub-optimal. Features that are only useful in combination, as in an XOR pattern, may show no gain on their own, so the greedy search may not find them early.
Common errors
- Evaluating on training data. A deep tree scores near perfect there, which says nothing about new data. Always report test or cross-validated scores.
- Fixing overfitting by tuning only
max_depth. Several controls interact. A tree withmin_samples_leaf=5may need a different depth than one without it. - Reading a tree as causal. A split on a feature shows association in the training data, not that changing the feature changes the outcome.
- Expecting a stable structure. If you refit on a different sample, the tree you explain to stakeholders may change.
- Passing category strings directly. Scikit-learn trees need numeric input, so encode categorical columns first.
Why this matters for random forests
A fully grown tree has low bias and high variance. It fits the training data closely but changes a lot when the data changes. A random forest keeps that property of deep trees, because deep trees are flexible, and then reduces the variance by averaging many trees trained on different resamples of the data. The chapters that follow explain each ingredient in turn: the split criteria, the bias and variance trade-off, bootstrap sampling, bagging, and random feature subsets.
Exercise
You train a DecisionTreeClassifier with no depth limit and get 1.00 accuracy on the training set but 0.91 on the test set. Name the problem, explain why the tree reaches 1.00 on the training set, and name two hyperparameters that would limit it.
Show answer
The tree is overfitting. With no limits it keeps splitting until every leaf is pure, so it can classify every training sample correctly, including noisy ones, and it does not generalise equally well. Hyperparameters that limit it include maxdepth, minsamplesleaf, minsamplessplit, maxleafnodes and minimpurity_decrease.
Exercise
Why is a decision tree's greedy split search not guaranteed to find the best possible tree?
Show answer
At each node it chooses the split that is best for that node alone and never revisits the choice. A split that looks weak now might enable much better splits below it, but the greedy search cannot see that. Finding the globally optimal tree is computationally intractable, so practical algorithms accept this limitation.