SDE & MLE Prep

Decision Tree Split (Gini)

Key idea: for each feature, sort values and sweep thresholds while maintaining left/right class counts → O(N log N) per feature instead of O(N²).

import numpy as np

def gini(counts):
    n = counts.sum()
    return 0.0 if n == 0 else 1.0 - ((counts / n) ** 2).sum()

def best_split(X, y, n_classes):
    best = (np.inf, None, None)                        # (weighted gini, feature, threshold)
    N = len(y)
    for f in range(X.shape[1]):
        order = np.argsort(X[:, f])
        xs, ys = X[order, f], y[order]
        left, right = np.zeros(n_classes), np.bincount(ys, minlength=n_classes).astype(float)
        for i in range(1, N):
            left[ys[i - 1]] += 1; right[ys[i - 1]] -= 1
            if xs[i] == xs[i - 1]:
                continue                               # can't split between equal values
            score = (i * gini(left) + (N - i) * gini(right)) / N
            if score < best[0]:
                best = (score, f, (xs[i] + xs[i - 1]) / 2)
    return best

X = np.array([[2.0, 1.0], [3.0, 5.0], [1.0, 2.0], [8.0, 1.5], [9.0, 4.0], [7.0, 3.0]])
y = np.array([0, 0, 0, 1, 1, 1])
score, f, t = best_split(X, y, 2)
assert f == 0 and 3 < t < 7 and score == 0
print("ok feature", f, "threshold", t)