---
title: Best decision-tree split by Gini impurity
url: https://gurkanozkan.ai/learn/coding/mle-best-decision-tree-split-by-gini-impurity-19/
markdown: https://gurkanozkan.ai/learn/coding/mle-best-decision-tree-split-by-gini-impurity-19.md
kind: coding
difficulty: Medium
topics:
  - Decision trees
  - From scratch
json: https://gurkanozkan.ai/api/learn/coding/mle-best-decision-tree-split-by-gini-impurity-19.json
robots: noindex
---

# Best decision-tree split by Gini impurity

- 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. - Return `None` if no feature has two distinct values.

## Signature

```python
def best_gini_split(X, y: list) -> tuple[int, float, float] | None: ...
```

## Examples

Each call and the value it should give.

```python
>>> 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))
True
```

## Hints

1. For each feature, candidate thresholds are midpoints between consecutive distinct sorted values.
2. Score each split by weighted Gini; keep the first minimum (ascending feature, then ascending threshold).
3. Return None if no feature has two distinct values.

## Reference solution

```python
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 best
```

## What 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.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
