Decision Trees
Algorithms

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

1. Root Node (Entire Dataset)
Evaluates all features to find the split that maximizes impurity reduction
2. Binary Decision Split
Divides the dataset into Left (True) and Right (False) child subsets
3. Recursive Sub-Tree Growth
Repeats splitting on each child node until stopping conditions are met
4. Terminal Leaf Nodes
Outputs the majority class label or the mean numerical value

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

  1. Prepare Clean Feature Matrix

    Decision trees work well with both numbers and categories, and they do not require feature scaling like StandardScaler.

  2. Select Splitting Criterion

    Choose between Gini Impurity (faster computation) or Entropy / Information Gain. Both metrics produce very similar trees in most practical cases.

  3. 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.

  4. 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.

  5. 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

Training, Constraining, and Inspecting a Decision Tree in Pythonpython
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}")
This script trains a constrained Decision Tree with `max_depth=3` and `min_samples_leaf=5`, then prints out the learned rules as text. You can read each branch directly to see how the model categorizes each flower.

Decision Tree vs Linear / Logistic Model

AspectDecision TreeLinear / Logistic Model
Decision BoundariesRectangular, step-like boundaries aligned with feature axesSmooth, continuous straight lines or flat hyperplanes
Feature Scaling NeededNo: unaffected by feature scale or monotonic transformationsYes: strictly requires normalization or standardization
InterpretabilityVery high: can be read and drawn as an intuitive flowchartModerate: interpreted through mathematical weights and coefficients
Risk of OverfittingVery high without depth limits or pruningLow to moderate, controlled through regularization penalties
Handling Non-LinearityNaturally captures non-linear patterns and feature interactionsRequires manual feature combinations or polynomial terms

Cost-Complexity Pruning (R_alpha(T)) Mathematical Derivation

Stopping a tree early using parameters like max_depth is fast, but it can sometimes stop too soon before discovering useful combinations of features further down the tree. Minimal Cost-Complexity Pruning solves this problem through a clear two-step process: 1. Grow a Full Tree: Let the tree grow until all leaves are pure, capturing all potential relationships. 2. Weakest-Link Trimming: Use a cost formula that balances error against tree size: R_\alpha(T) = R(T) + \alpha |T| Here, R(T) represents training error, |T| is the number of leaf nodes, and alpha is a penalty for each added leaf. For each branch, the algorithm calculates the exact alpha value where trimming that branch causes no meaningful harm. 3. Cross-Validation Selection: By testing these pruned variations against validation data, the algorithm picks the value of alpha that delivers the best balance between simplicity and real-world accuracy.

Tree Splitting Algorithms: CART vs ID3 vs C4.5 vs CHAID

Different decision tree algorithms handle splits, data types, and branching in different ways: • CART (Classification and Regression Trees): - Branching: Always makes two-way (binary) splits into Left and Right child nodes. - Metric: Uses Gini Impurity for classification and Mean Squared Error for regression. - Types: Works with both numbers and categories. This is the algorithm implemented in Scikit-Learn. • ID3 (Iterative Dichotomiser 3): - Branching: Creates multi-way branches for each distinct categorical value. - Metric: Uses Shannon Entropy and Information Gain. - Drawback: Biased toward features with many distinct values, such as ID numbers or phone numbers, which look artificially pure. • C4.5: - Improvements: An upgrade to ID3 that normalizes Information Gain into Gain Ratio, reducing bias toward high-cardinality features. It also handles continuous numerical features and missing values. • CHAID (Chi-Square Automatic Interaction Detection): - Metric: Uses statistical chi-square tests for categories and F-tests for numbers. It stops growing when splits no longer reach statistical significance.

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

  1. Given a node with 40 positive samples and 10 negative samples, compute its Gini Impurity and Shannon Entropy.
  2. Explain why a decision tree must build a staircase pattern of splits to separate points along a simple diagonal boundary like y = x.