PIXELBANKv9.1.0
Menu
Back to ML Study Plan
Week 9-10

Chapter 5: Decision Trees

Master the most interpretable machine learning models. Learn how decision trees recursively partition feature space, choose optimal splits using Gini impurity and entropy, prevent overfitting through pruning, and extract feature importance from learned structures.

Chapter Overview

Decision trees are among the most intuitive models in machine learning. They mirror human decision-making by asking a series of questions: "Is this feature above a threshold? If yes, go left; if no, go right." This continues until reaching a leaf node that makes the final prediction.

The key advantage of decision trees is interpretability—you can trace exactly why a model made a particular prediction by following the decision path from root to leaf. This makes trees invaluable in domains requiring explainability, like healthcare and finance.

Trees are also remarkably versatile. They handle both numerical and categorical features naturally, don't require feature scaling, and can capture non-linear relationships and interactions without explicit feature engineering. The same algorithm works for classification (predict a class) and regression (predict a continuous value).

The main challenge is overfitting. An unpruned tree will keep splitting until each leaf contains a single training example—perfect training accuracy but useless generalization. Controlling tree complexity through pruning and stopping criteria is essential.

Decision trees also form the foundation for powerful ensemble methods like Random Forests and Gradient Boosting, which combine many trees to achieve state-of-the-art performance.

This chapter covers:

  • Tree Construction: How trees recursively partition data through optimal splits
  • Splitting Criteria: Measuring node purity with Gini impurity, entropy, and MSE
  • Pruning: Pre-pruning and post-pruning to prevent overfitting
  • Regression Trees: Decision trees for continuous targets
  • Feature Importance: Extracting which features contribute most to predictions
  • Tree Visualization: Understanding and explaining tree decisions

Chapter Roadmap

Click any topic to jump in

1
Decision Tree Basics

Recursive partitioning, tree structure, and how trees make predictions — the most interpretable ML model.

Tree StructureRecursive PartitioningSplit SelectionClassification TreesRegression TreesAdvantages of TreesDisadvantages of Trees
How to split and when to stop

Splitting criteria decide each branch, pruning decides when to stop growing

2
Splitting Criteria

Gini impurity, entropy, and information gain — mathematical measures that guide optimal split selection.

Gini ImpurityEntropyInformation GainGain RatioGini vs EntropyMSE for RegressionMAE for Regression
3
Pruning

Pre-pruning and post-pruning — controlling tree complexity to prevent overfitting.

Pre-pruning (Early Stopping)Post-pruningCost-Complexity Pruning (CCP)Finding Optimal αmax_depthmin_samples_split / min_samples_leafMinimum Impurity Decrease
Continuous targets and model insights

Regression trees extend to continuous outputs, feature importance explains the model

4
Regression Trees

Piecewise constant predictions for continuous targets — MSE splitting and the extrapolation problem.

Regression Tree PredictionMSE as Splitting CriterionPiecewise Constant ApproximationMAE CriterionExtrapolation ProblemComparison to Linear Regression
5
Feature Importance

Impurity-based importance, permutation importance, and SHAP — understanding what drives predictions.

Impurity-Based ImportanceInterpreting ImportanceHigh-Cardinality BiasCorrelated FeaturesPermutation ImportanceSHAP Values
Making trees explainable
6
Visualization & Interpretation

Visualizing trees, extracting rules, and interpreting decisions — the unique explainability advantage of trees.

Tree VisualizationDecision PathRule ExtractionInterpreting NodesGlobal vs Local InterpretationWhen Trees Are Best

Suppose a bank wants to approve loans with a model whose every decision can be read aloud to the applicant. Linear and logistic regression, from the earlier chapters, give one weighted sum per prediction: accurate when the relationship is roughly linear, but hard to explain when the true rule is "approve if income is high, unless debt is also high." Such rules involve thresholds and interactions that a single hyperplane cannot express without hand-built features. The previous chapter, Model Evaluation, gave us the tools to measure whether a model generalizes; this chapter builds a model family whose structure we can also inspect.

A decision tree answers a sequence of yes-or-no questions about the features, each answer narrowing the set of possibilities, until it reaches a leaf that makes the prediction. This first topic covers the anatomy of a tree, the recursive partitioning that builds it, and how the best split is searched for. We then look at what classification and regression leaves predict, and close with the strengths and weaknesses that motivate pruning later in this chapter and ensembles in the next.

Definition

A decision tree is a model that recursively partitions the feature space with axis-aligned tests of the form "feature j is at most threshold t". Each internal node holds one test, each branch one outcome, and each leaf a constant prediction: a class (with class proportions) for classification, or a mean value for regression.

In this topic

