Fix a Broken From-Scratch Extra-Trees Forest in NumPy
Machine LearningModel answerLast updated
Debug a NumPy random-split decision-tree ensemble that crashes on constant columns and returns wrong shapes, until it matches scikit-learn's accuracy.
Scenario
You inherit a small NumPy library that implements an Extremely Randomized Trees (Extra-Trees) classifier. Its tests fail in two ways:
- A
ValueErrorabout an inhomogeneous shape appears on the breast-cancer dataset and on any dataset that contains a constant column. - On a 3-class synthetic dataset,
predictreturns an array with the wrong shape.
Even once those errors are gone, you suspect the model is not actually learning.
Algorithm the code is meant to follow
At every node of a tree:
- Choose
max_featuresdistinct candidate features at random. - For each candidate, draw one uniform random threshold between that feature's minimum and maximum within the node.
- Score each (feature, threshold) pair by the size-weighted Gini impurity of the two children, and keep the pair with the lowest score.
- Recurse on both sides. Stop on a pure node, too few samples, or the depth limit.
Each tree is trained on the whole training set (no bootstrap). The forest predicts by averaging the per-tree class-probability vectors and taking the argmax.
Goal
Without redesigning the algorithm or changing the public API (fit, predict, predict_proba), fix the module so that:
- It never crashes on numeric data with any label type (integers or strings), including constant features.
predict(X)returns exactly one label per input row.- Test accuracy lands within a few points of
sklearn.ensemble.ExtraTreesClassifier(n_estimators=50)(about 92% on the synthetic set and about 94% on breast cancer).
Code under test
import numpy as np
class TreeNode:
def __init__(self, feat=None, thr=None, lo_child=None, hi_child=None, probs=None):
self.feat, self.thr = feat, thr
self.lo_child, self.hi_child = lo_child, hi_child
self.probs = probs
def impurity(labels, n_classes):
counts = np.bincount(labels, minlength=n_classes)
return 1.0 - np.sum(counts ** 2)
class RandomSplitTree:
def __init__(self, n_try, min_split=2, depth_limit=None, seed=0):
self.n_try = n_try
self.min_split = min_split
self.depth_limit = depth_limit
self.rng = np.random.default_rng(seed)
def fit(self, X, y, n_classes):
self.n_classes = n_classes
self.root = self._grow(X, y, 0)
return self
def _make_leaf(self, y):
counts = np.bincount(y)
return TreeNode(probs=counts / counts.sum())
def _grow(self, X, y, depth):
if (len(y) < self.min_split
or (self.depth_limit is not None and depth >= self.depth_limit)
or np.all(y == y[0])):
return self._make_leaf(y)
cand = self.rng.choice(X.shape[1], self.n_try)
best = None
for f in cand:
col = X[:, f]
thr = self.rng.uniform(col.min(), col.max())
mask = col < thr
n_lo = mask.sum()
n_hi = len(y) - n_lo
cost = (n_lo * impurity(y[mask], self.n_classes)
+ n_hi * impurity(y[~mask], self.n_classes)) / len(y)
if best is None or cost > best[0]:
best = (cost, f, thr, mask)
_, f, thr, mask = best
return TreeNode(f, thr,
self._grow(X[mask], y[mask], depth + 1),
self._grow(X[~mask], y[~mask], depth + 1))
def proba_for(self, x):
node = self.root
while node.probs is None:
node = node.hi_child if x[node.feat] < node.thr else node.lo_child
return node.probs
class ExtraTreesClassifier:
def __init__(self, n_estimators=50, max_features="sqrt", seed=0, **tree_kw):
self.n_estimators = n_estimators
self.max_features = max_features
self.seed = seed
self.tree_kw = tree_kw
def fit(self, X, y):
X = np.asarray(X, dtype=float)
y = np.asarray(y)
self.classes_, y_enc = np.unique(y, return_inverse=True)
d = X.shape[1]
k = max(1, int(np.sqrt(d))) if self.max_features == "sqrt" else self.max_features
self.trees = [
RandomSplitTree(k, seed=self.seed, **self.tree_kw).fit(X, y_enc, len(self.classes_))
for _ in range(self.n_estimators)
]
return self
def predict_proba(self, X):
X = np.asarray(X, dtype=float)
per_tree = [[t.proba_for(x) for x in X] for t in self.trees]
return np.mean(per_tree, axis=1)
def predict(self, X):
return self.classes_[np.argmax(self.predict_proba(X), axis=1)]
What to deliver
The corrected module, plus a short list of every bug you found: the symptom it produced and the fix you applied.
Hints
Hint 1
Fix the crashes first, then measure accuracy. If it is at or even below chance, something is systematically inverted, not just noisy. Also test small invariants: the impurity of labels [0,0,1,1] should be 0.5, a pure node should give 0, and every leaf's probability vector should have length n_classes and sum to 1.
Hint 2
Compare how the tree is built with how it is queried: which side do samples with value < threshold go to during growth, and which side during prediction? Also check which direction the best-split comparison goes, and what the impurity function does with raw counts versus proportions.
Hint 3
Look for randomness and shape problems: does the feature draw allow repeats, what happens when a feature has min == max in the node, do all trees share the same seed, and which axis is averaged when combining per-tree outputs of shape (n_trees, n_samples, n_classes)?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat this as a two-phase debugging job. First remove the loud failures (exceptions, wrong shapes). Then, because the code runs but still performs near or below chance, check invariants instead of eyeballing the score. The code has eight bugs: three produce crashes or bad shapes, five silently wreck accuracy.
Debugging process
- Shrink the problem. Use about 20 rows, 2 features, and a fixed seed, and print the resulting tree.
- Fix crashes, then measure. After only the crash fixes, a correct forest should be strong; if it sits at chance (about 33% on 3 classes) or below chance on a balanced binary task, a decision is inverted somewhere.
- Unit-check invariants.
impurity([0,0,1,1], 2) == 0.5and a pure node gives0.- Every leaf's probability vector has length
n_classesand sums to 1. - One deep tree should score roughly 100% on its own training data.
- Different trees in the forest should have different structures.
The eight bugs
| # | Location | Problem | Symptom | Fix |
|---|---|---|---|---|
| 1 | impurity | Uses 1 - sum(counts**2) on raw counts | Scores grow with node size, so split ranking is meaningless | Convert to proportions; return 0 for an empty array |
| 2 | _make_leaf | np.bincount(y) has no minlength | Leaves with missing high classes have shorter vectors, so stacking fails with an inhomogeneous-shape error | minlength=self.n_classes |
| 3 | _grow | rng.choice(d, k) samples with replacement | Duplicate candidates, fewer distinct features tried | replace=False |
| 4 | _grow | Constant feature gives uniform(lo, lo), so col < thr is all False | Empty child, then a leaf built from an empty array (0/0), then a crash | Only draw from features with max > min; skip splits that leave a side empty; make a leaf if nothing is usable |
| 5 | _grow | Keeps the split with the highest cost (>) | Always selects the worst split | Use < |
| 6 | proba_for | Growth sends < thr to the lower child, but prediction sends it to the other one | Every sample follows the wrong branch; accuracy falls below chance | Send x[feat] < thr to lo_child |
| 7 | fit (forest) | Every tree receives the same seed | 50 identical trees, so no ensemble benefit | Give each tree its own stream, e.g. default_rng(seed).spawn(n) |
| 8 | predict_proba | np.mean(..., axis=1) | Averages across samples instead of trees, so predict returns one label per tree | Convert to an array and use axis=0 |
Notes on how they interact:
- Bug 6 is the most instructive. It hides behind the crashes, and its signature is accuracy below the chance level on a balanced binary problem.
- Bugs 1 and 5 partially mask each other. Fixing only one can look like "no improvement", which is why checking
impurity([0,0,1,1]) == 0.5beats guessing from the score. - Bug 4 has several layers: the degenerate threshold, the empty child, and the zero-division in the leaf. Guard against all of them, not only the first.
Corrected code
import numpy as np
class TreeNode:
def __init__(self, feat=None, thr=None, lo_child=None, hi_child=None, probs=None):
self.feat, self.thr = feat, thr
self.lo_child, self.hi_child = lo_child, hi_child
self.probs = probs
def impurity(labels, n_classes):
if len(labels) == 0:
return 0.0
p = np.bincount(labels, minlength=n_classes) / len(labels) # 1
return 1.0 - np.sum(p ** 2)
class RandomSplitTree:
def __init__(self, n_try, min_split=2, depth_limit=None, rng=None):
self.n_try = n_try
self.min_split = min_split
self.depth_limit = depth_limit
self.rng = rng if rng is not None else np.random.default_rng()
def fit(self, X, y, n_classes):
self.n_classes = n_classes
self.root = self._grow(X, y, 0)
return self
def _make_leaf(self, y):
counts = np.bincount(y, minlength=self.n_classes) # 2
return TreeNode(probs=counts / counts.sum())
def _grow(self, X, y, depth):
if (len(y) < self.min_split
or (self.depth_limit is not None and depth >= self.depth_limit)
or np.all(y == y[0])):
return self._make_leaf(y)
lo, hi = X.min(axis=0), X.max(axis=0)
usable = np.flatnonzero(hi > lo) # 4
if len(usable) == 0:
return self._make_leaf(y)
k = min(self.n_try, len(usable))
cand = self.rng.choice(usable, k, replace=False) # 3
best = None
for f in cand:
thr = self.rng.uniform(lo[f], hi[f])
mask = X[:, f] < thr
n_lo = mask.sum()
n_hi = len(y) - n_lo
if n_lo == 0 or n_hi == 0:
continue
cost = (n_lo * impurity(y[mask], self.n_classes)
+ n_hi * impurity(y[~mask], self.n_classes)) / len(y)
if best is None or cost < best[0]: # 5
best = (cost, f, thr, mask)
if best is None:
return self._make_leaf(y)
_, f, thr, mask = best
return TreeNode(f, thr,
self._grow(X[mask], y[mask], depth + 1),
self._grow(X[~mask], y[~mask], depth + 1))
def proba_for(self, x):
node = self.root
while node.probs is None:
node = node.lo_child if x[node.feat] < node.thr else node.hi_child # 6
return node.probs
class ExtraTreesClassifier:
def __init__(self, n_estimators=50, max_features="sqrt", seed=0, **tree_kw):
self.n_estimators = n_estimators
self.max_features = max_features
self.seed = seed
self.tree_kw = tree_kw
def fit(self, X, y):
X = np.asarray(X, dtype=float)
y = np.asarray(y)
self.classes_, y_enc = np.unique(y, return_inverse=True)
d = X.shape[1]
k = max(1, int(np.sqrt(d))) if self.max_features == "sqrt" else self.max_features
rngs = np.random.default_rng(self.seed).spawn(self.n_estimators) # 7
self.trees = [RandomSplitTree(k, rng=r, **self.tree_kw)
.fit(X, y_enc, len(self.classes_)) for r in rngs]
return self
def predict_proba(self, X):
X = np.asarray(X, dtype=float)
per_tree = np.array([[t.proba_for(x) for x in X] for t in self.trees])
return per_tree.mean(axis=0) # 8
def predict(self, X):
return self.classes_[np.argmax(self.predict_proba(X), axis=1)]
Verification and trade-offs
- Run a stratified 70/30 split with 50 trees. The fixed model should land within a point or two of scikit-learn (about 92% on the 3-class set, about 94% on breast cancer). Repeat with a few appended constant columns and with string labels to confirm there are no crashes.
- Add regression tests for each invariant above, plus one asserting that two trees in the forest differ.
- Complexity: each node costs O(n_try * n) to evaluate splits, so a tree is about O(n_try * n * depth), and the forest multiplies by the number of trees. Prediction is O(trees * depth) per sample; the per-sample Python loop is the main speed limiter, and vectorizing traversal would be the next optimization.
- Design note: random thresholds trade a little bias for lower variance and much cheaper split search than sorting-based greedy splits, which is why many decorrelated trees are essential. Bug 7 removes exactly that benefit.
Common mistakes
- Stopping after the crash fixes and accepting chance-level accuracy.
- Fixing the constant-column crash only in the leaf (for example with a 0/0 guard) without preventing the empty split.
- Using
seed + iincorrectly or reusing one generator object across trees in a way that is not reproducible. - Changing the algorithm (bootstrap sampling, sorted thresholds) instead of repairing it.