Best decision-tree split by Gini impurity
Problem
- For each feature, candidate thresholds are midpoints between consecutive distinct sorted values; the left child is
x ≤ t. - Score a split by weighted Gini,(n_L·G_L + n_R·G_R)/n. - Return(feature_index, threshold, weighted_gini)for the minimum. On ties keep the first found when scanning features in ascending order, then thresholds ascending. - ReturnNoneif no feature has two distinct values.
Signature
def best_gini_split(X, y: list) -> tuple[int, float, float] | None: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> close(best_gini_split([[1.0],[2.0],[3.0],[4.0]], [0, 0, 1, 1]), (0, 2.5, 0.0))
True
>>> close(best_gini_split([[1.0, 5.0],[2.0, 6.0],[3.0, 5.0],[4.0, 6.0]], [0, 1, 0, 1]), (1, 5.5, 0.0))
TrueHints
For each feature, candidate thresholds are midpoints between consecutive distinct sorted values.
Score each split by weighted Gini; keep the first minimum (ascending feature, then ascending threshold).
Return None if no feature has two distinct values.
Reference solution
from collections import Counter
import numpy as np
def best_gini_split(X, y):
X = np.asarray(X, float)
n, d = X.shape
def gini(lbls):
if not lbls:
return 0.0
c = Counter(lbls); m = len(lbls)
return 1 - sum((v / m) ** 2 for v in c.values())
best = None
for f in range(d):
vals = sorted(set(X[:, f]))
for a, b in zip(vals, vals[1:]):
t = (a + b) / 2
L = [y[i] for i in range(n) if X[i, f] <= t]
R = [y[i] for i in range(n) if X[i, f] > t]
g = (len(L) * gini(L) + len(R) * gini(R)) / n
if best is None or g < best[2] - 1e-12:
best = (f, t, g)
return bestWhat a strong solution covers
- Correct Gini.
- Midpoint thresholds; deterministic ties.
- Follow-up: O(n log n) per feature with prefix class counts instead of rescanning.
- Discusses entropy vs Gini and min-samples constraints.
Common mistakes
- using raw values as thresholds and putting equal values on both sides
- unweighted child impurity.