S30 Logo
S30 AI Labwww.thes30.com
Back
#14

Decision Trees

Medium🎯 Classical MLW4 D1

Before You Start

Required knowledge
Classification, class proportions, train/validation splits, and NumPy.
Libraries used
NumPy, scikit-learn
Dataset and source
Synthetic nonlinear classification data from the notebook's make_nonlinear helper.
Expected output
Impurity and split calculations, a decision stump, and tree-depth/generalization comparisons.

Decision Trees — Theory & Concepts

Read this before attempting the exercises. Decision trees are the foundation of the most powerful ML models in practice (Random Forest, XGBoost, LightGBM).


1. How Decision Trees Work

A decision tree recursively splits data based on feature thresholds:

                  [Age < 30?]
                 /            \
              Yes              No
         [Income > 50k?]    [Predict: No]
         /            \
      Yes              No
  [Predict: Yes]   [Predict: No]

At each node, the algorithm finds the best split — the feature and threshold that maximizes information gain.

Example decision tree


2. Splitting Criteria

Gini Impurity (Classification)

Gini(S) = 1 - Σ pᵢ²

# Pure node (all one class): Gini = 0
# Maximum impurity (50/50): Gini = 0.5

Entropy / Information Gain (Classification)

Entropy(S) = -Σ pᵢ log₂(pᵢ)
InfoGain = Entropy(parent) - Σ (nᵢ/N) x Entropy(childᵢ)

MSE Reduction (Regression)

MSE(S) = (1/n) Σ (yᵢ - ȳ)²

Interview Tip: Gini and entropy produce nearly identical trees. Gini is slightly faster (no log computation). sklearn uses Gini by default.

Gini impurity split comparison


3. Controlling Tree Complexity

ParameterEffectTypical Values
max_depthLimits tree depth3-10
min_samples_splitMin samples to split a node2-20
min_samples_leafMin samples in a leaf1-10
max_featuresFeatures considered per splitsqrt(d) or log2(d)
from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(max_depth=5, min_samples_leaf=5)

4. Strengths & Weaknesses

StrengthsWeaknesses
Interpretable (visualize the tree)High variance (small data changes → different tree)
Handles mixed feature typesProne to overfitting
No feature scaling neededGreedy splits (not globally optimal)
Captures nonlinear relationshipsUnstable (high variance)

5. Feature Importance

tree.fit(X, y)
importances = tree.feature_importances_  # based on total impurity reduction

Caveat: Tree feature importance is biased toward high-cardinality features. Use permutation importance for more reliable results.


6. Decision Boundaries

Trees create axis-aligned rectangular decision boundaries:

Feature 2
    |  +------+
    |  | Yes  |
    |  +------+
    |  +----------+
    |  |   No     |
    |  +----------+
    +---------------- Feature 1

This means trees can't efficiently model diagonal boundaries — they need many splits to approximate them.

Synthetic nonlinear dataset and tree regions

Deeper tree structure example


Now you're ready to attempt the exercises. Switch to the Exercise tab and start coding!

Ready to practice?

Python 3 — Notebook
0/8 solvedSubstack Notes
1
Dataset & Setup

Decision Trees — Student Lab

We start using sklearn in Week 4, but you’ll still implement core pieces from scratch.

Section 0 — Synthetic dataset

We’ll create a non-linear boundary dataset to show how trees fit.

Figure: Synthetic Nonlinear Dataset

Synthetic Nonlinear Dataset

Loading editor...
1

Impurity

2
Gini impurity
1

Section 1 — Impurity

Task 1.1: Gini impurity

DtreeMiniEx.png Gini Impurity Split Comparison

Formula: Gini(S) = 1 - sum_k p_k^2

Binary case: Gini(S) = 1 - (p0^2 + p1^2)

FAANG gotcha: Gini is usually faster than entropy in training because it avoids logarithm computations.

Loading editor...
3
Entropy
1

Task 1.2: Entropy

Formula: Entropy(S) = -sum_k p_k log2(p_k)

Binary case: Entropy(S) = -(p0 log2(p0) + p1 log2(p1))

Loading editor...
2

Best split (decision stump)

4
Evaluate impurity after threshold split
1

Section 2 — Best split (decision stump)

Task 2.1: Evaluate impurity after threshold split

Split rule: go left if X[:,j] <= t else right. Return weighted impurity and information gain.

Loading editor...
5
Find best (feature, threshold)
1

Task 2.2: Find best (feature, threshold)

FAANG gotcha: if a split makes an empty child, skip it.

Loading editor...
6
Train a stump and evaluate

Task 2.3: Train a stump and evaluate

Use best_split to build a stump that predicts majority class on each side.

Loading editor...
3

sklearn DecisionTreeClassifier (sanity check)

7
Train trees with different max_depth

Section 3 — sklearn DecisionTreeClassifier (sanity check)

Task 3.1: Train trees with different max_depth

Loading editor...
4

Failure mode: leakage

8
Create a leaky feature

Section 4 — Failure mode: leakage

Task 4.1: Create a leaky feature

Add a feature that is directly derived from y and watch validation accuracy jump.

Explain: why do trees exploit leakage aggressively?

Explain: why do trees exploit leakage aggressively?
Loading editor...

Need help? Share feedback