Implement a Gini Decision Tree with Learned NaN Directions

Quick Overview

Implement a Gini classification tree in NumPy that handles NaN features by learning, at every split, which child the missing values should follow. It tests split search over midpoint thresholds, gain computed with missing rows included, strict tie-breaking rules, stopping criteria and a predict function that replays the learned routing.

Implement a Gini Decision Tree with Learned NaN Directions

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: hard

Interview Round: Other

Implement a Gini classification tree over a float matrix `X` that may contain `NaN`. Each split learns a default direction `nan_left` for missing values, which is used when routing rows during training and in `predict`. Write these four functions with NumPy: ```python def gini(y) -> float: ... def best_split_with_missing(X, y): ... # (feature, threshold, nan_left, gain) or None def build_tree(X, y, max_depth=None, min_samples_split=2) -> dict: ... def predict(tree, X) -> np.ndarray: ... ``` Requirements: - `gini(y)` is ${1 - \sum_k p_k^2}$, where $p_k$ is the share of label $k$. An empty array gives `0.0`. Gain is the parent Gini minus the size-weighted child Gini over all rows, with NaN rows placed in their child. - In `best_split_with_missing`, thresholds are midpoints of consecutive unique non-NaN values (skip features with fewer than 2). If the feature has NaNs, try `nan_left=True` then `False`. Otherwise `nan_left = (#<=t >= #>t)`, so the default points at the larger child and ties go left. - Return `(feature, threshold, nan_left, gain)` for the first strictly best gain (lowest feature, then lowest threshold, `True` before `False`). Return `None` if no gain is greater than 0. - Nodes are `{"leaf": True, "value": int}` (the majority label, ties go to the lowest label) or `{"leaf": False, "feature", "threshold", "nan_left", "left", "right"}`. Non-NaN rows with `x <= threshold` go left. - A node becomes a leaf when it is pure, when `n < min_samples_split`, when `depth >= max_depth` (root depth 0; `max_depth=None` means no limit), or when no split exists. `predict` returns an `int` array. Example: ```python nan = float("nan") X = [[1.0], [2.0], [3.0], [nan], [nan], [4.0]] y = [0, 0, 1, 0, 0, 1] best_split_with_missing(X, y) # (0, 2.5, True, 0.4444...) tree = build_tree(X, y) # {"leaf": False, "feature": 0, "threshold": 2.5, "nan_left": True, # "left": {"leaf": True, "value": 0}, "right": {"leaf": True, "value": 1}} predict(tree, [[nan], [3.5], [0.0]]) # array([0, 1, 0]) ``` ```hint Missing rows in the gain Thresholds come from observed values only, but the gain is weighted over all n rows. Treat the NaN rows as one block that joins either the left or the right child. ``` ```hint Tie rules Think about which loop order and which comparison (strict or not, and where the tolerance goes) make the first best candidate win without any extra bookkeeping. ``` ### Constraints & Assumptions - Labels are non-negative integers, and `len(X) == len(y)`. - Use a `1e-12` tolerance when comparing gains. ### What a Strong Answer Covers - Candidate thresholds built from observed values only, with the gain computed over all rows so the NaN block counts toward whichever child it joins. - Scoring both NaN directions when the column has missing values, and the larger-child default (ties left) when it has none. - Tie-breaking that follows from loop order plus a strict, tolerance-based improvement test, with `None` when nothing beats zero gain. - Stopping rules, majority leaves with lowest-label ties, and a `predict` that replays exactly the routing used in training. - The cost of the split search and where it can be made cheaper. ### Follow-up Questions - How would surrogate splits (CART-style) differ from a learned default direction? - How would you handle NaNs in a feature that was never missing at training time? - How would you make the split search scale to large datasets?

Overview: Implement a Gini classification tree in NumPy that handles NaN features by learning, at every split, which child the missing values should follow. It tests split search over midpoint thresholds, gain computed with missing rows included, strict tie-breaking rules, stopping criteria and a predict function that replays the learned routing.

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

Implement a Gini classification tree over a float matrix X that may contain NaN. Each split learns a default direction nan_left for missing values, which is used when routing rows during training and in predict.

Write these four functions with NumPy:

def gini(y) -> float: ...
def best_split_with_missing(X, y): ...  # (feature, threshold, nan_left, gain) or None
def build_tree(X, y, max_depth=None, min_samples_split=2) -> dict: ...
def predict(tree, X) -> np.ndarray: ...

Requirements:

  • gini(y) is 1−∑kpk2{1 - \sum_k p_k^2} , where pkp_k is the share of label kk . An empty array gives 0.0 . Gain is the parent Gini minus the size-weighted child Gini over all rows, with NaN rows placed in their child.
  • In best_split_with_missing , thresholds are midpoints of consecutive unique non-NaN values (skip features with fewer than 2). If the feature has NaNs, try nan_left=True then False . Otherwise nan_left = (#<=t >= #>t) , so the default points at the larger child and ties go left.
  • Return (feature, threshold, nan_left, gain) for the first strictly best gain (lowest feature, then lowest threshold, True before False ). Return None if no gain is greater than 0.
  • Nodes are {"leaf": True, "value": int} (the majority label, ties go to the lowest label) or {"leaf": False, "feature", "threshold", "nan_left", "left", "right"} . Non-NaN rows with x <= threshold go left.
  • A node becomes a leaf when it is pure, when n < min_samples_split , when depth >= max_depth (root depth 0; max_depth=None means no limit), or when no split exists. predict returns an int array.

Example:

nan = float("nan")
X = [[1.0], [2.0], [3.0], [nan], [nan], [4.0]]
y = [0, 0, 1, 0, 0, 1]
best_split_with_missing(X, y)  # (0, 2.5, True, 0.4444...)
tree = build_tree(X, y)
# {"leaf": False, "feature": 0, "threshold": 2.5, "nan_left": True,
#  "left": {"leaf": True, "value": 0}, "right": {"leaf": True, "value": 1}}
predict(tree, [[nan], [3.5], [0.0]])  # array([0, 1, 0])

Constraints & Assumptions

  • Labels are non-negative integers, and len(X) == len(y) .
  • Use a 1e-12 tolerance when comparing gains.

What a Strong Answer Covers Guidance

  • Candidate thresholds built from observed values only, with the gain computed over all rows so the NaN block counts toward whichever child it joins.
  • Scoring both NaN directions when the column has missing values, and the larger-child default (ties left) when it has none.
  • Tie-breaking that follows from loop order plus a strict, tolerance-based improvement test, with None when nothing beats zero gain.
  • Stopping rules, majority leaves with lowest-label ties, and a predict that replays exactly the routing used in training.
  • The cost of the split search and where it can be made cheaper.

Follow-up Questions Guidance

  • How would surrogate splits (CART-style) differ from a learned default direction?
  • How would you handle NaNs in a feature that was never missing at training time?
  • How would you make the split search scale to large datasets?