SeeingML
Core ML Models Guide 2 of 6 · tap to switch
✦ Interactive Visual Guide 9 min · 4 hands-on labs · Beginner friendly

Decision Trees & Split Impurity

Turn messy tables into crystal-clear flowcharts of yes/no questions, understand Gini Impurity vs. Entropy, and see why pruning stops overfitted boxes.

Think of how a veteran bank officer reviews small-business loan applications. They do not calculate a complicated weighted formula in their head. They follow a crisp mental checklist: First, is the Credit Score at least 635? If yes, is Annual Income above £45k?

A Decision Tree discovers that exact checklist automatically from past data. At every step, it draws one straight vertical or horizontal fence through your scatter plot, trying to separate Approved loans cleanly from Rejected loans so each new bucket is as pure (single-color) as possible.

To measure how mixed a bucket is, the tree scores Bucket Messiness (Gini Impurity): 0.00 means a completely pure bucket where every borrower belongs to the same class, while 0.50 is the messiest possible 50/50 split. At every step, the tree checks every candidate fence and picks whichever cut drops messiness the most!

Switch between Credit Score and Annual Income below, slide the decision fence, and watch Purity Gain (Gini Impurity Reduction) climb to its peak!

Interactive Lab 1: Slide a Decision Fence & Maximize Purity Gain
Approved LoanRejected LoanActive Fence
Credit best: +0.181Income best: +0.206 (Winner)
500575650725800£20k£40k£60k£80k£100kCredit ScoreAnnual Income
Left Bucket (< 585) (5)
1 Approved · 4 Rejected
Messiness (Gini = 0.320 · 0 is pure)
Right Bucket (>= 585) (19)
11 Approved · 8 Rejected
Messiness (Gini = 0.487 · 0 is pure)
Purity Gain (Messiness Drop)
+0.047
Weighted Gini: 0.50 to 0.453
Slide the fence or click "Snap to Purest Split". A decision tree checks every cutoff on every column and picks whichever single fence drops bucket messiness the most.

Notice a massive everyday superpower of Decision Trees: they do not care about feature scaling! Whether Annual Income is written in pounds (£46,000) or thousands (46), multiplying Income by 1,000 simply shifts the cutoff number along with the units while separating the exact same borrowers.


How a Decision Tree Grows: Splits, Depth & Overfitting

Once the first question splits the room in two, the tree repeats the exact same trick inside each new bucket (called recursive binary splitting). When a bucket stops splitting, it becomes a leaf: a final answer box at the bottom of the tree that votes Approved or Rejected for every borrower who lands inside it.

One question gives a blunt Decision Stump (Depth 1, just 2 leaves). Two levels carve clean, sensible approval rules. What happens if you let the tree keep growing to Depth 6? Click through the depths below and watch both Training Accuracy (filled circles) and Unseen Test Accuracy (hollow diamonds)!

Interactive Lab 2: Growing Tree Depth & Watching Overfit Boxes Appear
Filled = PracticeHollow = Unseen TestCoral Ring = Missed Test
2 unseen test errors ringed
500575650725800£20k£40k£60k£80k£100kCredit ScoreAnnual Income
Leaf Boxes
2
Train Accuracy
79% (19/24)
Unseen Test
83% (10/12)
Depth 1 (Decision Stump): asks only 1 straight question ("Annual Income >= £46k?"). Too blunt: 2 unseen test diamonds fail (ringed in coral) because high-income applicants with poor credit get approved by mistake (Underfitting).

Look closely at Depth 6: it hits 100% on the Training circles by carving tiny surgical trap boxes around the two noisy outlier applicants, immediately misclassifying unseen Test diamonds sitting nearby (ringed in coral). That is why production trees always use simple depth brakes to stop overfitting:

  • Max Depth: Cap how many follow-up questions the flowchart is allowed to ask from top to bottom.
  • Minimum Rows per Box: Refuse to create a final leaf unless it holds enough borrowers to represent a real pattern rather than a single noisy outlier.
  • Pruning weak branches: Grow the tree first, then trim back extra branches whose tiny purity gain does not justify the added complexity (formally called cost-complexity pruning).

Gini Impurity vs. Shannon Entropy: does it matter?

