Decision Trees
A complete guide to Decision Trees: tree architecture (root, nodes, leaves), splitting criteria (Entropy, Information Gain, Gini Impurity), CART, and pruning to prevent overfitting.
Think about playing the classic game 20 Questions. You have a secret object in mind, and your friend tries to guess it by asking only yes-or-no questions. Your friend does not start by blurting out a wild guess like, 'Is it a 1998 sedan?' That would waste an entire question on a low-probability guess. Instead, they ask a broad question that splits the possibilities cleanly in half: 'Is it a living thing?' If you answer yes, they instantly rule out rocks, cars, furniture, and computers. Next question: 'Does it have four legs?' You say yes. 'Does it bark?' You say yes. Your friend smiles and guesses: 'It is a dog!' With just three focused questions, your friend narrowed down millions of possible items to the right answer. A Decision Tree works on this exact same principle. It builds a hierarchical flowchart of questions where each internal node tests a specific feature, each branch represents the answer, and each leaf node delivers the final prediction.
Definition
A Decision Tree is a non-parametric supervised machine learning algorithm that recursively splits data into smaller subsets using a sequence of logical rules, making it capable of handling both classification and regression tasks with clear interpretability.
Why It Matters
Many machine learning models, such as deep neural networks, act like black boxes. They can give you an accurate prediction, but they cannot clearly explain how they arrived at that conclusion. In fields like medicine, banking, and law, black-box decisions can be risky or even illegal under regulations like the GDPR Right to Explanation. A doctor cannot recommend an aggressive treatment simply because an algorithm recommended it; a bank cannot reject a loan application without giving clear, understandable reasons to the applicant. Decision Trees matter because their reasoning is transparent. You can trace every branch from top to bottom, understand the exact rule applied at each step, and explain the logic clearly to clients, auditors, or patients.
How It Works
Let us walk through how a Decision Tree is structured and how it decides which questions to ask: 1. Parts of a Decision Tree: • Root Node: The top of the tree that receives the entire dataset and asks the very first question. • Internal Decision Nodes: Intermediate points where the data splits based on a specific feature threshold, such as 'Age > 30'. • Branches: The connecting paths that represent the outcome of a test, usually True or False. • Leaf Nodes: The end points of the tree that deliver the final answer, such as a category label or a numerical average. 2. How the Algorithm Picks the Best Split: At every step, the algorithm looks at all available features and possible split points to find the question that produces the cleanest, most uniform groups. We call this quality purity. Two common formulas measure impurity: • Gini Impurity (used by CART): Measures the chance that a randomly selected item would be labeled incorrectly if it were classified according to the label distribution in that node: $$Gini = 1 - \sum_{i=1}^C p_i^2$$ If a node contains only cat photos ($p = 1.0$), then $Gini = 1 - (1.0)^2 = 0$, meaning the node is completely pure. If a node has an even 50/50 mix of cats and dogs, $Gini = 0.5$, which represents maximum disorder for two classes. • Shannon Entropy and Information Gain (used by ID3 and C4.5): Entropy measures uncertainty or disorder in a dataset: $$H(S) = - \sum_{i=1}^C p_i \log_2(p_i)$$ Information Gain ($IG$) measures how much entropy drops after splitting the data using feature $A$: $$IG(S, A) = H(S) - \sum_{v \in Values(A)} \frac{|S_v|}{|S|} H(S_v)$$ The algorithm chooses the split that produces the highest Information Gain. 3. Overfitting and Pruning: If you let a tree grow without restrictions, it will continue splitting until every single training example sits in its own leaf node. That gives 100% accuracy on training data, but the tree simply memorizes quirks and noise, failing on new data. • Pre-Pruning (Early Stopping): Stop the tree early by setting limits like `max_depth`, `min_samples_split`, or `min_samples_leaf`. • Post-Pruning (Cost-Complexity Pruning): Let the tree grow fully, and then trim back branches that add little predictive value.
Decision Tree Hierarchical Splitting Architecture
Key Points
- Decision Trees are intuitive flowchart models that make transparent, step-by-step decisions.
- Splits are chosen to maximize purity using formulas like Gini Impurity or Information Gain.
- Feature scaling is not needed because trees only look at the ordering of values within each feature.
- Trees can easily overfit if their depth and minimum leaf sizes are not limited.
- They form the building blocks for ensemble models like Random Forests and Gradient Boosted Trees.
Steps
Prepare Clean Feature Matrix
Decision trees work well with both numbers and categories, and they do not require feature scaling like StandardScaler.
Select Splitting Criterion
Choose between Gini Impurity (faster computation) or Entropy / Information Gain. Both metrics produce very similar trees in most practical cases.
Constrain Tree Hyperparameters
Set limits like `max_depth` (such as 3 to 6) and `min_samples_leaf` (such as 5 to 20) to keep the tree simple and prevent overfitting.
Fit and Visualize the Tree
Train the model using Scikit-Learn. Use `plot_tree` or `export_text` to inspect the learned flowchart rules and ensure they make intuitive sense.
Extract Feature Importances
Check which features were selected near the root to understand which inputs drive predictions most strongly.
Formula
Gini Impurity (CART):
Gini(p) = 1 - \sum_{i=1}^C p_i^2
Shannon Entropy (ID3 / C4.5):
H(S) = - \sum_{i=1}^C p_i \log_2(p_i)
Information Gain:
IG(S, A) = H(S) - \sum_{v \in Values(A)} \frac{|S_v|}{|S|} H(S_v)
Minimal Cost-Complexity Pruning Criterion:
R_\alpha(T) = R(T) + \alpha |T|
where R(T) is training error, |T| is number of terminal leaf nodes, and \alpha \ge 0 is the complexity penalty parameter.Examples
Bank Loan Approval Tree
Root Node: 'Credit Score > 700?' If Yes -> 'Annual Income > $60,000?' If Yes -> Leaf: 'Approve Loan'. If No -> 'Debt-to-Income < 30%?' If No -> Leaf: 'Reject Loan'.
Emergency Room Triage
A hospital triage tree: 'Oxygen Saturation < 90%?' If Yes -> Leaf: 'Immediate Intensive Care'. If No -> 'Systolic Blood Pressure > 180?' If Yes -> Leaf: 'Urgent Care'.
Real-World Examples
Clinical Decision Support Systems in Hospitals
Emergency departments use decision-tree guidelines, such as the Ottawa Ankle Rules or Wells Score, to help doctors decide whether a patient needs an expensive X-ray or CT scan. The rules provide fast, auditable guidance during high-pressure medical evaluations.
Loan Underwriting and Fair Lending Compliance
Under lending regulations such as the US Equal Credit Opportunity Act, lenders must provide clear reasons when denying credit. Decision trees allow banks to generate clear, transparent explanations, such as denying an application because the debt-to-income ratio exceeded 45 percent.
Technical Examples
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.model_selection import train_test_split
# 1. Load benchmark flower dataset
iris = load_iris()
X, y = iris.data, iris.target
# 2. Split dataset into train and test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 3. Train a regularized Decision Tree (prevent overfitting with max_depth=3)
tree_clf = DecisionTreeClassifier(
criterion='gini',
max_depth=3,
min_samples_leaf=5,
random_state=42
)
tree_clf.fit(X_train, y_train)
# 4. Print human-readable decision rules
rules = export_text(tree_clf, feature_names=iris.feature_names)
print("--- Learned Decision Tree Flowchart ---")
print(rules)
# 5. Inspect feature importances
print("\nFeature Importances:")
for name, imp in zip(iris.feature_names, tree_clf.feature_importances_):
print(f" {name:20s}: {imp:.4f}")Decision Tree vs Linear / Logistic Model
| Aspect | Decision Tree | Linear / Logistic Model |
|---|---|---|
| Decision Boundaries | Rectangular, step-like boundaries aligned with feature axes | Smooth, continuous straight lines or flat hyperplanes |
| Feature Scaling Needed | No: unaffected by feature scale or monotonic transformations | Yes: strictly requires normalization or standardization |
| Interpretability | Very high: can be read and drawn as an intuitive flowchart | Moderate: interpreted through mathematical weights and coefficients |
| Risk of Overfitting | Very high without depth limits or pruning | Low to moderate, controlled through regularization penalties |
| Handling Non-Linearity | Naturally captures non-linear patterns and feature interactions | Requires manual feature combinations or polynomial terms |
Cost-Complexity Pruning (R_alpha(T)) Mathematical Derivation
Tree Splitting Algorithms: CART vs ID3 vs C4.5 vs CHAID
Advantages
- Easy to interpret and explain to non-technical stakeholders.
- Requires no data scaling or normalization before training.
- Captures non-linear relationships and interactions without manual feature engineering.
- Handles both numerical and categorical inputs cleanly.
Limitations
- Can be unstable: small changes in training data can produce a completely different tree layout.
- Overfits easily if tree depth and leaf sizes are not restricted.
- Struggles with diagonal decision boundaries, creating inefficient staircase splits.
Interview Questions
Why do single decision trees have high variance, and how do ensemble methods solve this?
A single decision tree has high variance because its greedy splits depend heavily on the specific training data. A small change in data near the top of the tree can change the root split entirely, which cascades into completely different branches below. Ensemble methods like Random Forests solve this by training many diverse trees on random subsets of the data and features, then averaging their predictions. Averaging cancels out individual errors, cutting variance while keeping accuracy high.
Explain the difference between Pre-Pruning and Post-Pruning.
Pre-pruning stops a tree while it is still growing by setting thresholds such as maximum depth, minimum samples per split, or minimum impurity decrease. Post-pruning lets the tree grow completely to fit the training data, and then trims branches from the bottom up using cost-complexity pruning. Post-pruning is often more effective because it can discover valuable multi-step feature interactions that early stopping might overlook.
Practice Questions
- Given a node with 40 positive samples and 10 negative samples, compute its Gini Impurity and Shannon Entropy.
- Explain why a decision tree must build a staircase pattern of splits to separate points along a simple diagonal boundary like y = x.