1Tree Structure
2Recursive Partitioning
3Split Selection
4Classification Trees
5Regression Trees
6Advantages of Trees
7Disadvantages of Trees
1 of 7
Tree Structure

A tree is built from three kinds of nodes. The root is the first test, applied to every sample. Internal nodes apply further tests to the samples routed to them, and leaves hold the final predictions. Every root-to-leaf path is a conjunction of conditions, so the whole tree is a set of mutually exclusive rules. Depth is the number of edges on the longest path; a binary tree of depth dd has at most 2d2^d leaves and 2d+1−12^{d+1}-1 nodes. Depth controls both capacity and readability: depth 3 gives at most 8 rules a person can follow, while depth 20 allows over a million leaves.

Mathematical Intuition

A binary decision tree with depth dd has at most 2d2^d leaf nodes and 2d−12^d - 1 internal nodes, for a maximum of 2d+1−12^{d+1} - 1 total nodes. Each internal node stores a split rule (j,τ)(j, \tau) meaning "feature j≤τj \leq \tau?" The number of possible trees with pp features grows super-exponentially, making brute-force search over all tree structures intractable — greedy top-down construction is necessary.

Example:

Tree has root, 2 children (1 leaf, 1 internal with 2 leaves). How many nodes? What depth?

2 of 7
Recursive Partitioning

Trees are grown top-down and greedily. Starting with all training samples at the root, the algorithm chooses the single feature and threshold whose split most improves purity, sends samples to the left or right child, and repeats the same procedure independently inside each child. Growth stops when a node is pure, too small, or a depth limit is reached. Each split cuts a region with a line perpendicular to one feature axis, so the final partition is a set of axis-aligned boxes. Greedy means each split is chosen without looking ahead, so the resulting tree is good but not guaranteed optimal; finding the optimal tree is NP-hard.

Mathematical Intuition

Each split on feature xj≤τx_j \leq \tau divides a region RR into RL=R∩{xj≤τ}R_L = R \cap \{x_j \leq \tau\} and RR=R∩{xj>τ}R_R = R \cap \{x_j > \tau\}. After dd splits, the feature space is partitioned into at most 2d2^d axis-aligned rectangular regions. The tree prediction is constant within each region: f^(x)=cm\hat{f}(x) = c_m for x∈Rmx \in R_m. This makes trees piecewise constant approximators — they approximate any continuous function by stacking enough rectangular regions.

Example:

Root splits on age>30. Left child splits on income>50K. What regions are created?

3 of 7
Split Selection

At each node the tree must choose one feature and one threshold. For a numeric feature with nn distinct sorted values, only n−1n-1 thresholds can produce different partitions, so candidates are the midpoints between consecutive values. For each candidate the algorithm computes the impurity of the two children, weighted by their sizes, and keeps the split with the largest reduction from the parent. Sorting once and scanning with running counts makes each feature cost about O(nlog⁡n)O(n \log n). The search is exhaustive over features and thresholds but myopic over depth, which is why a split with little immediate gain can be overlooked.

Mathematical Intuition

For a feature with nn unique values, there are n−1n-1 candidate thresholds (midpoints between consecutive sorted values). With pp features, the greedy algorithm evaluates O(pn)O(pn) candidate splits per node. For each candidate, computing the impurity reduction takes O(n)O(n) time using running sums. The total cost for building a balanced tree of depth dd is O(pnlog⁡n)O(pn \log n) if the data is pre-sorted, or O(pn2)O(pn^2) in the worst case for unbalanced trees.

Example:

Feature X has values [10, 20, 35, 40]. What thresholds to try?

4 of 7
Classification Trees

In a classification tree each leaf stores the class counts of the training samples that reached it. The predicted class is the majority class, which minimizes misclassification on those samples, and the predicted probabilities are the class proportions, which are maximum likelihood estimates for that region. Probabilities from small leaves are unreliable: a leaf with 3 samples can only output multiples of one third, and a pure leaf outputs probability 1 even when the true rate is lower. Deep trees therefore tend to give overconfident, poorly calibrated probabilities, which is one reason min_samples_leaf and ensembles help.

Mathematical Intuition

A leaf containing nmn_m samples with class counts (nm,1,…,nm,K)(n_{m,1}, \ldots, n_{m,K}) predicts class k^=arg⁡max⁡knm,k\hat{k} = \arg\max_k n_{m,k} and outputs probabilities p^k=nm,k/nm\hat{p}_k = n_{m,k} / n_m. The class probabilities are maximum likelihood estimates for a categorical distribution. The prediction k^\hat{k} minimizes the 0-1 loss (misclassification rate) on the leaf's training samples. More samples in the leaf give more reliable probability estimates, with standard error p^k(1−p^k)/nm\sqrt{\hat{p}_k(1-\hat{p}_k)/n_m}.

