Compute Gini Impurity for a Split
Compute Gini Impurity for a Split
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)=1−i=1∑Cpi2For a weighted split:
Ginisplit=NNL⋅Gini(tL)+NNR⋅Gini(tR)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 nodey_right: array-like- Class labels in right child node
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
Log in to take notes on this problem
Accepts: array
Accepts: array
Compute Gini Impurity for a Split
Compute Gini Impurity for a Split
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)=1−i=1∑Cpi2For a weighted split:
Ginisplit=NNL⋅Gini(tL)+NNR⋅Gini(tR)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 nodey_right: array-like- Class labels in right child node
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
Log in to take notes on this problem
Accepts: array
Accepts: array