📘
Gini Impurity
EasyDecision Trees
Compute the Gini impurity of a set of labels.
Gini impurity measures how often a randomly chosen element would be incorrectly classified:
Gini=1−∑k=1Kpk2
where pk is the proportion of class k in the dataset.
A pure node (all same class) has Gini = 0. Maximum impurity for binary classification is 0.5.
Return the Gini impurity rounded to 4 decimal places.
Example:
Input:
labels = [1, 1, 0, 0, 0]
Output:
0.48
Reasoning:
- First, we calculate the proportion of each class in the dataset: p0=53 for class 0 and p1=52 for class 1.
- Then, we apply the Gini impurity formula: Gini=1−(p02+p12)=1−((53)2+(52)2)
- The calculation yields: Gini=1−(259+254)=1−2513=2512=0.48
- The final output is the Gini impurity rounded to 4 decimal places, which is 0.4800, but since it's already in the correct format, the output is 0.48
Constraints:
- labels is a list of class labels (integers or strings)
- Return a float rounded to 4 decimal places
- Handle empty lists (return 0.0)
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.