KatInterview

Fix a Broken From-Scratch Extra-Trees Forest in NumPy

Machine LearningModel answer
HardModel answerMachine Learningdebuggingextra-treesrandom-forest

Last 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 ValueError about an inhomogeneous shape appears on the breast-cancer dataset and on any dataset that contains a constant column.
  • On a 3-class synthetic dataset, predict returns 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:

  1. Choose max_features distinct candidate features at random.
  2. For each candidate, draw one uniform random threshold between that feature's minimum and maximum within the node.
  3. Score each (feature, threshold) pair by the size-weighted Gini impurity of the two children, and keep the pair with the lowest score.
  4. 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:

  1. It never crashes on numeric data with any label type (integers or strings), including constant features.
  2. predict(X) returns exactly one label per input row.
  3. 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)?