Information Gain and Decision Trees
A decision tree asks one question at a time about the features and splits the data until each leaf is (nearly) pure. Which question should it ask first? The one that tells it the most about the label: the split with the largest information gain, which is exactly the mutual information between the split and the label. The Decision Trees lesson covers the scikit-learn side; here we build the criterion from entropy.
Information gain
For a dataset with label entropy and a split into groups, the information gain is the drop in entropy:
import numpy as np
def H(labels):
_, c = np.unique(labels, return_counts=True); p = c / c.sum()
return float(-np.sum(p * np.log2(p))) + 0.0
def info_gain(y, groups):
return H(y) - sum(np.mean(groups == g) * H(y[groups == g]) for g in np.unique(groups))
# play tennis? outlook, windy -> play
outlook = np.array(["sun", "sun", "cloud", "rain", "rain", "rain", "cloud", "sun", "sun", "rain", "sun", "cloud", "cloud", "rain"])
windy = np.array([0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1])
play = np.array([0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0])
print(f"H(play) = {H(play):.4f} bits")
print(f"IG(outlook) = {info_gain(play, outlook):.4f}")
print(f"IG(windy) = {info_gain(play, windy):.4f}")H(play) = 0.9403 bits
IG(outlook) = 0.2467
IG(windy) = 0.0481
Outlook tells more about the label, so a tree using information gain splits on it first. Note that the "cloud" branch is pure: every cloudy day was a play day.
Thresholds for numeric features
For a numeric feature, try every threshold between consecutive sorted values and keep the one with the largest gain:
import numpy as np
def H(labels):
_, c = np.unique(labels, return_counts=True); p = c / c.sum()
return float(-np.sum(p * np.log2(p))) + 0.0
rng = np.random.default_rng(0)
x = np.concatenate([rng.normal(2, 1, 100), rng.normal(5, 1, 100)])
y = np.array([0] * 100 + [1] * 100)
order = np.argsort(x); xs, ys = x[order], y[order]
best = (0, None)
for i in range(1, len(xs)):
if xs[i] == xs[i - 1]:
continue
left, right = ys[:i], ys[i:]
gain = H(ys) - (i * H(left) + (len(ys) - i) * H(right)) / len(ys)
if gain > best[0]:
best = (gain, (xs[i - 1] + xs[i]) / 2)
print(f"best threshold x < {best[1]:.3f}, information gain {best[0]:.4f} bits")best threshold x < 4.076, information gain 0.6231 bits
The bias toward many-valued features
Information gain favours features with many distinct values: a unique ID column splits the data into pure singletons and gets the maximum gain , while being useless for prediction. C4.5 corrects this with the gain ratio, which divides by the entropy of the split itself:
import numpy as np
def H(labels):
_, c = np.unique(labels, return_counts=True); p = c / c.sum()
return float(-np.sum(p * np.log2(p))) + 0.0
def info_gain(y, groups):
return H(y) - sum(np.mean(groups == g) * H(y[groups == g]) for g in np.unique(groups))
outlook = np.array(["sun", "sun", "cloud", "rain", "rain", "rain", "cloud", "sun", "sun", "rain", "sun", "cloud", "cloud", "rain"])
play = np.array([0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0])
day_id = np.arange(14)
for name, f in [("outlook", outlook), ("day id", day_id)]:
ig = info_gain(play, f)
print(f"{name:8s}: gain {ig:.4f}, split entropy {H(f):.4f}, gain ratio {ig / H(f):.4f}")outlook : gain 0.2467, split entropy 1.5774, gain ratio 0.1564
day id : gain 0.9403, split entropy 3.8074, gain ratio 0.2470
The gain ratio shrinks the ID column's advantage from almost 4 times to about 1.6 times, but on this tiny dataset the ID still wins. The gain ratio reduces the bias without removing it. In practice, ID-like columns should be removed before training; if one slips through, it shows up as a large gap between training and validation accuracy.
Entropy versus Gini
scikit-learn's default criterion is the Gini impurity , not entropy. Both are concave, zero for pure nodes and largest for uniform labels, and they choose the same split in most cases. Gini avoids logarithms and is slightly faster.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
X, y = load_iris(return_X_y=True)
for crit in ["entropy", "gini"]:
tree = DecisionTreeClassifier(criterion=crit, max_depth=3, random_state=0)
print(f"{crit:8s}: 5-fold accuracy {cross_val_score(tree, X, y, cv=5).mean():.4f}")entropy : 5-fold accuracy 0.9600
gini : 5-fold accuracy 0.9600
In software
DecisionTreeClassifier(criterion="entropy")uses information gain;criterion="log_loss"is the same in recent scikit-learn versions.- Gradient-boosted trees (XGBoost, LightGBM) choose splits by the reduction of their training loss, which for classification is the cross-entropy, so the same idea appears in a second-order form.
Exercises
Exercise 1: A perfect split
A node has 8 positive and 8 negative examples. A split sends all positives left and all negatives right. What is the information gain?
Answer
1 bit.
Solution
and both children are pure, so the gain is .
Exercise 2: A useless split
A split produces two children with the same label proportions as the parent. What is its gain?
Answer
Solution
Each child has entropy , so . The split is independent of the label.
Exercise 3: Gain by hand (code)
A node has labels [1, 1, 1, 0, 0, 0, 0, 0]. A split sends the first four examples left and the rest right. Compute the information gain.
Answer
About 0.549 bits.
Solution
import numpy as np
def H(labels):
_, c = np.unique(labels, return_counts=True); p = c / c.sum()
return float(-np.sum(p * np.log2(p))) + 0.0
y = np.array([1, 1, 1, 0, 0, 0, 0, 0])
print(round(H(y) - 0.5 * H(y[:4]) - 0.5 * H(y[4:]), 4))0.5488
Test yourself
Information gain of a split equals…
- the mutual information between the split and the label
- the entropy of the split
- the number of children
- the Gini impurity
Why does C4.5 use the gain ratio?
- Information gain favours features with many distinct values
- Information gain is negative
- Gain ratio is faster
- Gini is not defined for numeric features
Which split criterion is scikit-learn's default for classification trees?
- Gini impurity
- entropy
- gain ratio
- accuracy