Gini Impurity

~12 mincode completion

Implement gini_impurity(counts) where counts is an array of class counts (not probabilities). Convert to proportions first.

Examples

Pure node: Gini = 0

Input
gini_impurity([10, 0])
Output
0

50/50 binary split: Gini = 0.5

Input
gini_impurity([5, 5])
Output
0.5

3/1 split: Gini = 0.375

Input
gini_impurity([3, 1])
Output
0.375

Hints

Hint 1

Sum with , and check which axis you are summing over.

Hint 2

Do not forget to convert counts to probs. That step is easy to skip.

Requirements

  • counts: 1D array of non-negative integer class counts.

  • Return Gini impurity in [0, 0.5].

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~12 min

8 employers weight this skill

2 health and bio companies, 2 quant funds, 2 enterprise vendors, 1 AI product company, 1 frontier lab. Top match scores 87.

Python
import numpy as np

def gini_impurity(counts: np.ndarray) -> float:
    """
    Compute the Gini impurity from class counts.

    Args:
        counts: 1D array of non-negative integer class counts.

    Returns:
        Gini impurity in [0, 0.5].
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.