Decision Trees and Random Forests


Decision Trees and Random Forests

Michael
Today we’re looking at two related machine-learning methods: decision trees and random forests. We’ll begin with decision trees, using a classification example to see how a tree is built and how it makes predictions.

Simon
And the same general tree idea can also be used for regression, right?

Michael
Exactly. In classification, the goal is to assign an example to one of a set of predefined classes. In regression, the goal is to predict a target value. A decision tree can handle either kind of task, though the metric used to build it depends on the problem.

Simon
So what does the tree actually look like?

Michael
It starts at a root node containing the training data. At each decision node, the tree checks a feature and sends the example down one branch or another. Eventually it reaches a leaf, where it gives a classification or a predicted value. Different algorithms and software packages offer different ways to choose the splits.

Simon
And the metric helps the algorithm decide how to make those splits?

Michael
Right. Metrics provide a procedure for growing the tree from the data. For classification, common choices include Gini impurity and information entropy. For regression, variance reduction is commonly used. We’ll focus on Gini impurity, but the broader idea—measuring how useful a split is—carries over.

Simon
Let’s make it concrete with the Iris data.

Michael
The task is to classify an Iris flower as setosa, versicolor, or virginica. For each flower, the data includes four measured features: sepal length, sepal width, petal length, and petal width. In this example there are 149 labelled training samples: 49 setosa, 50 versicolor, and 50 virginica.

Simon
Those labels are what the model learns from, and the measurements are what it uses to make a prediction for a new flower.

Michael
That’s it. Looking at feature ranges can already give us clues. For example, the lecture notes that setosa petal lengths range from about 1 to 1.9, while versicolor ranges from about 3 to 5.1 and virginica from about 4.5 to 6.9. Those last two ranges overlap, but setosa is separated from them by a gap.

Simon
Before building a tree, what would happen if we just used the root node and made no split at all?

Michael
The root contains all 149 samples. If we had to predict one class for every new flower without using its features, we’d choose a most common class. Versicolor and virginica are tied at 50 each, so we could break that tie arbitrarily. Predicting one class for every sample would get only 50 of these 149 training examples right, which is not useful.

Simon
So the point of growing the tree is to use the features to make more informative groups.

Michael
Yes. A node represents a collection of data points. A split partitions that collection into child nodes, ideally making each child more concentrated in one class. A perfectly pure leaf contains examples from only one class, so it can give that class as its prediction.

Simon
That sounds like the ideal case, but you can’t always separate every class perfectly.

Michael
Correct. Whether a clean separation is possible depends on the data. And even when a tree can perfectly classify the training set, that may mean it has learned the training examples too closely. A very complex tree can generalize poorly to new examples, so some training errors may be worth accepting.

Simon
Let’s unpack the Gini measure. What does it calculate?

Michael
For a node, let each class fraction be the number of samples from that class divided by the total samples in the node. Gini impurity is one minus the sum of the squared class fractions: one minus the sum of f-sub-i squared. It is zero when all the samples in the node belong to one class.

Simon
What would that be at the root of our Iris example?

Michael
The three class fractions are 49 over 149, 50 over 149, and 50 over 149. So the root’s Gini impurity is one minus each of those fractions squared, added together. It’s about 0.666, indicating that the root contains a mixture of classes rather than a pure group.

Simon
And for a leaf containing only the 49 setosa samples?

Michael
Its class fractions are 1, 0, and 0. The Gini impurity is therefore one minus one squared, which is zero. That’s a pure node. The tree-building goal is to keep reducing impurity as we split, ideally producing pure leaves when the data allows it.

Simon
How does the tree decide which feature and threshold to use?

Michael
A candidate split might say, for example, ‘if petal length is less than a particular value, go left; otherwise, go right.’ The algorithm checks candidate features and thresholds, measures how the resulting children are distributed across classes, and selects a useful split. The software automates the search, but understanding the score helps us interpret the resulting tree.

Simon
What’s the score for a split?

Michael
One way to describe it is the parent node’s impurity minus the weighted impurities of its children. Each child’s impurity is weighted by the fraction of the parent’s samples that went into that child. A good split leaves the children with low impurity, so it produces a large reduction in impurity.

Simon
So if a split made both children pure, their impurities would be zero, and the reduction would be as large as possible.

Michael
Exactly. In the lecture’s terminology, this improvement is called the Gini split index. When comparing candidate splits, choose the one with the largest index—that is, the one that reduces impurity the most. Algorithms may search through many possible feature-threshold combinations to find a strong option.

Simon
Can we walk through the petal-length example?

Michael
Suppose we split at 2.4: petal length below 2.4 goes to one child, and the other values go to the other child. In this training set, the first child contains all 49 setosa samples, so it is pure. The second child contains the 50 versicolor and 50 virginica samples, so it is still mixed.

Simon
Then the first child has Gini impurity zero, and the second child has equal class fractions—one half and one half—so its impurity is 0.5.

Michael
Right. The split score weights those child impurities by their sizes: 49 out of 149 for the pure child and 100 out of 149 for the mixed child. Subtracting that weighted child impurity from the root impurity gives about 0.324. That number tells us how much this candidate split improves on leaving all the data together.

Simon
The example also tries a sepal-length threshold, doesn’t it?

Michael
Yes. Suppose we use sepal length at 5.8. That creates two groups with different class mixtures, and the lecture gives a Gini split index of about 0.1915 for that candidate. Compared with the petal-length split’s roughly 0.324, petal length at 2.4 is the stronger of those two examples because it gives a larger reduction in impurity.

Simon
Once the first split is made, does the algorithm keep splitting every child?

Michael
It considers each child in turn. A pure child, such as the setosa group in our petal-length example, needs no further split for classification. The mixed child may be split again, perhaps using another feature and threshold, to separate versicolor from virginica as much as possible.

Simon
In the lecture’s illustrative next step, the remaining 100 samples are split using petal width at 1.8.

Michael
Right. The example places about 54 samples on one side and 46 on the other. Each child gets a class label based on whichever class is most common there. A node’s label is the majority class among its samples; it doesn’t mean every sample in that node belongs to that class.

Simon
That distinction matters, because a leaf can still make mistakes even after the tree has been built.

Michael
Exactly. In the illustrative tree, a new flower first gets checked against the petal-length threshold of 2.4. If it falls on the setosa side, the tree predicts setosa. Otherwise, it checks petal width against 1.8, using that result to choose between the versicolor and virginica leaves. The tree follows the feature tests from the root until it reaches a leaf.

Simon
And to find out how well that works on unseen data, we evaluate it on a test set.

Michael
Yes. Training performance alone is not enough. Some training examples may be misclassified, and we need test data to assess how often the tree predicts correctly on examples it did not train on. If a leaf is still mixed, we could try more features and splits, but that might make the tree unnecessarily deep and reduce its ability to generalize.

Simon
So tree growth involves a balance: make useful partitions, but don’t keep splitting just to memorize the training examples.

Michael
That’s the key idea. The same general approach applies to regression trees: a node holds data, splits divide it into smaller groups, and the model predicts a target value at a leaf. The metric changes—variance reduction is used for regression—but the idea of building a useful sequence of feature-based decisions remains.

Simon
Now let’s connect that to random forests. Why not just rely on one decision tree?

Michael
A decision tree can be sensitive to changes or errors in the data: a small change may lead to different splits and a noticeably different tree. A random forest addresses this by combining multiple trees rather than depending on just one.

Simon
How does it create those different trees from the same original data?

Michael
It makes multiple modified versions of the data. For example, it can use different subsets of the data points, different subsets of the features, or both. Then it builds a decision tree for each version. Ten such data versions could produce ten trees, which together make up a random forest.

Simon
And when a new flower comes in, each tree gets to vote?

Michael
That’s the idea. Send the new example through each tree, then use the majority prediction as the forest’s classification. If three trees predict setosa, for instance, the forest predicts setosa. If two vote setosa and one votes virginica, setosa still wins. If the votes tie, a method is needed to break the tie.

Simon
The trees may use different features, so each one can arrive at its answer in a different way.

Michael
Exactly. One tree might use sepal length, sepal width, and petal length; another might use only sepal length and petal length. Different subsets of examples can also lead to different trees. Combining their votes makes the final result less dependent on any single tree’s particular splits.

Simon
So the forest’s advantage is that a collection of trees can be more robust to fluctuations in the data than one tree by itself.

Michael
That’s the motivation. If the trees tend to agree, their majority decision is the forest’s answer. The practical tools build the trees and combine their predictions for you; the important part is knowing how to read a decision tree, how a split improves class purity, and how a random forest combines multiple trees.

Ask anything
We've read this whole study set, so questions about it get the best answers.