Sub topic 1
Anatomy of a decision tree
A decision tree predicts by asking a chain of simple questions about an input. Each answer sends the input down one branch, until it reaches a final answer. This chapter covers the parts of a tree, how a prediction travels through it, what a fitted tree stores, and the geometry it produces. Later chapters cover how the tree is built.
Prerequisites
This chapter assumes you have:
- Basic Python, enough to read short scripts and loops.
- The supervised learning vocabulary: features (inputs), labels (targets), and the split into training and test sets.
- The difference between classification (predict a category) and regression (predict a number).
- Basic probability and averages, such as class proportions and means.
You need scikit-learn and NumPy installed to run the example.
The parts of a tree
A decision tree is a rooted, directed structure with no cycles. Data enters at the top and flows downward. It has four kinds of parts:
- Root node: the first node. Every sample starts here, and it holds the whole training set.
- Internal node (also called a decision node or split node): holds a test on one feature, such as
petal length <= 2.45. It has exactly two children in the binary trees that scikit-learn builds. - Branch: the connection from an internal node to a child. Each branch corresponds to one outcome of the test, true or false.
- Leaf node (also called a terminal node): has no children. It holds the prediction.
Two measurements describe the overall shape:
- Depth of a node is the number of branches between it and the root. The root has depth 0. The depth of the tree is the depth of its deepest leaf.
- Size is usually counted as the number of leaves or the total number of nodes. In a binary tree where every internal node has two children, a tree with L leaves has L − 1 internal nodes and 2L − 1 nodes in total.
The diagram shows a small classification tree for the iris flower data.
Tracing a prediction
To predict, start at the root and repeat these steps:
- If the current node is a leaf, return its prediction.
- Otherwise evaluate the node's test on the sample's feature value.
- Follow the branch matching the outcome, and go back to step 1.
Take a flower with petal length 5.5 cm and petal width 2.0 cm. The root test petal length <= 2.45 is false, so you move to the right child. There petal width <= 1.75 is false, so you move right again. That node is a leaf labeled virginica, so the prediction is virginica.
Three properties follow from this procedure:
- The prediction cost is proportional to the depth of the tree, not to the size of the training set. Prediction is cheap.
- Each sample reaches exactly one leaf. The leaves partition the feature space: every possible input belongs to one leaf, and no input belongs to two.
- Only the features on the sample's path matter for its prediction. The other features are never read.
What each node stores
A fitted tree is more than its tests. Each node records facts about the training samples that reached it during fitting.
| Stored value | Meaning | Where it is used |
|---|---|---|
| Feature and threshold | The test at an internal node | Routing samples during prediction |
| Number of samples | How many training samples reached the node | Weighting splits, minimum-size rules, pruning |
| Impurity | How mixed the labels are at the node (Gini or entropy) | Choosing splits, importance scores |
| Class distribution | Label counts or proportions among those samples | Leaf prediction and probability estimates |
In a classification leaf, the prediction is the majority class among the training samples in that leaf. The class proportions also give a probability estimate. A leaf with 48 versicolor and 2 virginica predicts versicolor with an estimated probability of 0.96. In a regression leaf, the prediction is the mean of the training targets in that leaf, which a later chapter covers.
The class distribution is what makes a leaf meaningful. A leaf with three samples and one with three hundred can both predict "versicolor", but you should trust them very differently.
Inspecting a fitted tree in scikit-learn
The next script fits a small tree and walks one sample down it, using the arrays that scikit-learn exposes on tree_. The array tree_.children_left holds -1 for leaves. The helper decision_path returns the nodes a sample visits.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
data = load_iris()
clf = DecisionTreeClassifier(max_depth=2, random_state=0)
clf.fit(data.data, data.target)
tree = clf.tree_
print("nodes:", tree.node_count)
print("leaves:", clf.get_n_leaves())
print("depth:", clf.get_depth())
sample = data.data[[100]] # one flower, kept as a 2D array
path = clf.decision_path(sample).indices # node ids from root to leaf
for node in path:
n = tree.n_node_samples[node]
impurity = tree.impurity[node]
if tree.children_left[node] == -1:
label = data.target_names[np.argmax(tree.value[node][0])]
print(f"node {node}: LEAF, {n} samples, impurity {impurity:.3f}, predicts {label}")
else:
feature = tree.feature[node]
threshold = tree.threshold[node]
value = sample[0, feature]
direction = "left" if value <= threshold else "right"
print(
f"node {node}: {data.feature_names[feature]} = {value} "
f"vs {threshold:.2f} -> go {direction} "
f"({n} samples, impurity {impurity:.3f})"
)On this data the root typically tests petal length near 2.45 cm, and the second test uses petal width near 1.75 cm. A depth-2 tree has at most 3 internal nodes and 4 leaves. Here the left child of the root is already pure, so the tree stops there and ends up with 3 leaves and 5 nodes.
Note that tree.value holds raw class counts in older scikit-learn versions and class fractions in newer ones. Taking argmax works in both cases.
How tests are written
An internal node tests exactly one feature. The form of the test depends on the feature type:
- Numeric feature: a threshold test,
feature <= t. The tree pickstfrom the data, usually as a midpoint between two neighboring sorted values. Samples withfeature <= tgo left and the rest go right. - Binary feature: a threshold at 0.5 on a 0/1 column, which is the same as asking "is it 1?".
- Categorical feature: in theory a test can ask "is the category in this subset?". The scikit-learn tree classes do not support raw string categories. You must encode them first, usually with one-hot columns, and each one-hot column then becomes a yes/no test.
Because scikit-learn handles encoded categories as numbers, label-encoding a category with no natural order (red = 0, green = 1, blue = 2) lets the tree split on color <= 1.5. That groups categories by arbitrary integer order. One-hot encoding avoids this, at the cost of more columns.
The geometry of a tree
Each test compares one feature to one threshold, so each split is a line perpendicular to a feature axis. The leaves therefore carve the feature space into rectangles, or boxes in higher dimensions. The prediction is constant inside each box. This is why decision boundaries of trees are axis-aligned and look like staircases.
This has practical consequences:
- A tree needs no feature scaling. Multiplying a feature by 100 only changes the thresholds, not which samples go left or right.
- A boundary that runs diagonally, such as
x1 > x2, needs many small steps to approximate. A linear model represents it with one weight vector. - Predictions are piecewise constant. A regression tree outputs a step function, never a smooth curve.
- Features can interact naturally. A test on feature B below a test on feature A applies only to samples that passed A, so the tree can express "B matters only when A is large".
Common mistakes
- Counting depth wrong. The root is depth 0. A tree with only a root and two leaves has depth 1.
- Reading
valueas probabilities in every version. Check your scikit-learn version, or usepredict_proba, which is always normalized. - Treating a leaf as certain. A pure leaf with 2 samples is weak evidence. Check
n_node_samples. - Passing a 1D array to
predictordecision_path. Scikit-learn expects shape(n_samples, n_features), so usedata.data[[100]]ordata.data[100].reshape(1, -1). - Assuming a left branch means a smaller class label. Left means only "test is true", that is,
feature <= threshold.
Exercise
A binary decision tree has 7 leaves, and every internal node has exactly two children. How many internal nodes and how many nodes in total does it have? What is the smallest depth it could have?
Show answer
With L leaves, there are L − 1 internal nodes, so 6 internal nodes and 13 nodes in total (2L − 1). The smallest depth comes from a balanced tree. A tree of depth 2 has at most 4 leaves and a tree of depth 3 has at most 8 leaves, so 7 leaves needs depth at least 3.
Exercise
A tree predicts "versicolor" at leaf A, which holds 50 training samples (49 versicolor, 1 virginica), and at leaf B, which holds 3 samples (2 versicolor, 1 virginica). Both leaves give the same class. Why should you trust them differently, and what does the tree output for the probability of versicolor at each?
Show answer
Leaf A estimates 49/50 = 0.98 from many samples, so the estimate is stable. Leaf B estimates 2/3 ≈ 0.67 from only three samples, so one different sample would change the estimate a lot. The sample count at each node shows how reliable its class proportions are.