Gini Split Search Plus One Regression Gradient Step
Heaps, Sorting & SearchAuto-graded · 15 test casesLast 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 fulllabels_c(float)."split":[j, t]as a list of the chosen column index and threshold, orNoneif 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, andk = 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).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Sorted sweep for the best split
Approach. With binary labels, the impurity of a group is 2p(1-p), so it depends only on the group size and its number of ones. For each column:
- Sort the (value, label) pairs by value.
- Walk through the sorted list, moving one row at a time from the right group to the left group. Keep
left_nandleft_pos; the right counts follow fromn - left_nandtotal_pos - left_pos. - Score a split only when the current value differs from the next one. Equal values cannot be separated by a
<=rule. - The threshold for the gap is the midpoint
value + (next - value) / 2. - Replace the best candidate only on a strictly smaller score. This gives the required tie-break: lowest column, then smallest threshold.
Why it is correct. Any split (j, t) produces a left group that is a prefix of the column's sorted order. Every non-empty proper prefix that ends at a value change is a distinct partition, and a midpoint threshold realizes it. Thresholds inside the same gap give identical partitions, so one representative per gap suffices. Stopping at index n - 2 and skipping equal neighbours ensures neither side is ever empty. If nothing is scored, the answer is None.
The whole-data impurity is computed directly from the fraction of ones.
Part 2: Gradient step
Let the residual be r_i = w . x_i + b - y_i. Differentiating the mean squared error gives:
dL/dw_j = (2/m) * sum_i r_i * x_ijdL/db = (2/m) * sum_i r_i
Each residual is computed from the old parameters, the gradients are accumulated, and the new parameters are old - step_size * gradient. New lists are returned and the inputs are left unchanged. This works unchanged for m = 1 or k = 1.
Complexity
- Part 1: time
O(d * n log n)(one sort and one linear sweep per column), extra spaceO(n). - Part 2: time
O(m * k), extra spaceO(k).
Reference solution
from typing import Dict, List, Optional
def split_and_descend(features_c, labels_c, features_r, targets_r, weights, bias, step_size):
n = len(labels_c)
positives = sum(labels_c)
p = positives / n
impurity = 2.0 * p * (1.0 - p)
best_split = None
best_score = float("inf")
if n > 1:
d = len(features_c[0])
for j in range(d):
ordered = sorted((features_c[i][j], labels_c[i]) for i in range(n))
left_pos = 0
left_n = 0
for k in range(n - 1):
value, label = ordered[k]
left_n += 1
left_pos += label
next_value = ordered[k + 1][0]
if value == next_value:
continue
right_n = n - left_n
right_pos = positives - left_pos
left_p = left_pos / left_n
right_p = right_pos / right_n
score = (left_n * 2.0 * left_p * (1.0 - left_p)
+ right_n * 2.0 * right_p * (1.0 - right_p)) / n
threshold = value + (next_value - value) / 2.0
if score < best_score:
best_score = score
best_split = [j, threshold]
m = len(targets_r)
k_dim = len(weights)
grad_w = [0.0] * k_dim
grad_b = 0.0
for i, row in enumerate(features_r):
error = sum(weights[j] * row[j] for j in range(k_dim)) + bias - targets_r[i]
scale = 2.0 * error / m
for j in range(k_dim):
grad_w[j] += scale * row[j]
grad_b += scale
new_w = [weights[j] - step_size * grad_w[j] for j in range(k_dim)]
new_b = bias - step_size * grad_b
return {"gini": impurity, "split": best_split, "new_w": new_w, "new_b": new_b}