Decision Trees — Gini Impurity & Overfitting
Lesson opener
In one line: How decision trees split data with yes/no rules humans can read.
Why it matters: Trees are interpretable - you can paste rules into a slide for stakeholders.
Before this lesson: Logistic regression / ML workflow
Before you start
| Resource | Link |
|---|---|
| Previous | K-Nearest Neighbors |
| Next | Feature engineering |
| Prerequisites | Logistic regression, ML workflow |
| Time | ~50 minutes |
What you will learn
- How decision trees split data with yes/no rules humans can read
- What Gini impurity measures — and why trees minimise it
- Why deep trees overfit and shallow trees underfit
- How to control tree depth for Indian customer segmentation
What is a decision tree?
The problem it solves: A Delhi insurance call centre manager asks, "Which customers should we call first?" A decision tree answers with rules:
IF support_tickets > 3 AND tenure_months < 12
→ predict Churn
ELSE
→ predict StayWHY Trees are interpretable — you can paste rules into a slide for stakeholders.
WHEN You need explainability, mixed numeric and categorical features, or non-linear boundaries.
Unlike logistic regression's single equation, trees partition feature space into boxes.
How a split works — Gini impurity
At each node, the algorithm tries every feature and threshold, picking the split that purifies the two child nodes most.
Gini impurity for a node:
\[
G = 1 - \sum_{k=1}^{K} p_k^2
\]
- \(p_k\) = proportion of class k in the node
- G = 0 when node is pure (all one class)
- G is highest when classes are evenly mixed
Hand example — 8 customers at root:
| Churned | Count |
|---|---|
| Stay (0) | 6 |
| Churn (1) | 2 |
- p_stay = 6/8 = 0.75, p_churn = 2/8 = 0.25
- G = 1 − (0.75² + 0.25²) = 1 − (0.5625 + 0.0625) = 0.375
After split on support_tickets > 3:
| Left (tickets ≤ 3) | Right (tickets > 3) |
|---|---|
| 5 stay, 0 churn | 1 stay, 2 churn |
| G ≈ 0 (pure) | G = 1 − (⅓² + ⅔²) ≈ 0.444 |
Weighted Gini improves — tree keeps the split.
WHY Gini is fast to compute and works well for multi-class problems.
WHEN sklearn's DecisionTreeClassifier uses Gini by default (criterion='gini').
sklearn — churn tree with depth limit
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.metrics import accuracy_score
df = pd.read_csv("data/customers.csv")
X = df[["tenure_months", "monthly_spend", "support_tickets"]]
y = df["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# Shallow tree — less overfitting
model = DecisionTreeClassifier(max_depth=3, random_state=42)
model.fit(X_train, y_train)
print("Train accuracy:", accuracy_score(y_train, model.predict(X_train)))
print("Test accuracy:", accuracy_score(y_test, model.predict(X_test)))
print(export_text(model, feature_names=list(X.columns)))Breaking it down:
max_depth=3— at most 3 levels of splits- Train accuracy >> test accuracy → overfitting signal
export_text— human-readable rules for ops team
Use this when: compliance needs "why was this customer scored high risk?"
Overfitting — the tree memorisation trap
Overfitting means the model learns noise in training data — including quirks of specific Mumbai or Chennai customers — and fails on new data.
| Tree depth | Train accuracy | Test accuracy | Diagnosis |
|---|---|---|---|
| 1 | 72% | 71% | Underfit — too simple |
| 3 | 78% | 76% | Reasonable |
| None (full) | 99% | 68% | Overfit — memorised |
Controls to reduce overfitting:
| Parameter | Effect |
|---|---|
max_depth | Cap tree height |
min_samples_leaf | Require ≥ N rows per leaf |
min_samples_split | Require ≥ N rows to split a node |
Indian workplace example: A Kolkata ed-tech startup trains a tree on 200 students with 50 features. Full depth hits 100% train accuracy. max_depth=4 drops train to 85% but test improves — the deployable model.
Trees vs logistic regression
| Logistic regression | Decision tree | |
|---|---|---|
| Boundary | Linear | Stair-step, non-linear |
| Interpretability | Coefficients | IF/ELSE rules |
| Overfitting risk | Lower (linear) | Higher without limits |
| Best for | Smooth relationships | Rule-based ops workflows |
Essential commands
| Command / action | What it does |
|---|---|
DecisionTreeClassifier(max_depth=3) | Shallow interpretable tree |
export_text(model, feature_names=...) | Print rules |
| Compare train vs test accuracy | Spot overfitting |
criterion='gini' | Default split metric |
Practice
Do this now: Fit two trees on churn — max_depth=2 and max_depth=None. Compare train and test accuracy. Paste the shallow tree rules and explain one split in plain English for a retention manager.
Checklist
- [ ] I can explain Gini impurity as "how mixed a node is"
- [ ] I know why unlimited depth trees overfit
- [ ] Train vs test accuracy compared for depth tuning
- [ ] I can read
export_textoutput as business rules - [ ] Next: Random forests