Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 2 of 9
Decision Trees: Information Gain, Gini Impurity, Pruning & Interpretation
Decision Trees perform non-parametric recursive binary partitioning of feature space. At each internal node, the algorithm greedily selects the feature and numerical split threshold that maximizes the reduction in impurity. Splitting criteria include Gini Impurity: G = 1 - sum(p_i²) and Shannon Entropy: H = - sum(p_i log2(p_i)). Unconstrained trees grow deep and overfit by memorizing training instances. Cost-Complexity Pruning (CCP) prunes trees back to optimal generalization capacity.
Tree Splitting, Impurity Reduction & Cost-Complexity Pruning
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.metrics import accuracy_score
# Ingest high-dimensional medical dataset
raw = load_breast_cancer(as_frame=True)
X, y = raw.data, raw.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
# 1. UNCONSTRAINED OVERFITTING TREE (Grows deep until leaves are pure)
unconstrained_tree = DecisionTreeClassifier(criterion='gini', random_state=42)
unconstrained_tree.fit(X_train, y_train)
train_acc = accuracy_score(y_train, unconstrained_tree.predict(X_train))
test_acc = accuracy_score(y_test, unconstrained_tree.predict(X_test))
print(f"Unconstrained Tree Depth: {unconstrained_tree.get_depth()} | Leaves: {unconstrained_tree.get_n_leaves()}")
print(f" Train Accuracy: {train_acc*100:.2f}% | Test Accuracy: {test_acc*100:.2f}% (Notice overfitting gap!)")
# 2. COST-COMPLEXITY PRUNING (ccp_alpha)
# Cost Complexity Criterion: R_alpha(T) = R(T) + alpha * |T|
path = unconstrained_tree.cost_complexity_pruning_path(X_train, y_train)
ccp_alphas = path.ccp_alphas[:-1] # Exclude root-only tree
# Evaluate pruned trees across alpha values
best_alpha = None
best_test_acc = 0.0
for alpha in ccp_alphas[::5]: # Sample alpha grid
pruned_tree = DecisionTreeClassifier(random_state=42, ccp_alpha=alpha)
pruned_tree.fit(X_train, y_train)
acc = accuracy_score(y_test, pruned_tree.predict(X_test))
if acc > best_test_acc:
best_test_acc = acc
best_alpha = alpha
print(f"\nOptimal Pruning Alpha (ccp_alpha): {best_alpha:.5f}")
optimal_tree = DecisionTreeClassifier(random_state=42, ccp_alpha=best_alpha)
optimal_tree.fit(X_train, y_train)
print(f"Pruned Tree Depth: {optimal_tree.get_depth()} | Leaves: {optimal_tree.get_n_leaves()}")
print(f" Pruned Test Accuracy: {accuracy_score(y_test, optimal_tree.predict(X_test))*100:.2f}% (Generalization restored!)")Pro Tip: Explainability with Text Trees
You can convert any fitted Scikit-Learn tree into human-readable conditional business logic using `sklearn.tree.export_text(tree, feature_names=list(X.columns))`. This can be audited directly by legal and compliance teams without specialized software.
Tree = interpretable. Forest = robust. XGBoost = wins.
Hands-On Challenge: Calculate Gini Impurity by Hand
Write a function `compute_gini(labels)` that accepts a list of binary class labels and calculates `1 - (p0^2 + p1^2)`. Verify that a 50:50 mixed split yields a maximum impurity of 0.5, while a pure node yields an impurity of 0.0.
Quick Quiz & Key Concept Checks
Common Pitfall: Bias Toward High-Cardinality Features
Information gain and Gini impurity are heavily biased toward features with many distinct values (e.g., zip codes or birthdates). A unique ID column can achieve 100% information gain at the root node while providing zero real predictive power. Never include raw identifier columns.