Decision trees
Greedy yes-or-no splits, read as a flowchart. Learn how a split is chosen, how to stop or prune, and why a lone tree predicts worse than it reads.
What runs in CodeSplash
- Decision tree (CART) Verified in Python and R
You will be able to
- Compute Gini impurity and pick a split
- Control tree size by depth, leaf size and pruning
- Explain why a single tree is unstable, and gives crude probabilities
Ask, split, repeat
ReadA decision treeDecision treeA flowchart of yes-or-no splits, each chosen greedily to reduce impurity most. starts with all rows. It tries every split on every feature, keeps the one that makes the two children purest, then repeats inside each child.
For classes, impurity is usually GiniGini impurityHow mixed a node is, as one minus the sum of squared class shares. Zero is pure.:
A pure node has . A 50/50 node has . For numbers, it's squared error. Split criterion (classes) also offers entropy, and the two rarely differ much.
Grow one
ExplorePress through Splits made. Each step lists the variable, threshold and the drop in impurity. Stop at the split count with the highest New-data accuracy. Then raise Smallest leaf until the tree can't make more than 6 splits.
DExplorable · Grow a decision tree
How does a tree choose its splits, and when should it stop?
Training accuracy keeps rising with every split. After how many splits will accuracy on new data stop improving?
Data
Split criterion
- 1x₂ ≤ 0.03120 rowsimpurity −0.254
- 2x₁ ≤ 1.5777 rowsimpurity −0.126
- 3x₂ ≤ 0.4266 rowsimpurity −0.012
Commit your prediction above to see the result
Make your prediction to see the result.
Splits are chosen greedily: each looks best now, not best overall. That's what makes it fast, and it's also why small changes in the data can change the whole tree.
Stop, or grow and prune
ReadThree ways to limit a tree:
- Maximum depth: levels of questions.
- Minimum rows per leaf: no decisions from a handful of rows.
- Pruning strength (α): grow big, then remove any branch that doesn't reduce error by α per extra leaf.
Pruning can keep a useful split that follows a weak one, where an early stop can't. On ozone, a pruned tree has RMSE 22.6 with unlimited depth and .
Why isn't it better?
PredictPredict first
On penguins, LDA has a cross-validated log loss of 0.0242. How will a depth-4 tree compare?
Reveal
Many times worse: 0.429. A leaf's probability is the share of its rows, so with small leaves it's often exactly 0 or 1. Log loss punishes a confident miss hard. Averaging many trees is what fixes that.
Reads better than it predicts
ReadOn Pima, a depth-6 tree scores 0.777, and a plain logistic model 0.857. A tree approximates smooth effects with stairs, and it spends rows quickly: each split halves what's left.
Its strengths are elsewhere. You can print it, check it against domain knowledge and export it: both engines run the same builder, so splits are identical, and a tree can be scored in SQL.
Check your understanding
CheckpointCheck yourself
A node has 8 rows of one class and 2 of another. What is its Gini impurity?
Show the answer
Answer: 0.32
.
Check yourself
You re-fit a tree on a slightly different sample, and its top split changes. What does that show?
Show the answer
Answer: a
Two splits can be nearly tied, and picking the other one changes everything below. This is what bagging exploits.
Check yourself
Which change gives a tree's probabilities fewer extreme values?
Show the answer
Answer: b
A leaf's probability is a share of its rows. Bigger leaves give less extreme shares, as they're less likely to be pure.
Train a readable tree
In the appIn the Learners step, select Decision tree (CART). Try a low Maximum depth first. The run's Explanations tab shows what it uses, and the Code tab has the full script. Train it next to a forest on the same folds to see what the readability costs.
import pandas as pd
from sklearn.tree import DecisionTreeClassifier, export_text
df = pd.read_csv("pima.csv")
X, y = df.drop(columns="diabetic"), df["diabetic"]
tree = DecisionTreeClassifier(max_depth=3, min_samples_leaf=20, random_state=1).fit(X, y)
print(export_text(tree, feature_names=list(X.columns)))library(rpart)
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
fit <- rpart(type ~ ., df, control = rpart.control(maxdepth = 3, minbucket = 20, cp = 0))
print(fit)Recap
Recap- A tree greedily chooses the split that most reduces impurity, and keeps going.
- Depth, leaf size and pruning all limit its flexibility.
- It's easy to read and to export, but it's unstable, and its probabilities are crude.
Concepts in this lesson