#137Decision tree — node impurity (Gini & entropy)EasyDecision TreesAsked atBosch · Samsung R&D
Decision tree — node impurity (Gini & entropy)
Background
When a decision tree decides where to split, it measures how mixed a node's labels are. Two classic measures are Gini impurity and entropy. A node with a single class is pure (impurity 0); a node with an even mix of classes is maximally impure. Every CART/ID3 split is chosen to reduce this impurity the most.
Problem statement
Implement node_impurity(labels) returning the tuple (gini, entropy) for the class labels at a node. With the fraction of samples in class :
Entropy is in bits. Use the convention .
Input
labels— an array-like of class labels of any hashable type (ints, strings, booleans).
Output
- A tuple
(gini, entropy)of twofloats.
Examples
Example 1
Input: labels = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0]
Output: (0.48, 0.9709505944546686)
Explanation: 6 of 10 are class 1 and 4 are class 0, so . Gini and Entropy bits.
Constraints
- Works for any number of classes and any hashable label type.
- A pure node (all labels equal) returns
(0.0, 0.0). - Gini lies in ; entropy is and equals for equally-likely classes.
Notes
- Only classes that actually appear contribute, so the case never arises if you build proportions from observed counts.
Python
Loading...
▶ Run executes the 2 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference example: 6 positive, 4 negative -> Gini
- •Reference example -> Entropy (bits)