Skip to content
Lambdian

Decision trees

Learn a flowchart of yes/no questions: greedy splits, impurity, depth and pruning.

Animated explanation

The idea

A decision tree is a flowchart: Is income below ₹40k? If yes, is the loan longer than 5 years?… until it reaches a leaf that gives the answer. Each question looks at one feature and a threshold, so the tree slices the feature space into boxes and predicts the majority class (or mean value) in each box.

Training is greedy: at each node, try every feature and threshold, and keep the split that makes the two children purest. Repeat inside each child. Trees need no feature scaling, handle mixed feature types, capture interactions, and are easy to read. Their weakness is variance: a deep tree memorises its training data, and a small change in the data can grow a very different tree.

Purity measures

Gini impurity 1−∑kpk21-\sum_kp_k^2 is the probability that two random members of a node disagree; entropy −∑kpklog⁡2pk-\sum_kp_k\log_2p_k measures uncertainty in bits. Both are zero for a pure node and largest for an even mix, and in practice they pick nearly the same splits. For regression, impurity is the variance of the target in the node, and leaves predict the mean.

Controlling overfitting

Grown until every leaf is pure, a tree reaches zero training error and generalises poorly. Limit it with max_depth, min_samples_leaf or min_impurity_decrease (pre-pruning), or grow it fully and cost-complexity prune it back, choosing the penalty α\alpha in R(T)+α∣T∣R(T) + \alpha|T| by cross-validation. Better still, average many trees: random forests and boosting (next lessons).

Strengths you only get from trees

Splits are invariant to monotone transformations of a feature (no scaling needed), categorical and missing values can be handled natively, and the path to each leaf is a human-readable rule. Feature importance is the total impurity decrease contributed by each feature (biased towards features with many split points; permutation importance is safer).

The algorithm, step by step

  1. 1
    Start with all training data at the root.
  2. 2
    For every feature and every midpoint between consecutive sorted values, compute the weighted impurity of the two children.
  3. 3
    Split on the best one if it reduces impurity and stopping rules allow; otherwise make a leaf (majority class or mean).
  4. 4
    Recurse into each child.
  5. 5
    Predict by following the questions from the root to a leaf.

The maths

Gini impurity

G(S)=1−∑kpk2G(S) = 1 - \sum_{k} p_k^2

Entropy

H(S)=−∑kpklog⁡2pkH(S) = -\sum_k p_k\log_2 p_k

Split quality

cost(j,t)=nLnI(SL)+nRnI(SR)\text{cost}(j, t) = \frac{n_L}{n}I(S_L) + \frac{n_R}{n}I(S_R)

Cost-complexity pruning

Rα(T)=R(T)+α ∣leaves(T)∣R_\alpha(T) = R(T) + \alpha\,|\mathrm{leaves}(T)|

Strengths and weaknesses

Strengths

  • Readable rules; no scaling needed
  • Handles numeric and categorical features and interactions
  • Fast prediction; the base of the best tabular models

Weaknesses

  • High variance: small data changes give different trees
  • Greedy splits are not globally optimal
  • Axis-aligned boxes approximate diagonal boundaries poorly

Reach for it when…

You need an explainable model, or as the building block of forests and boosting.

Check your understanding

Question 1

Q1A node has 8 cats and 2 dogs. Its Gini impurity is…

Question 2

Q2Why don't decision trees need feature scaling?

Question 3

Q3A fully grown tree has 100% training accuracy and 70% test accuracy. Best first fix?

Lambdian Lab

Grow a CART tree

A classification tree for integer labels.

  • gini(y): impurity of a label array.
  • best_split(X, y): (feature, threshold, cost) minimising weighted Gini over all features and midpoints between sorted unique values; None if no split lowers impurity.
  • build(X, y, depth, max_depth, min_samples): nested dicts — a leaf is {"leaf": True, "value": majority} and a split is {"leaf": False, "f": j, "t": threshold, "left": …, "right": …} (left means x[j] <= t).
  • predict_one(node, x) and predict(node, X).
Open the labPython + NumPy + scikit-learn runs in your browser. Sign-in keeps your code and attempts.