Implement a decision tree classifier from scratch
Written by the mlprep team · Updated
Implement a decision tree classifier from scratch in Python. Use information gain (entropy) to choose splits. Support both categorical and continuous features. Walk me through the recursive structure and how you'd prevent overfitting.
A decision tree recursively partitions the feature space by asking yes/no questions. At each node, it finds the split that maximally reduces uncertainty about the label.
Core implementation#
import numpy as np
from collections import Counter
class Node:
def __init__(self, feature=None, threshold=None, left=None,
right=None, value=None):
self.feature = feature # index of feature to split on
self.threshold = threshold # threshold for the split
self.left = left # left subtree (feature <= threshold)
self.right = right # right subtree (feature > threshold)
self.value = value # class prediction (leaf nodes only)
class DecisionTree:
def __init__(self, max_depth=10, min_samples_split=2,
min_samples_leaf=1):
self.max_depth = max_depth
self.min_samples_split = min_samples_split
self.min_samples_leaf = min_samples_leaf
self.root = None
def fit(self, X, y):
self.n_classes = len(np.unique(y))
self.root = self._build_tree(X, y, depth=0)
return self
def predict(self, X):
return np.array([self._traverse(x, self.root) for x in X])
def _build_tree(self, X, y, depth):
n_samples = len(y)
# Stopping conditions
if (depth >= self.max_depth or
n_samples < self.min_samples_split or
len(np.unique(y)) == 1):
return Node(value=self._majority_class(y))
# Find best split
best_feature, best_threshold, best_gain = self._best_split(X, y)
if best_gain <= 0:
return Node(value=self._majority_class(y))
# Split data
left_mask = X[:, best_feature] <= best_threshold
right_mask = ~left_mask
# Check min_samples_leaf
if (left_mask.sum() < self.min_samples_leaf or
right_mask.sum() < self.min_samples_leaf):
return Node(value=self._majority_class(y))
# Recurse
left_subtree = self._build_tree(X[left_mask], y[left_mask], depth + 1)
right_subtree = self._build_tree(X[right_mask], y[right_mask], depth + 1)
return Node(feature=best_feature, threshold=best_threshold,
left=left_subtree, right=right_subtree)
def _best_split(self, X, y):
n_samples, n_features = X.shape
best_gain = -1
best_feature = None
best_threshold = None
parent_entropy = self._entropy(y)
for feature_idx in range(n_features):
# Get unique thresholds (midpoints between sorted unique values)
values = np.sort(np.unique(X[:, feature_idx]))
if len(values) <= 1:
continue
thresholds = (values[:-1] + values[1:]) / 2
for threshold in thresholds:
left_mask = X[:, feature_idx] <= threshold
right_mask = ~left_mask
if left_mask.sum() == 0 or right_mask.sum() == 0:
continue
# Information gain
n_left = left_mask.sum()
n_right = right_mask.sum()
gain = parent_entropy - (
(n_left / n_samples) * self._entropy(y[left_mask]) +
(n_right / n_samples) * self._entropy(y[right_mask])
)
if gain > best_gain:
best_gain = gain
best_feature = feature_idx
best_threshold = threshold
return best_feature, best_threshold, best_gain
def _entropy(self, y):
counts = np.bincount(y)
probs = counts[counts > 0] / len(y)
return -np.sum(probs * np.log2(probs))
def _majority_class(self, y):
return Counter(y).most_common(1)[0][0]
def _traverse(self, x, node):
if node.value is not None:
return node.value
if x[node.feature] <= node.threshold:
return self._traverse(x, node.left)
return self._traverse(x, node.right)How it works step by step#
-
Entropy measures class impurity: H(S) = -Σ pᵢ log₂(pᵢ). A pure node (one class) has entropy 0. A uniform distribution has maximum entropy.
-
Information gain = parent entropy - weighted average of children's entropy. We want the split that reduces entropy the most.
-
Greedy search: for each feature, try all possible thresholds (midpoints between sorted values). Pick the (feature, threshold) pair with highest information gain.
-
Recurse: split the data and build subtrees for left (≤ threshold) and right (> threshold).
-
Stop when: max depth reached, not enough samples, or all samples are the same class.
Complexity analysis#
- Building: O(n × d × n log n) per node (n samples, d features, sorting)
- Total: O(n² × d × log n) in the worst case (depth log n, each level processes all n samples)
- Prediction: O(depth) = O(log n) for balanced tree, O(n) worst case
Preventing overfitting#
| Parameter | What it does | Effect |
|-----------|-------------|--------|
| max_depth | Limits tree depth | Most important — deep trees memorize |
| min_samples_split | Minimum samples to attempt a split | Prevents splitting tiny groups |
| min_samples_leaf | Minimum samples in each leaf | Ensures leaves have enough support |
| Post-pruning | Remove branches that don't improve validation loss | More principled but more complex |
Gini impurity alternative#
Gini is faster to compute (no log) and works almost identically in practice:
def _gini(self, y):
counts = np.bincount(y)
probs = counts[counts > 0] / len(y)
return 1 - np.sum(probs ** 2)Gini and entropy produce nearly identical trees. Entropy slightly favors balanced splits; Gini slightly favors isolating the largest class. In practice, the difference is negligible.
Interview red flags#
- Testing every unique value as a threshold by re-sorting at every candidate, instead of sorting once per feature per node.
- Recursing without stopping conditions (max depth, minimum samples per split or leaf), which grows a tree that memorizes the training set.
- Computing information gain without weighting each child's entropy by its share of samples.
- Leaving out the leaf prediction rule or the handling of an empty or pure node.
Good implementation. Now: what's the connection between this single decision tree and a random forest? What does the "random" in random forest actually refer to, and why does it help?
A random forest builds many decision trees and averages their predictions. The "random" refers to two sources of randomness that make the trees diverse:
1. Bootstrap sampling (bagging)#
Each tree is trained on a random subset of the training data, sampled with replacement. A dataset of n rows produces n bootstrap samples, but ~37% of rows are left out of any given tree (out-of-bag samples).
def _bootstrap_sample(self, X, y):
n = len(y)
indices = np.random.choice(n, size=n, replace=True)
return X[indices], y[indices]2. Random feature subsets#
At each split, instead of considering all d features, only consider a random subset of size √d (classification) or d/3 (regression). This is the critical difference — it decorrelates the trees.
def _best_split_random_forest(self, X, y):
n_features = X.shape[1]
# Only consider a random subset of features
feature_subset = np.random.choice(
n_features, size=int(np.sqrt(n_features)), replace=False
)
# Find best split only among these features
...Why randomness helps#
Without random features: if one feature is very strong, every tree splits on it first. All trees are nearly identical. Averaging identical predictions doesn't help — you get the same overfitting as a single tree.
With random features: trees are forced to use different features, learning different patterns. Some trees will be weaker individually, but their errors are uncorrelated. When you average uncorrelated predictions, the variance drops proportional to 1/n_trees while bias stays the same.
This is the bias-variance tradeoff of ensembles:
- Each tree: low bias (deep, flexible), high variance (overfits)
- Average of many decorrelated trees: low bias (still flexible), low variance (individual errors cancel)
The math: if each tree has variance σ² and pairwise correlation ρ, the ensemble variance is:
Var(ensemble) = ρσ² + (1-ρ)σ²/n_trees
Reducing ρ (via random features) directly reduces ensemble variance. This is why random forests almost never overfit when you add more trees — the second term approaches zero.
The key takeaway unlocks after you reveal an expert answer.
Key Takeaway
A decision tree greedily finds the (feature, threshold) split that maximally reduces entropy at each node. Information gain = parent entropy - weighted children entropy. Prevent overfitting with max_depth, min_samples_split, and min_samples_leaf. Random forests average many decorrelated trees — each trained on bootstrap samples with random feature subsets at each split — reducing variance without increasing bias.
Follow-up Questions to Test Yourself
Interviewers often pivot here once you cover the core concept.
- How would you modify this implementation to handle missing values — what does XGBoost do differently from sklearn's approach?
- Implement feature importance computation from a trained tree — both impurity-based and permutation-based methods.
- Why do gradient-boosted trees (XGBoost, LightGBM) use shallow trees (depth 3-8) while random forests use deep trees? What's the theoretical reason?
How confident do you feel explaining this?
Track your understanding or flag it to revisit before your next loop.
Related Questions
Implement k-nearest neighbors with efficient distance computation
Implement scaled dot-product attention from scratch
Implement Word2Vec (skip-gram) training from scratch
How do decision trees split? Walk me through Gini impurity vs information gain.