Implement CART Surrogate Splits to Route Missing Values at Prediction Time

Quick Overview

Implement a Gini CART classifier that stores ranked surrogate splits at each internal node and uses them to route rows with missing values at prediction time. It tests split search, surrogate agreement measured against the majority-direction baseline, tie-breaking and fallback routing.

Implement CART Surrogate Splits to Route Missing Values at Prediction Time

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: hard

Interview Round: Other

Implement a Gini CART classifier that trains on complete data (`X`, `y`) and stores ranked surrogate splits at every internal node. At prediction time, a row with `NaN` in a node's primary feature is routed through that node's surrogates. Write these four functions: ```python def best_split(X, y): ... def find_surrogates(X, feature, threshold, max_surrogates=5): ... def build_tree(X, y, max_depth=None, min_samples_split=2, max_surrogates=5): ... def predict(tree, X): ... ``` They must follow these rules: - `best_split`: thresholds are midpoints of consecutive unique values, and `x <= t` goes left. Return `(feature, threshold, gain)` for the split with the largest Gini gain, breaking ties by lowest feature and then lowest threshold. Return `None` if no split has a gain above `1e-12`. - `find_surrogates`: for each feature other than the primary, find the midpoint and direction that send the most rows to the same side as the primary split. Direction `1` means `x <= t` goes left, and `-1` means `x <= t` goes right. Ties go to the lowest threshold, then to `1` before `-1`. - Keep a surrogate only if its match count is greater than the size of the primary split's larger side. Return tuples `(feature, threshold, direction, agreement)`, where agreement is the match count divided by `n`, sorted by agreement descending and then by feature index, and truncated to `max_surrogates`. - `build_tree` returns nested dicts. A leaf has `is_leaf=True`, `value` and `n_samples`, where `value` is the majority label (smallest label on ties). An internal node has `is_leaf=False`, `feature`, `threshold`, `surrogates`, `default_left`, `n_samples`, `left` and `right`. Its surrogates are computed from the rows that reach the node, and `default_left` is true when the left child has at least as many rows as the right. A node becomes a leaf when it is pure, when `depth >= max_depth` (the root is at depth 0), when `n < min_samples_split`, or when there is no split. - `predict` returns an `int` array. When a row's primary feature is `NaN`, use the first surrogate whose feature is present. If every surrogate feature is missing too, follow `default_left`. Example: ```python nan = float("nan") X = [[1,10,8],[2,20,7],[3,30,6],[4,50,5], [5,40,4],[6,60,3],[7,70,2],[8,80,1]] y = [0,0,0,0,1,1,1,1] best_split(X, y) # (0, 4.5, 0.5) find_surrogates(X, 0, 4.5) # [(2, 4.5, -1, 1.0), (1, 35.0, 1, 0.875)] predict(build_tree(X, y), [[nan, 15.0, 2.0]]) # [1] (routed by feature 2, reversed) ``` ```hint Two directions from one count For a candidate cut, the rows a reversed surrogate agrees on are exactly the rows the forward version disagrees on. One count gives you both. ``` ```hint Ties come from scan order Visit thresholds in increasing order, try direction 1 before -1, and replace the current best only on a strictly larger value. Gains are floats, so compare them with a small tolerance. The example root has two features that split perfectly. ``` ```hint NaN comparisons Check what `nan <= t` evaluates to in NumPy before relying on a plain comparison in `predict`. ``` ### Constraints & Assumptions - Training data contains no missing values. Only the inputs to `predict` may contain `NaN`. - Labels are integers, and `predict` returns them as an `int` array. - `max_depth` is `None` or a non-negative integer. - On complete data, the primary splits use the same rules as scikit-learn's `DecisionTreeClassifier` (Gini gain, midpoint thresholds, `x <= t` to the left). ### What a Strong Answer Covers - A primary split search with midpoint thresholds, `<=` routing, the positive-gain requirement and the stated tie order - A surrogate search over both directions at every threshold, with its tie order and the filter against the majority-direction baseline - Ranking by agreement, agreement as a fraction of the node's rows, and truncation to `max_surrogates` - Tree dicts with the required keys, surrogates computed from each node's own rows, and the stopping rules - Prediction that falls back from the primary feature to surrogates in rank order and then to `default_left`, plus the cost of the search ### Follow-up Questions - How would you build surrogates when the training data itself has missing values? - Why compare surrogates against the majority-direction rule, and what is rpart's adjusted agreement? - How would you bring the primary and surrogate searches down to `O(n log n)` per feature at each node? - On complete data, where can this tree and scikit-learn's `DecisionTreeClassifier` still differ?

