CD0030 Gini Split From Scratch

Mode B · Build & Trace 30 Min NumPy + sklearn 4 NumPy Blanks

Quant research teams that fit gradient-boosted trees on market features spend most of their training time inside one routine, the per-feature split search, which open-source learners such as Microsoft’s LightGBM rebuild around histograms for speed. This screen (reported by candidates from several quant and applied-AI loops) asks you to write the exact version of that routine by hand. You implement best_split for one continuous feature in NumPy, and no tree library may be called inside the function.

The column x has shape (m,) and the labels y are integers in \{0, \ldots, C - 1\}. Your function returns the threshold t (left child: x \leq t) and its expected information gain under the Gini criterion 1 - \sum_c p_c^2, or (None, 0.0) when no split exists. The interviewer grades three things. Candidates must be midpoints of sorted unique values rather than observed values. The scan must stay at O(m \log m) with no Python loop over classes. Degenerate columns must be handled honestly.

Complete the 4 missing operations in the skeleton below and trace the array shape after each line. Then verify your routine against a hand-computed two-threshold fixture and cross-check the threshold and gain with a depth-1 sklearn.tree.DecisionTreeClassifier on a toy dataset.

Skeleton Code (Fill Blanks 1-4):

01  import numpy as np
02
03
04  def gini(counts: np.ndarray) -> np.ndarray:
05      """Gini impurity from class counts of shape (..., C)."""
06      # TODO (Blank 2): 1 - sum_c p_c^2 over the class axis only,
07      #                 vectorized over any leading axes (no class loop)
08      impurity = ...
09      return impurity
10
11
12  def best_split(x, y, n_classes, min_samples_split=2):
13      """Best Gini threshold for one feature (left child: x <= threshold).
14      Returns (threshold, gain), or (None, 0.0) when no split exists."""
15      m = len(x)
16      # TODO (Blank 1): candidate thresholds, shape (K,), ascending
17      candidates = ...
18      # TODO (Blank 4): guard contract, return (None, 0.0) when this node
19      #                 or this column cannot be split
20      ...
21      order = np.argsort(x, kind="stable")
22      x_sorted, y_sorted = x[order], y[order]                     # (m,)
23      parent_counts = np.bincount(y_sorted, minlength=n_classes)  # (C,)
24      parent_gini = gini(parent_counts)
25      # TODO (Blank 3): weighted Gini gain of all K candidates in one
26      #                 vectorized pass (no Python loop), shape (K,);
27      #                 best = argmax index, ties go to the lowest threshold
28      gains = ...
29      best = ...
30      return float(candidates[best]), float(gains[best])
Operator contract for best_split: input columns x and y of shape (m,) flow through a question-marked candidate step, a provided argsort, a question-marked Gini gain step, and a question-marked argmax step to an output pair of threshold and gain; below, boxes list the guard contract, the O(m log m) budget, and the two test oracles

Figure 1: the input and output contract is fixed and the sort is provided, while the question-marked steps between them are yours to write in plain NumPy.

Interactive NumPy Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and run the fixture and sklearn checks.

Open in Colab ↗
Progressive Hints (Free · Zero Spoilers)
1Inspection Checklist (Where to Look)

(1) Candidate Set: A useful threshold must change the partition. Count how many distinct partitions x <= t can produce, and make sure no candidate leaves a child empty.
(2) Impurity on Counts: The helper receives class counts, both as one (C,) row and as a (K, C) table. Reduce over the class axis only.
(3) Scan Budget: Count how many full passes over the m rows your scan makes. The budget is one sort plus a constant number of linear passes, with no Python loop.
(4) Degenerate Inputs: List the inputs for which no honest threshold exists, and return (None, 0.0) for them before anything divides or indexes.

2Visual Review Map (Figure 2)
Shape trace for best_split: the top row marks the target shape of Blank 1 as (K,) and a question-marked Blank 4 early exit before the provided sort and the parent class counts of shape (C,); the bottom row shows question-marked target shapes for child counts (K, C), child Gini (K,), gains (K,), the best index, and the output pair

Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shapes it must produce; writing the operations that reach them is the exercise.

3Interviewer Nudge & Line Focus

Pin the input shape, output shape, and failure inputs of each blank before writing the NumPy call:

Blank 1 (Candidate Thresholds): For x = [2, 2, 5, 9], which thresholds produce genuinely different partitions under x <= t, and how many are there? If you used t = 9, what size would the right child have when you later divide by it?
Blank 2 (Gini on Counts): The helper is called once with (C,) for the parent and once per side with (K, C) for every candidate. Which axis must each row be normalized over, and what does a reduction without an axis argument return for the table case?
Blank 3 (One-Pass Scan): After sorting, which rows belong to the left child of the k-th candidate? If you had running class counts down the sorted order, how would you read off every left child at once, and how would you get the right child without rescanning? When two gains tie to the last bit, which index does your selection return?
Blank 4 (Guard Contract): List every input where the scan would index an empty array or reduce over zero candidates, plus the input where every gain is exactly 0. In which order must the checks run so none of them can itself raise?
Answer
Login to view more content
Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *