Decision Trees
A model that asks a series of questions about the features until it reaches a decision, with impurity measures and pruning.
How does it work?
The tree starts with all the data at the root, then searches for the feature and threshold that split the data into two purer groups, and repeats this in each branch until a stopping condition is met.
Impurity measures
For a node with class proportions \(p_k\):
$$\text{Gini} = 1 – \sum_k p_k^2 \qquad\qquad \text{Entropy} = -\sum_k p_k \log_2 p_k$$
We choose the split that gives the largest decrease in impurity, weighted by the number of examples in each branch.
Example
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, export_text
iris = load_iris()
tree = DecisionTreeClassifier(max_depth=3, random_state=0)
tree.fit(iris.data, iris.target)
print(export_text(tree, feature_names=list(iris.feature_names)))displays the rules in a readable form.
Controlling complexity
max_depth: the maximum depth.min_samples_leaf: the minimum number of examples in a leaf.ccp_alpha: cost-complexity pruning.
Choose these values by cross-validation.
Pros and cons
| Advantages | Drawbacks |
|---|---|
| Easy to interpret and present | High variance: a small change in the data may change the tree a lot |
| Does not need feature scaling | Tends to overfit |
| Handles non-linear relations and interactions | Its decision boundaries are perpendicular to the axes |
High variance is treated by ensembling many trees, which is the topic of the next lesson.
Lesson terms
- Pruning
- Shrinking the tree by removing branches that do not improve generalization, to reduce overfitting.
- Decision tree
- A tree-shaped model in which each internal node is a test on a feature and each leaf carries a prediction.
- Gini index
- A measure of node impurity equal to the probability of misclassifying a random element if it is classified according to the class distribution in the node.
Abstract
A decision tree splits the feature space successively with simple conditions such as (feature ≤ value), and at each node it chooses the split that reduces impurity (Gini or entropy for classification, variance for regression). It is easy to interpret and does not need feature scaling, but it tends to overfit unless its depth is limited or it is pruned.
Review questions
-
Why don't decision trees need feature scaling?
Because a split depends on the order of the values relative to a threshold, not on distances or magnitudes.
-
What is the effect of increasing max_depth?
A more complex tree that fits the training data more closely, with a greater risk of overfitting.
Sources and references
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate