KatInterview

Gini Split Search Plus One Regression Gradient Step

Heaps, Sorting & SearchAuto-graded · 15 test cases
MediumAuto-gradedHeaps, Sorting & Searchsortingprefix-sweepgini-impurity

Last updated

Sweep sorted feature values to find the lowest weighted-Gini binary split, and apply one MSE gradient descent update for linear regression.

Write one function that handles two independent sub-tasks and returns both results in a dictionary.

Part 1: Best split for a binary classifier

You get a feature matrix features_c with n rows and d columns (floats) and a label list labels_c of length n with values in {0, 1}.

Gini impurity. For a group of labels where p is the fraction of ones, the impurity is 2 * p * (1 - p).

Splits. A split is a pair (j, t) of a column index j and a threshold t.

  • The left group holds the rows with features_c[i][j] <= t.
  • The right group holds the rows with features_c[i][j] > t.
  • A split is valid only if both groups are non-empty.

Score. The score of a split is the weighted impurity

(n_left * G(left) + n_right * G(right)) / n

where G is the Gini impurity above. Lower is better.

Candidate thresholds. For each column, sort its values. Look at each pair of neighbouring sorted entries whose values a < b differ. The candidate threshold for that gap is a + (b - a) / 2.0. Equal neighbouring values give no candidate. Compute the score of each candidate from the counts of the left and right groups and their positives.

Choosing the winner. Take the candidate with the strictly smallest score. Scan columns in increasing index order and, within a column, gaps in increasing value order. A later candidate replaces the current best only if its score is strictly smaller. So ties go to the lowest column index, then the smallest threshold.

If no valid candidate exists (for example n = 1, or every column is constant), the split result is None.

You must also report the Gini impurity of the whole labels_c list.

Part 2: One gradient descent step for linear regression

You get features_r (m rows by k columns), real targets targets_r (length m), current weights weights (length k), a scalar bias, and a learning rate step_size.

The model predicts weights . x_i + bias. The loss is the mean squared error

L = (1/m) * sum_i (weights . x_i + bias - targets_r[i])^2

Perform exactly one gradient descent update:

  • new_weights[j] = weights[j] - step_size * dL/dweights[j]
  • new_bias = bias - step_size * dL/dbias

Compute every residual from the old parameters, and do not modify the input lists.

Return value

Return a dictionary with exactly these keys:

  • "gini": impurity of the full labels_c (float).
  • "split": [j, t] as a list of the chosen column index and threshold, or None if no valid split exists.
  • "new_w": list of updated weights.
  • "new_b": updated bias (float).

Constraints

  • 1 <= n <= 2 * 10^4, 1 <= d <= 50; labels are 0 or 1.
  • 1 <= m, and k = len(weights) >= 1; the single-sample and single-feature cases must work.
  • Aim for roughly O(n * d * log n) for Part 1; trying every threshold with a full rescan is too slow.
  • Constant labels and constant columns must be handled without error.

Examples

Example 1

Input: split_and_descend([[1], [2], [3], [4]], [0, 0, 1, 1], [[1], [2]], [1, 2], [0], 0, 0.1)

Output: {'gini': 0.5, 'split': [0, 2.5], 'new_w': [0.5], 'new_b': 0.30000000000000004}

Example 2

Input: split_and_descend([[1, 2], [2, 1], [3, 4]], [0, 1, 1], [[1, 2], [3, 4]], [2, 5], [0.5, -0.5], 1, 0.01)

Output: {'gini': 0.4444444444444445, 'split': [0, 1.5], 'new_w': [0.65, -0.29000000000000004], 'new_b': 1.06}

Hints

Hint 1

For binary labels, impurity depends only on the count of ones in a group. Sort a column once, then move rows from right to left one at a time while maintaining running counts.

Hint 2

Only gaps between distinct neighbouring values are candidate thresholds, because a `<=` rule cannot separate equal values. Skip the last position so the right side is never empty.

Hint 3

For the gradient, define residual = prediction - target using the old parameters. Then dL/dw_j = (2/m) * sum(residual * x_ij) and dL/db = (2/m) * sum(residual).