Decision Trees Explained Step by Step
A decision tree is a model that makes predictions by asking a series of simple questions. It looks like a flowchart: start at the top, answer a question about the data, follow the matching branch, and keep going until you reach an answer.
Part of their appeal is that people can read them. You can often trace exactly why a tree made a given prediction, which is not true of many other machine learning models.
The parts of a tree
A tree has a few named pieces.
- Root node: the first question, at the top.
- Internal nodes: further questions that split the data.
- Branches: the possible answers to a question, leading down to the next node.
- Leaf nodes: the end points, where the tree gives its prediction.
Trees can be used for classification, where a leaf gives a category such as "approved" or "rejected," and for regression, where a leaf gives a number such as the average value of the examples that reach it.
A tiny worked example
Suppose you want to predict whether someone will go for a walk, using weather data. A small tree might look like this:
- Is it raining? If yes, predict "no walk."
- If not, is the temperature above freezing? If no, predict "no walk."
- If yes, predict "walk."
To predict for a new day, you answer each question in turn. The path from top to leaf is the explanation. Real trees have more questions and more features, but the logic is the same.
How a tree is built from data
The tree is learned from labeled examples. The central idea is to choose, at each step, the question that best separates the data into purer groups.
The process goes like this:
- Start with all training examples at the root.
- Consider many possible questions, such as "is age greater than 30" or "is color red."
- Score each question by how much it improves the separation of classes.
- Pick the best question and split the data into subgroups.
- Repeat the process on each subgroup.
- Stop when a stopping rule is met, and turn that node into a leaf.
This approach is greedy. It picks the best question at each step without looking ahead, which is fast but does not guarantee the best possible tree overall.
Measuring how good a split is
To compare questions, you need a measure of how mixed a group is. This is called impurity.
Gini impurity measures how often a randomly chosen example from the group would be mislabeled if labeled according to the group's class mix. A group containing only one class has zero impurity.
Entropy comes from information theory. It is zero for a pure group and highest when classes are evenly mixed. The improvement from a split is called information gain: the drop in entropy from before the split to after it.
For regression trees, the usual measure is the variance or squared error of the target values within each group. A good split makes the values in each group close to their average.
In practice, Gini and entropy often produce very similar trees.
What the code looks like
Libraries make this short. Here is a classifier using scikit-learn:
from sklearn.tree import DecisionTreeClassifier, export_text
tree = DecisionTreeClassifier(max_depth=3, random_state=0)
tree.fit(X_train, y_train)
print(export_text(tree, feature_names=list(X_train.columns)))
print(tree.score(X_val, y_val))
The export_text call prints the rules, so you can read the tree directly.
Growing too deep: overfitting
Left unchecked, a tree keeps splitting until every leaf is perfectly pure, possibly with one example each. That tree memorizes the training data, including its noise, and does poorly on new data.
To control this, you can:
- Limit the depth of the tree.
- Require a minimum number of examples to split a node or to form a leaf.
- Prune the tree afterward, removing branches that add little value.
- Set a minimum improvement a split must achieve.
These settings are hyperparameters and are best chosen with a validation set or cross-validation.
Strengths of decision trees
- Easy to interpret. The rules can be shown to non-specialists.
- Little preparation needed. They do not require feature scaling, and many can handle a mix of numeric and categorical features.
- They capture non-linear patterns and interactions between features without extra work.
- Fast to train and to predict on moderate data.
Weaknesses to know about
- Instability. A small change in the data can produce a very different tree.
- Overfitting when not constrained.
- Axis-aligned splits only. Standard trees cut along one feature at a time, which approximates diagonal boundaries awkwardly.
- Bias toward features with many distinct values in some implementations.
From one tree to many
The weaknesses of single trees led to ensemble methods that combine many trees. A random forest trains many trees on random samples of the data and features, then averages or votes on their predictions, which reduces variance. Gradient boosting builds trees one after another, with each new tree correcting the errors of the previous ones. These methods are often highly accurate on tabular data, though they give up some of the easy readability of a single tree.
Frequently Asked Questions
Can decision trees handle both numbers and categories?
Yes. Trees can split on numeric thresholds, such as age above 30, and on categories. Some library implementations require categories to be converted to numbers first, so check the documentation of the tool you use.
Why do decision trees overfit so easily?
Because they can keep splitting until they fit every training example, noise included. Limiting depth, requiring a minimum leaf size or pruning keeps the tree general enough to work on new data.
Is a random forest the same as a decision tree?
No. A random forest is a collection of many decision trees, each trained on a different random sample, whose predictions are combined. It is usually more accurate and stable than a single tree, but harder to interpret.