Sub topic 3
Measuring node purity with Gini and entropy
This chapter assumes you know what a decision tree is (nodes, splits, leaves), how recursive partitioning grows one, and how to read a class-probability distribution. You should be comfortable with basic Python and logarithms. Here you learn the two standard ways to score how mixed a node is, and why the tree needs such a score at all.
Why a tree needs a purity score
A classification tree picks each split by asking whether the child nodes are "cleaner" than the parent. Accuracy is a poor tool for this, because one split rarely changes the majority-class prediction. You need a smooth measure of how mixed a node's labels are. That measure is called impurity.
An impurity function takes the class proportions in a node, written p1, ..., pK, and returns a number with three properties:
- It is 0 when the node is pure, meaning all samples share one class.
- It is largest when classes are evenly mixed.
- It changes smoothly as proportions change, so small improvements are visible.
Two functions dominate practice: Gini impurity and entropy.
Gini impurity
Gini impurity is defined as:
G = 1 − Σ p_k²
It has a direct reading. Draw a sample from the node, then label it by drawing a random label from the node's own class distribution. G is the probability that this label is wrong.
For a node with 6 samples of class A and 4 of class B, pA = 0.6 and pB = 0.4:
G = 1 − (0.36 + 0.16) = 0.48
For K classes the maximum is 1 − 1/K. That is 0.5 for two classes and about 0.667 for three.
Entropy
Entropy comes from information theory:
H = −Σ pk log₂ pk
It measures the average number of bits needed to encode a label drawn from the node. By convention, 0 · log 0 = 0, so classes that are absent contribute nothing.
For the same 6/4 node:
H = −(0.6 · log₂ 0.6 + 0.4 · log₂ 0.4) ≈ 0.442 + 0.529 ≈ 0.971
For K classes the maximum is log₂ K. That is 1 bit for two classes and about 1.585 bits for three.
Comparing the two curves
For a two-class node, plot each measure against p, the proportion of class A. Both are zero at p = 0 and p = 1, and both peak at p = 0.5. Entropy is taller and more sharply curved near the ends. Gini is 2p(1 − p), a plain parabola with a maximum of 0.5.
The upper curve is entropy and the lower curve is Gini. Their shapes are similar enough that they usually rank candidate splits the same way. If you rescale Gini by 2, the two curves are close everywhere.
Computing both in Python
This code implements both measures and scores one candidate split. The helper weighted combines child impurities, weighting each child by its share of the samples.
import math
from collections import Counter
def gini(labels):
n = len(labels)
if n == 0:
return 0.0
return 1.0 - sum((c / n) ** 2 for c in Counter(labels).values())
def entropy(labels):
n = len(labels)
if n == 0:
return 0.0
return 0.0 - sum((c / n) * math.log2(c / n) for c in Counter(labels).values())
def weighted(left, right, impurity):
n = len(left) + len(right)
return (len(left) * impurity(left) + len(right) * impurity(right)) / n
parent = ["A"] * 6 + ["B"] * 4
left = ["A"] * 5 + ["B"] * 1
right = ["A"] * 1 + ["B"] * 3
for name, fn in [("gini", gini), ("entropy", entropy)]:
before = fn(parent)
after = weighted(left, right, fn)
print(f"{name:8s} parent={before:.4f} children={after:.4f} decrease={before - after:.4f}")The output is:
gini parent=0.4800 children=0.3167 decrease=0.1633
entropy parent=0.9710 children=0.7145 decrease=0.2564The two decreases differ in scale, because the measures use different units. Within one training run, however, the tree only compares candidate splits against each other under the same measure, so the scale does not matter.
A reference table
| Node (class counts) | Gini | Entropy (bits) |
|---|---|---|
| 10, 0 (pure) | 0.000 | 0.000 |
| 9, 1 | 0.180 | 0.469 |
| 6, 4 | 0.480 | 0.971 |
| 5, 5 | 0.500 | 1.000 |
| 4, 3, 3 | 0.660 | 1.571 |
| 1, 1, 1 (equal thirds) | 0.667 | 1.585 |
Learn to eyeball these values. A node with Gini near 0 is almost pure, and a node near its maximum is a coin flip.
Why not just use misclassification error?
The error rate of a node is 1 − max p_k. It is the natural measure of what you care about, but it is flat in places and insensitive to some improvements.
Take a parent with 400 samples of class A and 400 of class B. Compare two candidate splits:
- Split 1 produces children with counts (300, 100) and (100, 300).
- Split 2 produces children with counts (200, 400) and (200, 0).
Both splits give a weighted misclassification error of 0.25, so error cannot choose between them. Gini gives 0.375 for split 1 and about 0.333 for split 2. Split 2 isolates a pure child that can never be wrong, and Gini rewards that. Entropy agrees with Gini here. This is why trees use strictly curved measures for growing, even if final performance is judged by error.
Gini versus entropy in practice
The practical differences are small:
- Cost. Gini needs only squares, while entropy needs a logarithm for every class at every candidate threshold. Gini is slightly faster, though tree-building time is usually dominated by sorting features.
- Behaviour. Entropy penalizes mixed nodes a bit more strongly, so it can favour slightly more balanced splits. Gini tends to isolate the largest class. In most datasets the two grow trees that differ in only a few nodes.
- Tradition. CART uses Gini. ID3 and C4.5 use entropy through information gain, which the next chapter covers.
- Units. Using natural logs instead of log₂ scales all entropy values by a constant. This does not change which split wins.
In scikit-learn you choose with the criterion argument. The values "entropy" and "log_loss" are equivalent. This example reads the impurity of each node from a fitted depth-1 tree:
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
X, y = load_iris(return_X_y=True)
for criterion in ["gini", "entropy"]:
clf = DecisionTreeClassifier(max_depth=1, criterion=criterion, random_state=0)
clf.fit(X, y)
print(criterion, clf.tree_.impurity.round(4), clf.tree_.n_node_samples)The root holds all 150 flowers with three equal classes, so its impurity is the three-class maximum: 0.6667 for Gini and 1.585 for entropy. The best first split isolates one species, giving a pure child with impurity 0. The other child holds 100 flowers split evenly between two species, with Gini 0.5 and entropy 1.0.
Edge cases and common errors
- Empty nodes. Return 0 for an empty list, as the functions above do. A candidate split that leaves one side empty should be skipped, since it gives no improvement.
- Zero proportions. Calling
math.log2(0)raises an error. Build proportions only from classes that appear, asCounterdoes, or apply the 0 · log 0 = 0 convention explicitly. - Negative zero. Writing
-sum(...)for a pure node can print-0.0. It is harmless but confusing in logs and tests. - Averaging children unweighted. A split that sends one sample to a pure child and 999 to a messy one is not good. Always weight each child by its sample count, as
weighteddoes. - Sample weights and class imbalance. With
sample_weightorclass_weight, scikit-learn computes proportions from weights, not counts. A node can then look impure or pure differently than the raw counts suggest. - Reading impurity as accuracy. Gini 0.48 does not mean 48% error. The node's actual error rate if it predicted the majority class is 40% in the 6/4 example. Gini's 0.48 is the error of random labeling.
- Comparing across measures. A Gini of 0.3 and an entropy of 0.3 are not equivalent. Compare only values from the same measure.
Where this leads
Impurity scores a single node. The tree chooses splits by comparing the parent's impurity with the weighted impurity of its children, which is the subject of the next chapter. The measure you choose here feeds directly into that comparison and later into feature importances.
Exercise
A node holds 8 samples: 2 of class A and 6 of class B. Compute its Gini impurity and its entropy in bits. Then say whether a split into children (2 A, 2 B) and (0 A, 4 B) lowers the weighted Gini, and by how much.
Show answer
Proportions are 0.25 and 0.75. Gini = 1 − (0.0625 + 0.5625) = 0.375. Entropy = −(0.25 · log₂ 0.25 + 0.75 · log₂ 0.75) = 0.5 + 0.311 ≈ 0.811 bits. For the split, the left child has 4 samples with proportions 0.5 and 0.5, so its Gini is 0.5. The right child is pure, so its Gini is 0. The weighted Gini is (4 · 0.5 + 4 · 0) / 8 = 0.25. The decrease is 0.375 − 0.25 = 0.125, so the split does lower impurity.
Exercise
Why can two splits have identical misclassification error yet different Gini scores, and which kind of split does Gini prefer?
Show answer
Misclassification error only counts the majority class in each child, so it ignores how the minority samples are distributed. Gini uses all class proportions, and its curve bends, so a split that produces a very pure child lowers the weighted impurity more than a split with two moderately mixed children. Gini therefore prefers the split that creates a purer child, even when the error rate is the same.