Picture a bucket of loan applicants as a jar of green (Approved) and coral (Rejected) marbles. Standard decision trees offer two classic ways to score how mixed that jar is, and both give 0.00 when every marble is the same color and hit their peak at an even 50/50 mix:

  • Gini Impurity asks: If you grab two marbles at random, how likely are they to be different colors?
  • Shannon Entropy asks: How many yes/no guesses would it take to figure out the color of a marble you pull blindly from the jar?

Drag the bucket mix slider below to see the marble jar shift from pure to 50/50 and watch both curves side by side, along with half-Entropy drawn as a dashed line.

Interactive Lab 3: Gini Impurity vs. Shannon Entropy (Same Shape!)
Gini: 0.500 · Entropy: 1.000
20-Marble Bucket Mix Jar: 10 Approved · 10 Rejected
Max Mess (50/50 Mix)
Shannon Entropy (0 to 1.00)Half-Entropy (dashed)Gini Impurity (0 to 0.50)0.000.250.500.751.000%25%50%75%100%Share of Green ApprovalsMessiness Score
Gini 0.500 · Half-Entropy 0.500
Maximum messiness (near 50/50 coin flip)! With an even mix of green and coral marbles, both Gini Impurity (0.50) and Shannon Entropy (1.00) peak right at the center.

Because their curves share practically the identical arch shape, Gini Impurity and Shannon Entropy choose the exact same split roughly 98% of the time. Standard decision trees default to Gini simply because squaring simple fractions runs faster than calculating Entropy’s curved surprise scores, so switching between them rarely moves your accuracy.


The two blind spots of a single Decision Tree

Decision Trees are fast, readable by non-technical stakeholders, and completely unfazed by feature units: multiply Annual Income by 1,000 and the cutoff simply shifts along with the units without changing a single split. So why do Kaggle winners and production teams almost never ship a single tree?

Explore both weaknesses below. First is Instability (high sensitivity to tiny data tweaks, which ML practitioners call high variance): because every deeper branch depends on the very first question, changing just a few borderline rows can flip the whole tree from the root down. Second is the Staircase Trap: whenever a real-world rule tilts diagonally, straight horizontal and vertical fences force clunky jagged steps.

Interactive Lab 4: Two Weaknesses of a Single Decision Tree
First Question: Annual Income < £46k? (Horizontal Cut)
ApprovedRejectedAmber Ring = 3 Borderline Rows to TweakRoot Cut
500575650725800£20k£40k£60k£80k£100kCredit ScoreAnnual Income
A single decision tree builds its flowchart greedily from the top down. Click "Tweak Just 3 Borderline Loans" above to flip the 3 amber-ringed dots in the bottom right and watch the entire root fence jump!
See CART Impurity Objectives, Regression MSE & Cost-Complexity PruningThesis / Reference

1. Classification Impurity Criteria (Breiman et al., 1984): For a node mm containing CC classes with empirical proportions pm,kp_{m,k}, Gini Impurity measures the probability of misclassifying a randomly chosen element if labeled according to the node’s class distribution, while Shannon Entropy measures expected surprise in bits:

G(m)=1−∑k=1Cpm,k2,H(m)=−∑k=1Cpm,klog⁡2pm,kG(m) = 1 - \sum_{k=1}^{C} p_{m,k}^2, \qquad H(m) = -\sum_{k=1}^{C} p_{m,k} \log_2 p_{m,k}

At each step, CART picks the feature jj and threshold tt minimizing the sample-weighted child impurity (equivalently maximizing Impurity Reduction / Information Gain):

ΔI(m;j,t)=I(m)−nLnm I(mL)−nRnm I(mR)\Delta I(m; j, t) = I(m) - \frac{n_L}{n_m}\,I(m_L) - \frac{n_R}{n_m}\,I(m_R)

2. Regression Trees: For continuous targets y∈Ry \in \mathbb{R}, CART replaces Gini with within-node Mean Squared Error (Variance) around each child mean yˉL,yˉR\bar{y}_L, \bar{y}_R, outputting the piecewise-constant leaf average y^(x)=yˉm\hat{y}(x) = \bar{y}_m.

3. Minimal Cost-Complexity Pruning (Weakest-Link Pruning): Finding the globally optimal binary tree is NP-complete (Hyafil & Rivest, 1976), so CART grows greedily and prunes back by minimizing penalized empirical risk across subtrees TT with ∣T∣|T| terminal leaves:

