Problems
Loading...
1 / 1

Compute Gini Impurity for a Split

Classic ML
Medium

Given labels from left and right child nodes after a binary split, compute the weighted Gini impurity of the split.

Gini impurity is a fundamental measure used in decision trees to evaluate the quality of a split. It quantifies how "impure" or mixed the classes are in a node, with 0 being perfectly pure (all same class) and higher values indicating more mixture.

Gini Impurity Formulas:

For a single node:

Gini(t)=1i=1Cpi2\mathrm{Gini}(t) = 1 - \sum_{i=1}^{C} p_i^{2}

For a weighted split:

Ginisplit=NLNGini(tL)+NRNGini(tR)\mathrm{Gini}_{\text{split}} = \frac{N_{L}}{N} \cdot \mathrm{Gini}(t_{L}) + \frac{N_{R}}{N} \cdot \mathrm{Gini}(t_{R})

Where pi is the proportion of class i, NL,NR are left/right child sizes, and N=NL+NR.

Function Arguments

  • y_left: array-like - Class labels in left child node
  • y_right: array-like - Class labels in right child node
Loading visualization...

Examples

Input: y_left=[0,0,0], y_right=[1,1,1]

Output: 0.0

Input: y_left=[0,1], y_right=[0,1]

Output: 0.5

Hint 1

Use np.unique() with return_counts=True to get class frequencies.

Hint 2

Handle empty nodes by returning 0 impurity (perfectly pure by convention).

Hint 3

Weight each child's Gini by its proportion of total samples.

Requirements

  • Return single float value in range [0, 1]
  • Handle empty child nodes (return 0 impurity for empty nodes)
  • Support multi-class problems (not just binary)
  • Use vectorized operations where possible
  • Weight by the number of samples in each child

Constraints

  • Total samples ≤ 1e6; NumPy only
  • Time limit: 100ms; Memory: 64MB
Try Similar Problems