Overview: Implement a Gini CART classifier that stores ranked surrogate splits at each internal node and uses them to route rows with missing values at prediction time. It tests split search, surrogate agreement measured against the majority-direction baseline, tie-breaking and fallback routing.

PracHub logo
General
Nov 25, 2026
hardMachine Learning EngineerOtherMachine Learning
0
0

Implement a Gini CART classifier that trains on complete data (X, y) and stores ranked surrogate splits at every internal node. At prediction time, a row with NaN in a node's primary feature is routed through that node's surrogates. Write these four functions:

def best_split(X, y): ...
def find_surrogates(X, feature, threshold, max_surrogates=5): ...
def build_tree(X, y, max_depth=None, min_samples_split=2, max_surrogates=5): ...
def predict(tree, X): ...

They must follow these rules:

  • best_split : thresholds are midpoints of consecutive unique values, and x <= t goes left. Return (feature, threshold, gain) for the split with the largest Gini gain, breaking ties by lowest feature and then lowest threshold. Return None if no split has a gain above 1e-12 .
  • find_surrogates : for each feature other than the primary, find the midpoint and direction that send the most rows to the same side as the primary split. Direction 1 means x <= t goes left, and -1 means x <= t goes right. Ties go to the lowest threshold, then to 1 before -1 .
  • Keep a surrogate only if its match count is greater than the size of the primary split's larger side. Return tuples (feature, threshold, direction, agreement) , where agreement is the match count divided by n , sorted by agreement descending and then by feature index, and truncated to max_surrogates .
  • build_tree returns nested dicts. A leaf has is_leaf=True , value and n_samples , where value is the majority label (smallest label on ties). An internal node has is_leaf=False , feature , threshold , surrogates , default_left , n_samples , left and right . Its surrogates are computed from the rows that reach the node, and default_left is true when the left child has at least as many rows as the right. A node becomes a leaf when it is pure, when depth >= max_depth (the root is at depth 0), when n < min_samples_split , or when there is no split.
  • predict returns an int array. When a row's primary feature is NaN , use the first surrogate whose feature is present. If every surrogate feature is missing too, follow default_left .

Example:

nan = float("nan")
X = [[1,10,8],[2,20,7],[3,30,6],[4,50,5],
     [5,40,4],[6,60,3],[7,70,2],[8,80,1]]
y = [0,0,0,0,1,1,1,1]
best_split(X, y)            # (0, 4.5, 0.5)
find_surrogates(X, 0, 4.5)  # [(2, 4.5, -1, 1.0), (1, 35.0, 1, 0.875)]
predict(build_tree(X, y), [[nan, 15.0, 2.0]])  # [1]  (routed by feature 2, reversed)

Constraints & Assumptions

  • Training data contains no missing values. Only the inputs to predict may contain NaN .
  • Labels are integers, and predict returns them as an int array.
  • max_depth is None or a non-negative integer.
  • On complete data, the primary splits use the same rules as scikit-learn's DecisionTreeClassifier (Gini gain, midpoint thresholds, x <= t to the left).

What a Strong Answer Covers Guidance

  • A primary split search with midpoint thresholds, <= routing, the positive-gain requirement and the stated tie order
  • A surrogate search over both directions at every threshold, with its tie order and the filter against the majority-direction baseline
  • Ranking by agreement, agreement as a fraction of the node's rows, and truncation to max_surrogates
  • Tree dicts with the required keys, surrogates computed from each node's own rows, and the stopping rules
  • Prediction that falls back from the primary feature to surrogates in rank order and then to default_left , plus the cost of the search

Follow-up Questions Guidance

  • How would you build surrogates when the training data itself has missing values?
  • Why compare surrogates against the majority-direction rule, and what is rpart's adjusted agreement?
  • How would you bring the primary and surrogate searches down to O(n log n) per feature at each node?
  • On complete data, where can this tree and scikit-learn's DecisionTreeClassifier still differ?