AI from scratch · Model zoo 5 of 10 · Decision trees
Decision trees
Chapter 13 showed how a tree picks a question (the split that leaves the purest boxes) and why trees run flat past the data. This page is about the tree as a model you'd actually use or reject: how to read one, how to stop it growing, and its big flaw, which the next two pages are built to fix: a tree is unstable. Change a few rows and you can get a completely different tree.
1. The idea in one picture: boxes, drawn by questions
Each line on the map is one question ("is x < 0.31?"), drawn only inside the box where it's asked. Deeper trees cut smaller boxes; smallest leaf refuses to make boxes with fewer training dots than that. Then press resample: the tree is regrown on a new bootstrap sample (200 dots drawn with replacement from the same 200), almost the same data.
Set depth 12 and press resample a few times. Predict first: what changes more, the training accuracy or the map?
- The training accuracy
- The map: islands appear and vanish
- Neither: same data, same tree
A tree cuts the data into boxes with yes/no questions and predicts each box's average; deep trees fit their sample so closely that a slightly different sample gives a different tree.
2. How it learns: greedy, one question at a time
CART (the algorithm in scikit-learn) starts with all rows in one box, tries every column and every cut, keeps the one that lowers impurity the most (Gini for classes, squared error for numbers), then repeats inside each half. It never goes back to revise a question. That greed is what makes trees fast (sorting each column once), and it's also why they're unstable: two cuts with nearly the same score at the top can send the whole tree down different paths.
\[ \text{best split: the column and cut with the smallest } \frac{n_L}{n} G_L + \frac{n_R}{n} G_R \]
Why small changes at the top change everything below
- At the root, the best and second-best cuts often score almost the same: two columns that both separate the classes about as well (on the bank calls, several economy columns move together).
- A handful of rows can swap which one wins. Greedy search takes the winner and never compares the trees that would have grown from the runner-up.
- Every later question is asked inside the boxes the root made, so a different root means different boxes, different data in each, and different questions all the way down.
- The deeper the tree, the fewer rows each question sees, so its winner is decided by fewer, noisier rows: the instability grows with depth. Measured on 20 resamples of the bank calls, the predicted chance for the same call varies by 0.026 on average at depth 3 and 0.22 when the tree grows until every leaf is pure.
- That noise is mostly independent from tree to tree, which is why averaging many trees (page 6) cancels much of it: twenty unpruned trees averaged score AUC 0.73 against one tree's 0.60.
3. Reading a tree
The thing trees do that nothing else in the zoo does: you can print the model. Here is a depth-2 tree on the bank calls (scikit-learn's export_text):
|--- nr.employed <= 5087.65 | |--- pdays <= 15.50 | | |--- class: yes | |--- pdays > 15.50 | | |--- class: no |--- nr.employed > 5087.65 | |--- cons.conf.idx <= -46.65 | | |--- class: no | |--- cons.conf.idx > -46.65 | | |--- class: no
In words: when the economy's employment figure was low (44% of those calls ended in a yes, against 7% of the rest) and the customer had been contacted within the last two weeks, predict yes; otherwise no. A banker can check that against experience, an auditor can see that no forbidden column is used, and anyone can apply it by hand. The right half asks a question whose two answers are both "no": it lowered impurity, so the greedy search took it, even though it changes no decision.
A tree splits on pdays at 15.5, but 96% of customers have pdays = 999 ("never contacted before"). Does that weird 999 need fixing before a tree can use it?
- No: a tree only asks "below or above a cut", so 999 is simply "above everything"
- Yes, it distorts the model badly
- Yes, trees can't handle outliers
4. Build it: CART from scratch in NumPy
Mine stops a box from splitting when it's smaller than twice the smallest leaf, while scikit-learn checks each child, so the trees can differ a little deep down.
5. Where it shines, where it breaks
Shines: readable rules, no scaling, any mix of numbers and categories, interactions found by itself ("only when employment was low and recently contacted"), and fast to train and to predict. A shallow tree is a fine explanation of a dataset even when it's not the model you ship.
Breaks: as a predictor on its own, a single tree is rarely the best. Grown fully on the bank calls it has 1,112 leaves and a test AUC of 0.62, barely better than chance; two full trees grown on the two halves of the training data disagree on 18.8% of the test calls. Limiting it helps a lot:
| Tree on the bank calls | Leaves | Test AUC |
|---|---|---|
| grown until pure | 1,112 | 0.62 |
| smallest leaf 50 calls | 109 | 0.76 |
| smallest leaf 200 calls | 29 | 0.77 |
| pruned (cost-complexity α = 0.001, chosen on validation) | 11 | 0.77 |
| for comparison: logistic regression (page 2) | 0.78 |
Pruning took a tree from 746 leaves to 11, and the test AUC went from 0.60 to 0.77. Why can removing most of a model make it better?
- The pruned tree fits the training data better
- Smaller models are faster, so they score higher
- Most of those leaves held a few calls each, and their answers were noise from this sample
A tree is the most readable model in the zoo and a weak predictor on its own; limit its depth or leaf size, or prune it, and expect it to change when the data does.
Where it breaks, and what people do
- Instability. Different samples, different trees. Don't read too much into one tree's exact questions; check whether they survive resampling. To predict, average many trees (random forests, page 6) or chain them (boosting, page 7).
- Overgrowth. Left alone it splits until every leaf is pure (chapter 13's "Why Gini" box): 100% on training, noise on test. Use
max_depth,min_samples_leaforccp_alpha, chosen on validation data. - Staircases. Diagonal edges and smooth trends need many cuts (chapter 13); a column like \(x - y\) or a linear model handles them in one.
- Flat outside the data. A leaf predicts an average of training rows, so beyond them it goes flat (page 1 measured what that means for a trend).
- Imbalance. With 11% yes, many leaves are "mostly no", and a depth-2 tree predicts "no" in three of its four boxes. Use the leaf shares as scores (
predict_proba) and choose a threshold, or setclass_weight.
6. The knobs that matter
| Knob | In scikit-learn | What it does |
|---|---|---|
| Depth | max_depth | The simplest limit. 3 to 5 for a tree to read; deeper only inside forests and boosting. |
| Leaf size | min_samples_leaf | Every leaf's answer is an average over at least this many rows, so it can't be one noisy row. Often the best single knob. |
| Pruning | ccp_alpha | Grow fully, then cut back every split that doesn't pay its cost α; pick α on validation data (cost_complexity_pruning_path lists the candidates). |
| Impurity | criterion (gini, entropy, log_loss) | Rarely matters; entropy is P5's information gain. |
| Class weights | class_weight | Makes rare classes count more when choosing splits. |
Next in the zoo: hundreds of unstable trees, averaged into one of the most reliable models there is.
All chapters: AI from scratch. Bank marketing: Moro, Cortez and Rita (2014), UCI Machine Learning Repository, CC BY 4.0.
Last updated