Rana Maninder Singh
Lesson 6 of 7ML Fundamentals

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

ResourceLink
PreviousK-Nearest Neighbors
NextFeature engineering
PrerequisitesLogistic 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 Stay

WHY 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

\]

Hand example — 8 customers at root:

ChurnedCount
Stay (0)6
Churn (1)2

After split on support_tickets > 3:

Left (tickets ≤ 3)Right (tickets > 3)
5 stay, 0 churn1 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:

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 depthTrain accuracyTest accuracyDiagnosis
172%71%Underfit — too simple
378%76%Reasonable
None (full)99%68%Overfit — memorised

Controls to reduce overfitting:

ParameterEffect
max_depthCap tree height
min_samples_leafRequire ≥ N rows per leaf
min_samples_splitRequire ≥ 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 regressionDecision tree
BoundaryLinearStair-step, non-linear
InterpretabilityCoefficientsIF/ELSE rules
Overfitting riskLower (linear)Higher without limits
Best forSmooth relationshipsRule-based ops workflows

Essential commands

Command / actionWhat it does
DecisionTreeClassifier(max_depth=3)Shallow interpretable tree
export_text(model, feature_names=...)Print rules
Compare train vs test accuracySpot 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_text output as business rules
  • [ ] Next: Random forests