Skip to content

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.

Applied ~11 min8 steps

What runs in CodeSplash

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

Read first

01

Ask, split, repeat

Read

A 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.:

G=1−∑cpc2G = 1 - \sum_{c} p_c^2

A pure node has G=0G = 0. A 50/50 node has G=0.5G = 0.5. For numbers, it's squared error. Split criterion (classes) also offers entropy, and the two rarely differ much.

02

Grow one

Explore

Press 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?

8
How sure?

Data

3

Split criterion

1
0.25
120
  1. 1x₂ ≤ 0.03120 rowsimpurity −0.254
  2. 2x₁ ≤ 1.5777 rowsimpurity −0.126
  3. 3x₂ ≤ 0.4266 rowsimpurity −0.012

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

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.

03

Stop, or grow and prune

Read

Three 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 α=2\alpha = 2.

04

Why isn't it better?

Predict

Predict first

On penguins, LDA has a cross-validated log loss of 0.0242. How will a depth-4 tree compare?

About the same log lossMany times worseBetter, because trees capture interactions
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.

05

Reads better than it predicts

Read

On 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.

06

Check your understanding

Checkpoint

Check yourself

A node has 8 rows of one class and 2 of another. What is its Gini impurity?

Show the answer

Answer: 0.32

1−(0.82+0.22)=1−0.68=0.321 - (0.8^2 + 0.2^2) = 1 - 0.68 = 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.

07

Train a readable tree

In the app

In 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.

Python
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)))
R
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)
08

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