Compute information gain and gain ratio for a categorical split
Why it matters Gain ratio is how C4.5 style decision trees avoid picking ID-like columns, a classic exam and interview question on tree splitting.
Information gain loves features with many values (an ID column splits perfectly). Gain ratio, used by C4.5 trees, divides by the split's own entropy to correct that bias.
Write gain_ratio(feature, labels). Both are equal-length lists. Use base-2 entropy. IG = H(labels) - sum over feature values v of (n_v / n) * H(labels where feature == v). Split info SI = -sum_v (n_v / n) log2(n_v / n). Return (IG, GR) as floats, where GR = IG / SI, or 0.0 when SI is 0 (only one feature value).
def gain_ratio(feature, labels)Example
feature ["s", "s", "r", "r", "o", "o"], labels [0, 0, 1, 1, 1, 0] gives (0.666667, 0.420620) (rounded).
Understand the idea
Information gain (IG) measures how much a split reduces uncertainty about the label. Its weakness: a column with a unique value per row, like a customer ID, splits the data into pure groups of size one and gets the maximum IG, even though it is useless for new customers.
Gain ratio divides IG by the split information, which is the entropy of the feature itself. A feature with many small groups has a big split information, so its ratio drops.
Worked example: 4 rows with labels 0, 1, 0, 1 and an ID feature a, b, c, d. Label entropy is 1 bit and every group is pure, so IG = 1. But split info = log2(4) = 2, so GR = 0.5. A clean binary feature with the same IG of 1 would have split info 1 and GR = 1, so it wins.
Rule: IG = H(Y) - sum_v (n_v/n) H(Y | v), SI = -sum_v (n_v/n) log2(n_v/n), GR = IG / SI.
C4.5 decision trees use gain ratio to pick splits.