Rα(T)=R(T)+α ∣T∣R_\alpha(T) = R(T) + \alpha\,|T|

Larger α≥0\alpha \ge 0 (ccp_alpha in scikit-learn) collapses leaves whose impurity reduction fails to justify an extra split, directly trading tiny training gains for dramatic test-set stability.

See Pruned Decision Tree in Python (No Scaler Needed!)Optional Code
python
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.model_selection import cross_val_score

# Notice: NO StandardScaler needed because trees split purely on rank thresholds!
tree = DecisionTreeClassifier(
  criterion="gini",
  max_depth=3,          # prevents deep memorization boxes
  min_samples_leaf=5,   # ensures every leaf represents real volume
  ccp_alpha=0.01,       # cost-complexity pruning penalty
  random_state=42,
)
tree.fit(X_train, y_train)

print("5-fold CV accuracy:", cross_val_score(tree, X_train, y_train, cv=5).mean().round(3))
print(export_text(tree, feature_names=["credit_score", "annual_income"]))

How do we cure a single tree’s jitteriness?

You just saw a single tree swing wildly when 3 borderline rows changed. Imagine instead growing 100 slightly different trees on random slices of your data and features, and letting the whole forest vote together.

Next up: Random Forests.

✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

A leaf box contains 20 Approved loans and 0 Rejected loans. What are its Gini Impurity and Shannon Entropy?

Pick an option first, or peek anytime
2

Your unlimited Decision Tree hits 100% Training accuracy with 42 tiny leaves, yet drops to 76% on unseen Test data. Which action directly cures this?

Pick an option first, or peek anytime
3

A Decision Tree breaks if you multiply Annual Income by 1,000 (turning £45k into 45,000) without rescaling it to match Credit Score.

Pick an option first, or peek anytime
4

You tweak just 3% of your training rows and refit a single Decision Tree. The very first root question changes completely and predictions shift across the whole map. What weakness did you just witness?

Pick an option first, or peek anytime
Quick Reference

Common Questions

What is a decision tree in machine learning?
A decision tree is a supervised learning model that predicts a label or number by asking a sequence of yes/no threshold questions (like 'Credit Score >= 680?'), splitting the feature space into progressively purer boxes.
How do you build a decision tree step by step?
Start with all training rows at the root node, test every candidate feature threshold to find the single split that gives the largest drop in Gini impurity or entropy (highest Information Gain), then repeat recursively on each branch until you hit a stopping rule like max_depth or min_samples_leaf.
How does a Decision Tree decide which feature to split on first?
At each node, the algorithm tests every feature and candidate threshold, measures the weighted Gini Impurity (or Entropy) of the two resulting child groups, and greedily chooses the single split that creates the largest drop in impurity (Information Gain).
What is the difference between Gini Impurity and Entropy in Decision Trees?
Both measure how mixed a node is, equalling 0 for a pure node and peaking at a 50/50 split. Gini ranges from 0 to 0.50 and avoids computing logarithms, making it slightly faster than Entropy (0 to 1 bit); in practice, both produce nearly identical trees.
Do Decision Trees require feature scaling like StandardScaler?
No! Because a Decision Tree only asks rank-order threshold questions (such as Income >= £45k), multiplying a column by 1,000 or applying a monotonic shift changes nothing about how rows split.
Why do Decision Trees overfit so easily, and how do you stop them?
Left unconstrained, a Decision Tree keeps splitting until every single training point sits in its own tiny pure leaf box (100% training accuracy, poor test accuracy). You stop this by limiting max_depth, setting min_samples_leaf, or applying cost-complexity pruning (ccp_alpha).
Can Decision Trees be used for Regression as well as Classification?
Yes. A Regression Tree uses the exact same top-down splitting logic, except instead of minimizing Gini Impurity it chooses splits that minimize Variance (Mean Squared Error) inside each leaf, then predicts the mean target value of that leaf.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/decision-trees/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@misc{irshad2026decisiontrees,
  author       = {Irshad, Muhammad Aashir},
  title        = {Decision Trees & Split Impurity: Interactive Visual Guide},
  howpublished = {SeeingML},
  year         = {2026},
  month        = {dec},
  url          = {https://seeingml.com/learn/decision-trees/},
  note         = {Interactive visual guide}
}
APA

Irshad, M. A. (2026). Decision Trees & Split Impurity: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/decision-trees/