Entropy and Information Gain
Imagine building a decision tree to classify emails as spam or not spam. At every step you face the same question: which feature should I test next? And where should I split it? A tree that greedily picks bad splits wastes depth. It also generalizes poorly. One that picks splits which sharply separate classes can achieve near-perfect classification in a handful of levels. The mathematical tool that quantifies "how good is this split" is information gain. It is built on top of entropy, a measure of uncertainty borrowed directly from Claude Shannon's information theory. This idea matters far beyond toy examples. The Decision Trees and Recursive Partitioning algorithms power gradient-boosted models like XGBoost and LightGBM. They also power random forests in production fraud-detection systems, and even medical diagnosis trees. All of these rely on a split-selection criterion at their core. Entropy-based information gain (used in ID3 and C4.5) and Gini impurity (used in CART) are the two dominant choices. Understanding their mathematical relationship — and their subtle differences — explains why certain trees behave the way they do. The big picture is this: a decision tree recursively partitions the feature space. It creates regions that are as "pure" as possible with respect to the target label. Purity needs a numeric score. Entropy (from thermodynamics and information theory) turns out to be a natural way to measure impurity. It is axiomatically justified for a set of labeled examples. Information gain then measures how much a candidate split reduces that impurity. It converts an abstract statistical quantity into a concrete, greedy search heuristic. This article defines entropy and Gini impurity precisely. It derives information gain step by step, and gives working pseudocode for a split-selection routine. It proves why greedy maximization of information gain is a sound (if imperfect) heuristic. It also traces a full worked example by hand. Finally, it flags the classic pitfalls that every practitioner must know before trusting a tree. These include the notorious bias toward high-cardinality features.
- Entropy measures the uncertainty (impurity) of a label distribution in bits.
- Information gain is the reduction in entropy achieved by splitting a dataset on a feature: .
- Gini impurity is a computationally cheaper, differentiable-flavored alternative that behaves similarly to entropy.
- Split selection is greedy: at each node pick the feature/threshold maximizing information gain (or minimizing weighted impurity), not a globally optimal tree.
- Raw information gain is biased toward high-cardinality splits; the gain ratio (C4.5) corrects this by normalizing by the split's own entropy.
- These criteria feed directly into Tree Pruning and Complexity Control, since greedy purity-maximizing splits tend to overfit without a stopping/pruning mechanism.
Information gain measures how much a split shrinks the uncertainty in class labels, and greedily maximizing it is how decision trees decide what to ask next.
The idea
Entropy is a measure of the average uncertainty, or "surprise," in a random variable's distribution. For a discrete label taking values in with probabilities (estimated from class frequencies in a dataset ), the Shannon entropy is
with the convention . Entropy is measured in bits when using . It is exactly when one class has probability (perfectly pure, no uncertainty) and it is maximized at when all classes are equally likely (maximum uncertainty). For binary classification (), , peaking at .
Information gain (IG) measures how much splitting a dataset on a feature (or feature/threshold pair) reduces this uncertainty. If the split partitions into subsets (e.g., for a binary threshold split, or for a categorical split), then
The second term is the weighted average entropy of the children, sometimes called the conditional entropy . Information gain is therefore literally the mutual information between the label and the split variable : , with equality only when is independent of within . Non-negativity of information gain is not an accident — it follows from the concavity of the entropy function (Jensen's inequality), so a split can never increase expected uncertainty about on average.
Gini impurity is an alternative impurity measure used by CART:
It can be interpreted as the expected error rate if you labeled a randomly drawn example from according to the label distribution itself (i.e., predicting class with probability and being wrong with probability ). Like entropy, Gini impurity is for a pure node and maximized when classes are balanced. The corresponding split-quality score, the Gini gain, is defined analogously to information gain:
Both entropy and Gini are special cases of a broader family of impurity functions — concave functions of that vanish at the vertices of the probability simplex ( for some ) and peak at the uniform distribution. This shared shape is exactly why they tend to prefer similar splits in practice, even though their numeric values and derivatives differ.
How it works
Building a tree with an impurity-based criterion is a greedy, recursive procedure. At each node, the algorithm searches over all candidate features and (for continuous features) all candidate thresholds, computes the information gain (or Gini gain) for each candidate split, and commits to the single best one — without ever reconsidering that choice later. This is what makes tree induction fast: it never explores the combinatorially many possible trees, only a sequence of locally optimal decisions. ```text function ENTROPY(S):
# S: multiset of class labels n = |S| if n == 0: return 0 H = 0 for each class k present in S: p_k = count(S, k) / n H -= p_k log2(p_k) return H function GINI(S): n = |S| if n == 0: return 0 G = 1 for each class k present in S: p_k = count(S, k) / n G -= p_k p_k return G function BEST_SPLIT(S, features, criterion=ENTROPY): H_parent = criterion(S) best_gain = -infinity best_split = None for A in features: candidate_thresholds = CANDIDATE_THRESHOLDS(S, A) for t in candidate_thresholds: S_left = { x in S : x[A] <= t } S_right = { x in S : x[A] > t } if |S_left| == 0 or |S_right| == 0: continue # degenerate split, skip weighted = (|S_left| / |S|) criterion(S_left) + (|S_right| / |S|) criterion(S_right) gain = H_parent - weighted if gain > best_gain: best_gain = gain best_split = (A, t, S_left, S_right) return best_split, best_gain function BUILD_TREE(S, features, max_depth, depth=0): if ENTROPY(S) == 0 or depth == max_depth or |features| == 0: return LEAF(majority_class(S)) # base case: pure or exhausted split, gain = BEST_SPLIT(S, features) if split == None or gain <= 0: return LEAF(majority_class(S)) # no useful split found (A, t, S_left, S_right) = split left_child = BUILD_TREE(S_left, features, max_depth, depth+1) right_child = BUILD_TREE(S_right, features, max_depth, depth+1) return NODE(test = (A <= t), left_child, right_child) ``` `CANDIDATE_THRESHOLDS` sorts the distinct values of feature observed in and considers midpoints between consecutive distinct values where the class label changes — a standard optimization, since the impurity can only improve at a boundary between differently-labeled adjacent points, so it never helps to place a threshold strictly inside a run of same-label points. For a categorical feature, either every subset of categories is tried (small cardinality) or, more commonly, a per-value one-vs-rest split is used. The recursion terminates because each recursive call operates on a strictly smaller subset (`S_left` and `S_right` are proper, non-empty subsets of `S` whenever a split is accepted), and depth is capped, so the tree has finite depth and every branch reaches a base case.
Complexity & correctness
Time complexity. Let be the number of examples at a node and the number of features. Computing entropy or Gini for one candidate split requires a pass over class counts, which can be maintained incrementally: sort the values of a continuous feature once (), then sweep left-to-right, updating running class counts in per boundary and recomputing the two impurities in per threshold, where is the number of classes. This gives per feature per node, so per node when sorting dominates (typical for ). Across a full tree of depth , since the total number of examples summed across all nodes at one depth level is (each example lives in exactly one node per level), the total cost is
in the (common) balanced case, and in the worst case of a maximally unbalanced tree with . Sorting can be done once per feature at the root and maintained via indices during partitioning, avoiding repeated full sorts — a standard implementation optimization in libraries like scikit-learn and CART, bringing the typical practical cost close to total amortized in balanced trees. Space complexity is per feature to hold sorted indices, plus for running counts, so overall for a naive implementation, or if features are processed one at a time and released.
Correctness of the greedy criterion. There is no claim that maximizing information gain at each node yields the globally optimal decision tree (finding the optimal tree of bounded size is NP-hard in general). What can be proven is narrower and more useful: information gain is a sound local measure of split quality, in the sense that 1. always. Proof sketch: entropy is a strictly concave function of the probability vector . By Jensen's inequality, for any partition of into with weights and label distributions satisfying (law of total probability),
which rearranges to . So splitting can never increase expected uncertainty about — a split is informative or, at worst, neutral, never harmful in expectation. 2. if and only if is (empirically) independent of within — that is, the class distribution is identical in every child. This matches intuition: a split that doesn't change the label distribution anywhere provides no information. 3. Gini gain satisfies the same two properties, by the identical Jensen's-inequality argument applied to the concave function . So the greedy algorithm is correct in the sense that it always makes locally non-harmful, information-theoretically justified choices, and it is a standard, well-studied heuristic for the (NP-hard) combinatorial problem of finding a small, accurate tree — analogous to how greedy heuristics are used for other NP-hard problems where exhaustive search is infeasible. The tradeoff is that greediness with no lookahead can miss splits that only pay off two levels down (the classic XOR problem: neither single feature reduces impurity alone, but their combination perfectly separates the classes). This limitation, and the tendency of unconstrained greedy growth to overfit training noise, motivates the pruning and depth-control techniques covered in Tree Pruning and Complexity Control.
Entropy vs. Gini — a practical note. Both are concave, both vanish at pure nodes, both peak at the uniform distribution — but they are not identical curves. For binary classification with the probability of the positive class:
Entropy is somewhat more sensitive near the extremes (it penalizes small impurities more sharply due to the logarithm), while Gini is computationally cheaper (no logarithms) and is what CART uses by default. Empirically, trees built with either criterion tend to agree on splits over 90% of the time in practice; disagreements are rare and rarely matter for final accuracy, though entropy-based gain has the additional bias problem addressed by gain ratio, discussed below.
Worked example
Consider a tiny "Play Tennis" dataset with 14 examples and a binary label (Play = Yes/No), split on the categorical feature Outlook with values Sunny, Overcast, Rain.
| Outlook | Yes | No | Total |
|---|---|---|---|
| Sunny | 2 | 3 | 5 |
| Overcast | 4 | 0 | 4 |
| Rain | 3 | 2 | 5 |
| All (parent) | 9 | 5 | 14 |
Step 1 — Parent entropy.
Step 2 — Entropy of each child. Sunny (2 Yes, 3 No; ):
Overcast (4 Yes, 0 No; pure):
Rain (3 Yes, 2 No; ):
Step 3 — Weighted child entropy.
Step 4 — Information gain.
Step 5 — Compare against another candidate feature, say Wind (Weak/Strong):
| Wind | Yes | No | Total |
|---|---|---|---|
| Weak | 6 | 2 | 8 |
| Strong | 3 | 3 | 6 |
Since , the algorithm chooses Outlook as the root split, because it produces far more purity reduction — the Overcast branch becomes an immediate pure leaf (all "Yes"), while Wind leaves both children substantially mixed. This matches the classic ID3 worked trace and illustrates exactly why greedy IG-maximization is a reasonable, checkable procedure: at every candidate, you can hand-verify the arithmetic and confirm the algorithm's choice is the one that locally destroys the most uncertainty.
Gini cross-check. Using Gini impurity instead: . For Outlook, , , , giving weighted Gini , so . For Wind: , , weighted , so . Gini agrees: Outlook again wins decisively over Wind, confirming the two criteria give the same qualitative split decision here.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| High-cardinality bias | A feature like "ID number" with unique values yields pure singleton children, giving artificially maximal information gain | Use gain ratio (C4.5), which penalizes splits with many small, high-entropy children |
| Confusing entropy units | Using instead of changes numeric values (nats vs. bits) though not which split wins | Be consistent; report units; ranking of splits is invariant to the log base, only magnitudes change |
| Zero-probability log | Computing for naively gives NaN | Explicitly define (its limit) in code |
| Treating IG=0 as "no signal ever" | A single feature may have marginally but be jointly informative with another (XOR-type interactions) | Use ensembles (random forests, boosting) or deeper/interaction-aware trees to recover such structure |
| Ignoring overfitting from unconstrained gain-chasing | Always splitting until nodes are pure fits noise, especially with many features relative to samples | Apply max depth, min-samples-per-leaf, or post-hoc pruning — see Tree Pruning and Complexity Control |
| Comparing gains across different-sized candidate sets unfairly | Comparing a 2-way split's gain to a 10-way split's gain without normalization favors the latter | Use gain ratio or restrict to binary splits, as CART does uniformly |
Pioneers & history
Origins · 1 minClaude Elwood Shannon and how this was discovered
Shannon's 1948 paper A Mathematical Theory of Communication introduced entropy as the fundamental measure of information content and uncertainty, originally to quantify the capacity of communication channels. Decades later, this exact formula became the backbone of decision tree learning, an application Shannon himself did not design but whose mathematics transferred essentially unchanged.
Quinlan's ID3 was built directly on Shannon's entropy formula, treating each feature test as a "question" whose expected information value could be computed exactly the way Shannon computed channel capacity. Breiman and colleagues, working independently in statistics, arrived at Gini impurity via a different route — minimizing expected misclassification cost under a two-class Bayes-error argument — yet the resulting splits so closely resemble entropy-based ones that both criteria remain standard, interchangeable defaults in modern libraries.
Where this matters
Every major tree-based library implements exactly this machinery: scikit-learn's `DecisionTreeClassifier` exposes `criterion='gini'` or `'entropy'` directly as a parameter, and both XGBoost and LightGBM use closely related (though second-order, loss-derivative-based) impurity surrogates when growing each boosting-round tree. Random forests, used in genomics for gene-expression classification and in finance for credit-risk scoring, build hundreds of such trees, each one repeatedly invoking information-gain or Gini-gain computations at every node. Medical decision-support tools favor entropy/Gini-based trees specifically because the splits are human-readable ("if age > 50 and troponin > threshold..."), unlike black-box neural models — auditability is a first-class requirement in clinical and regulatory settings. Feature-selection pipelines also borrow information gain directly (independent of any tree) as a fast univariate filter to rank candidate predictors before more expensive modeling. Finally, this same entropy-reduction logic generalizes to mutual-information feature selection in NLP and to impurity-based feature importance scores reported by every scikit-learn or ranger (R) random forest, making entropy and Gini impurity two of the most-invoked formulas in applied machine learning, even when practitioners never see the word "entropy" in the API they call.
Ask the tutor: How does the entropy-based information gain criterion change when the target variable is continuous, as in regression trees?
Why use log base 2 for entropy instead of natural log?
Log base 2 gives entropy units of bits, matching the original communication-theory motivation where one bit answers one yes/no question optimally. The choice of log base only rescales entropy by a constant factor (), so it never changes which split maximizes information gain — the ranking of candidate splits is invariant to the base. Some libraries use natural log (giving units of "nats") purely for computational convenience, since natural log avoids an extra division. For teaching and reporting purposes, bits are the traditional and more interpretable choice, since bits corresponds cleanly to needing yes/no questions to identify one of equally likely classes.
Is Gini impurity always faster to compute than entropy?
Yes, in practice, because Gini impurity requires only sums of squared probabilities (), while entropy requires a logarithm evaluation per class (). Logarithms are typically several times more expensive than multiplication on modern hardware, so for very large datasets or very deep forests with millions of split evaluations, this difference is measurable in wall-clock training time. This computational advantage, not superior statistical performance, is the primary reason CART and many production libraries default to Gini impurity. In terms of split quality, the two criteria are close enough that the choice rarely changes final model accuracy meaningfully.
What is gain ratio, and why does it fix the high-cardinality bias?
Gain ratio, introduced in Quinlan's C4.5, divides information gain by the intrinsic information (entropy) of the split itself: , where treats the partition sizes themselves as a probability distribution. A feature that splits data into many tiny fragments (like a unique ID) has very high , so dividing by it heavily discounts the raw gain. This normalizes for the "free" gain a feature gets merely from having many possible values, forcing the criterion to reward splits that are informative relative to how finely they fragment the data.
Can information gain be negative?
No — information gain is always non-negative for any partition, a direct consequence of the concavity of the entropy function via Jensen's inequality. Weighted child entropy can never exceed parent entropy in expectation over the induced partition. What can happen is information gain being exactly zero (the split provides no information, all children have the same class distribution as the parent) or the validation-set improvement being negative even though training-set information gain is positive, which signals overfitting rather than a violation of the entropy inequality itself.
How does information gain relate to decision tree pruning?
Because greedy information-gain maximization always finds some positive gain until nodes are pure (barring ties or degenerate splits), an unconstrained tree will keep splitting until every leaf is perfectly pure on the training set — which almost always means overfitting to noise. Pruning techniques, covered under Tree Pruning and Complexity Control, counteract this by either stopping growth early (pre-pruning, e.g., minimum gain thresholds) or growing a full tree and then removing subtrees that do not improve validation performance (post-pruning, e.g., cost-complexity pruning). Information gain tells you what the best split is; pruning tells you when to stop trusting that greedy signal.
Do entropy and Gini impurity generalize beyond classification trees?
Yes. The same entropy formula underlies mutual-information-based feature selection, used to rank predictors independent of any specific model. In regression trees, the analogous impurity measure is variance reduction rather than entropy, since class probabilities do not apply to continuous targets. In clustering and density estimation, entropy quantifies cluster purity or model uncertainty. In deep learning, the cross-entropy loss function used for classification is directly derived from the same Shannon entropy framework, connecting tree-based split criteria and neural network training losses through one shared information-theoretic foundation.
Why do information gain and Gini gain sometimes disagree on the best split?
Although both are concave impurity functions peaking at the uniform distribution, their exact curvature differs: entropy involves logarithms and is more sharply penalizing near extreme probabilities, while Gini is a simple quadratic. For most real datasets the two produce identical or near-identical split rankings, but in edge cases — particularly with highly imbalanced class distributions or specific threshold ties — the differing curvature can tip the ranking of two very close candidate splits. Neither criterion is "more correct"; they are two reasonable concave impurity functions from the same family, and empirical studies generally find negligible difference in final tree accuracy between them.