Example:

Leaf has 30 samples: 20 cats, 8 dogs, 2 birds. Prediction? Probabilities?

5 of 7
Regression Trees

A regression tree uses the same partitioning, but each leaf predicts a number: the mean of the training targets in that region. The mean is the constant that minimizes squared error within the leaf, so it pairs naturally with the variance-reduction split criterion covered next. The resulting model is a step function: constant inside each region and jumping at the boundaries. A leaf's prediction has variance proportional to the noise variance divided by the number of samples it holds, so deep trees with tiny leaves give noisy, overfitted predictions. A later topic in this chapter treats regression trees in depth.

Mathematical Intuition

A leaf predicts y^=yˉm=1nm∑xi∈Rmyi\hat{y} = \bar{y}_m = \frac{1}{n_m}\sum_{x_i \in R_m} y_i, the sample mean of targets in region RmR_m. This minimizes the squared error ∑xi∈Rm(yi−c)2\sum_{x_i \in R_m}(y_i - c)^2 over the constant cc. The prediction variance within the leaf is Var(y^m)=σ2/nm\text{Var}(\hat{y}_m) = \sigma^2/n_m where σ2\sigma^2 is the noise variance. Deep trees with few samples per leaf have high prediction variance — this is the overfitting mechanism in regression trees.

Example:

Leaf has 4 house prices, in thousands: [200, 220, 240, 300]. Prediction?

6 of 7
Advantages of Trees

Trees need little preprocessing. A split compares a feature with a threshold, so any monotonic transformation of a feature, such as scaling or taking logs, yields the same partitions; no standardization is required. Trees model interactions automatically, because a split on one feature followed by a split on another creates a rule involving both. They handle mixed feature types, ignore irrelevant features that are never chosen, and predict in time proportional to depth. Above all, a shallow tree is readable. Some caveats apply: scikit-learn's implementation needs categorical features encoded as numbers, and its support for missing values depends on the version.

Mathematical Intuition

Trees are invariant to monotonic transformations of features: if xj≤τx_j \leq \tau is a good split, then log⁡(xj)≤log⁡(τ)\log(x_j) \leq \log(\tau) produces the same partition. This means no feature scaling is needed. Trees also naturally handle interactions: a split on x1x_1 followed by a split on x2x_2 captures the interaction x1×x2x_1 \times x_2 without explicit feature engineering. Inference is O(d)O(d) — just follow a path from root to leaf, comparing one feature at each node.

Example:

Income in dollars, age in years, city as category. Do you need to preprocess for a tree?

7 of 7
Disadvantages of Trees

The main weakness of a single tree is high variance. Because splits are chosen greedily, a small change in the training data can change the root split, and every split below it changes too, giving a very different tree with similar accuracy. Trees also draw only axis-aligned boundaries, so a diagonal boundary such as x1+x2=cx_1 + x_2 = c must be approximated by a staircase of many splits. Grown fully, they memorize the training set. Finally, regression trees cannot extrapolate beyond the target range seen in training. Pruning reduces overfitting, and ensembles such as random forests, in the next chapter, average away much of the variance.

Mathematical Intuition

Trees are high-variance estimators: the greedy split selection means that adding or removing a single training sample can change the root split, cascading to a completely different tree structure. Formally, Var(f^tree(x))≫Var(f^linear(x))\text{Var}(\hat{f}_{\text{tree}}(x)) \gg \text{Var}(\hat{f}_{\text{linear}}(x)) for smooth functions. Trees also create axis-aligned boundaries only — approximating a diagonal boundary x1+x2=cx_1 + x_2 = c requires O(1/ϵ)O(1/\epsilon) splits for accuracy ϵ\epsilon, creating a staircase pattern.

Example:

Remove 1 sample, tree structure changes completely. Is this normal?

Theory Exercise

Problem:

Why do decision trees create axis-aligned boundaries? What patterns would be hard for a single tree to capture?

Hints:
  • Each split divides on one feature at a time
  • Think about diagonal patterns
  • What about circular decision boundaries?

Coding Exercise

Problem:

Fit a shallow DecisionTreeClassifier (max_depth=2) on the iris dataset and print its decision rules with export_text. Observe how readable the rules are.

Hints:
  • Load iris with load_iris(return_X_y=True) and keep load_iris().feature_names for labeling.
  • Constrain the tree with max_depth=2 and always pass random_state=42.
  • Use export_text(clf, feature_names=...) to dump human-readable if/else rules, then call clf.score for accuracy.