Decision Trees Explained: Gini, Entropy & Information Gain
Decision Trees are among the most intuitive and interpretable algorithms in machine learning. Instead of computing a linear boundary or mapping inputs into high-dimensional latent spaces, a decision tree asks a sequence of hierarchical if-else questions to divide data into smaller, more homogeneous groups.
For example, a bank might use a decision tree to decide whether a loan application should be approved:
Credit Score > 700?
/ \
Yes No
/ \
Income > 50K? Reject
/ \
Yes No
/ \
Approve Review
Each question creates a branch, and the final outcome is determined by the path followed through the tree.
The critical question when building a decision tree is:
How does the algorithm know which feature to split on, and at what specific cutoff?
To make this decision, tree algorithms evaluate mathematical split criteria that quantify uncertainty and impurity in a dataset.
The three primary concepts are:
- Entropy: Measures uncertainty in a node.
- Information Gain: Measures the reduction in entropy after a split.
- Gini Impurity: Measures how mixed the classes are within a node.
Understanding these concepts is essential for learning how decision trees work and how algorithms such as Random Forests and Gradient Boosted Trees build upon them.
1. Understanding Node Impurity
A decision tree attempts to partition a dataset into smaller subsets where observations belong predominantly to one target class.
This process is called recursive partitioning.
Every decision tree consists of three main node types:
- Root Node: The starting point containing the complete training dataset.
- Decision Node: A node that applies a condition to divide observations into branches.
- Leaf Node: A terminal node that produces the final prediction.
What Is Node Impurity?
Node impurity measures how mixed the target classes are within a particular node.
Consider a dataset containing 100 emails:
Pure Node:
Spam: 100
Legitimate: 0
Impurity = 0
Every observation belongs to the same class, so there is no uncertainty about the class label.
Impure Node:
Spam: 50
Legitimate: 50
Impurity = Maximum for binary classification
Both classes are equally represented, resulting in maximum impurity.
Partially Impure Node:
Spam: 80
Legitimate: 20
This node is less mixed than the 50-50 example but is not completely pure.
How Does a Decision Tree Use Impurity?
At every decision node, the algorithm evaluates possible splits and measures how much impurity would remain in the resulting child nodes.
The general objective is:
\[ \text{Best Split}= \text{Maximum Reduction in Weighted Impurity} \]
A good split creates child nodes that are more homogeneous than the parent node.
2. Entropy: Measuring Uncertainty
Entropy comes from Claude Shannon's Information Theory.
In machine learning, entropy measures the uncertainty or unpredictability of the target-class distribution within a node.
A node containing observations from several classes has higher entropy than a node containing observations from only one class.
2.1 Mathematical Formula
For a node containing \(C\) target classes:
\[ H(S)=-\sum_{i=1}^{C}p_i\log_2(p_i) \]
Where:
- \(H(S)\) = Entropy of the dataset or node.
- \(C\) = Number of target classes.
- \(p_i\) = Proportion of observations belonging to class \(i\).
- \(\log_2\) = Logarithm with base 2.
By convention:
\[ 0\log_2(0)=0 \]
This allows the formula to handle classes that are absent from a node.
2.2 Entropy in Binary Classification
Consider a binary classification problem containing two classes:
- Class 0: Not Spam.
- Class 1: Spam.
Case 1: Completely Pure Node
Suppose all 100 emails are spam.
\[ p_1=1,\qquad p_2=0 \]
\[ H(S)=-(1\log_2 1+0\log_2 0) \]
\[ \boxed{H(S)=0} \]
There is no uncertainty because every observation belongs to the same class.
Case 2: Equally Distributed Classes
Suppose the node contains 50 spam emails and 50 legitimate emails.
\[ p_1=0.5,\qquad p_2=0.5 \]
\[ H(S)=-[0.5\log_2(0.5)+0.5\log_2(0.5)] \]
\[ \boxed{H(S)=1} \]
This is the maximum entropy for a binary classification node.
Case 3: Unequal Class Distribution
Suppose the node contains:
- Spam: 80
- Legitimate: 20
Then:
\[ p_1=0.8,\qquad p_2=0.2 \]
\[ H(S)=-[0.8\log_2(0.8)+0.2\log_2(0.2)] \]
\[ \boxed{H(S)\approx0.722} \]
The node is less uncertain than an equally distributed node.
2.3 Entropy Boundary Behavior
For binary classification:
| Class Distribution | Entropy | Interpretation |
|---|---|---|
| 100% / 0% | 0.000 | Completely pure |
| 90% / 10% | 0.469 | Low impurity |
| 80% / 20% | 0.722 | Moderate impurity |
| 70% / 30% | 0.881 | Higher impurity |
| 50% / 50% | 1.000 | Maximum impurity |
For a problem containing \(C\) classes, the maximum entropy is:
\[ H_{\max}=\log_2 C \]
This maximum occurs when all classes have equal proportions.
Important: Entropy measures uncertainty in the class distribution. It does not directly measure the accuracy of a trained decision tree.
3. Information Gain: Evaluating the Best Split
Entropy describes the uncertainty within an individual node.
However, a decision tree must compare different possible feature splits to determine which one creates the most useful child nodes.
This is where Information Gain (IG) becomes important.
Information Gain measures how much entropy decreases after splitting a parent dataset into child subsets.
3.1 Mathematical Formula
Suppose a parent dataset \(S\) is divided into \(K\) child subsets using a feature test \(A\).
\[ IG(S,A)=H(S)- \sum_{v=1}^{K} \frac{|S_v|}{|S|}H(S_v) \]
Where:
- \(H(S)\) = Entropy of the parent node.
- \(K\) = Number of child subsets.
- \(|S|\) = Number of observations in the parent.
- \(|S_v|\) = Number of observations in child \(v\).
- \(H(S_v)\) = Entropy of child \(v\).
The second term represents the weighted average entropy of the child nodes.
The best split is the one that produces the highest Information Gain.
3.2 Worked Example: Splitting a Dataset
Suppose a dataset contains 10 customer records:
Total Customers = 10
Purchased: 6
Not Purchased: 4
The parent entropy is:
\[ H(S)=- \left[ \frac{6}{10}\log_2\frac{6}{10} + \frac{4}{10}\log_2\frac{4}{10} \right] \]
\[ \boxed{H(S)\approx0.971} \]
Now consider splitting the dataset using the feature Age.
The split produces two child nodes:
| Child Node | Purchased | Not Purchased | Total |
|---|---|---|---|
| Young | 4 | 0 | 4 |
| Adult | 2 | 4 | 6 |
Step 1: Calculate the Entropy of the First Child
The Young group contains only positive examples.
\[ H(S_1)=0 \]
Step 2: Calculate the Entropy of the Second Child
The Adult group contains two purchased and four not-purchased observations.
\[ H(S_2)=- \left[ \frac{2}{6}\log_2\frac{2}{6} + \frac{4}{6}\log_2\frac{4}{6} \right] \]
\[ H(S_2)\approx0.918 \]
Step 3: Calculate Weighted Child Entropy
\[ H_{\text{children}}= \frac{4}{10}(0)+\frac{6}{10}(0.918) \]
\[ H_{\text{children}}\approx0.551 \]
Step 4: Calculate Information Gain
\[ IG=0.971-0.551 \]
\[ \boxed{IG\approx0.420} \]
This split reduces the uncertainty in the dataset by approximately 0.420 bits per observation.
A decision tree compares this value with the Information Gain of other candidate splits and selects the best one.
3.3 The Greedy Split Selection Strategy
Algorithms such as ID3 and C4.5 use Information Gain or related criteria to choose splits.
At each node, the algorithm:
- Examines available features.
- Generates candidate split conditions.
- Calculates the impurity reduction for each candidate.
- Selects the split with the highest score.
- Repeats the process for the resulting child nodes.
This is called a greedy algorithm because the tree selects the best immediate split without exhaustively searching every possible future tree structure.
3.4 The High-Cardinality Feature Problem
Pure Information Gain can favor features containing many unique values.
For example:
- Customer Age: 18, 25, 35, 45, 60.
- Customer ID: 1001, 1002, 1003, 1004, 1005.
A Customer ID feature may create many small subsets, potentially one per customer.
These subsets can appear perfectly pure because they contain very few observations.
However, memorizing individual customer IDs does not necessarily help predict outcomes for new customers.
This is called high-cardinality bias.
Gain Ratio: A Correction Used in C4.5
C4.5 uses Gain Ratio to adjust Information Gain for the intrinsic information of a split.
\[ GainRatio(A)= \frac{IG(S,A)}{SplitInformation(A)} \]
Where:
\[ SplitInformation(A)= -\sum_{v=1}^{K} \frac{|S_v|}{|S|} \log_2\left(\frac{|S_v|}{|S|}\right) \]
Gain Ratio can reduce the preference for features that create too many small subsets.
However, it does not automatically eliminate every overfitting problem. Practical implementations may also impose constraints on valid splits.
4. Gini Impurity: The Computationally Efficient Alternative
Gini Impurity is another popular measure of node impurity used in classification decision trees.
It estimates the probability of incorrectly classifying a randomly selected observation if its label were assigned randomly according to the class proportions within the node.
It is commonly used by the CART (Classification and Regression Trees) algorithm.
Scikit-learn uses Gini Impurity as the default criterion for classification decision trees.
4.1 Mathematical Formula
For a node containing \(C\) classes:
\[ Gini(S)=1-\sum_{i=1}^{C}p_i^2 \]
Where:
- \(Gini(S)\) = Gini impurity.
- \(C\) = Number of classes.
- \(p_i\) = Proportion of observations belonging to class \(i\).
4.2 Gini Impurity in Binary Classification
Case 1: Completely Pure Node
Suppose all observations belong to Class 1.
\[ p_1=1,\qquad p_2=0 \]
\[ Gini(S)=1-(1^2+0^2) \]
\[ \boxed{Gini(S)=0} \]
Case 2: Equally Distributed Classes
Suppose the classes are equally distributed.
\[ p_1=0.5,\qquad p_2=0.5 \]
\[ Gini(S)=1-(0.5^2+0.5^2) \]
\[ \boxed{Gini(S)=0.5} \]
Case 3: Unequal Class Distribution
Suppose:
- Class 1: 80%
- Class 2: 20%
\[ Gini(S)=1-(0.8^2+0.2^2) \]
\[ Gini(S)=1-(0.64+0.04) \]
\[ \boxed{Gini(S)=0.32} \]
4.3 Gini Impurity Boundary Behavior
For binary classification:
| Class Distribution | Gini Impurity |
|---|---|
| 100% / 0% | 0.00 |
| 90% / 10% | 0.18 |
| 80% / 20% | 0.32 |
| 70% / 30% | 0.42 |
| 50% / 50% | 0.50 |
For a problem containing \(C\) classes, maximum Gini impurity is:
\[ Gini_{\max}=1-\frac{1}{C} \]
This occurs when every class has an equal proportion.
4.4 Gini Gain
Just like Information Gain measures the reduction in entropy, Gini Gain measures the reduction in weighted Gini impurity.
\[ \Delta Gini= Gini(S)- \sum_{v=1}^{K} \frac{|S_v|}{|S|}Gini(S_v) \]
The algorithm selects the split that produces the largest reduction in Gini impurity.
5. Gini Impurity vs. Entropy vs. Information Gain
Gini and Entropy are both measures of node impurity. Information Gain is specifically the reduction in entropy resulting from a split.
| Feature | Gini Impurity | Entropy | Information Gain |
|---|---|---|---|
| Purpose | Measures class impurity | Measures class uncertainty | Measures entropy reduction |
| Formula | \(1-\sum p_i^2\) | \(-\sum p_i\log_2p_i\) | Parent entropy − weighted child entropy |
| Minimum | 0 | 0 | Depends on the split |
| Binary Maximum | 0.5 | 1.0 | Not a fixed maximum |
| Computation | Uses squared probabilities | Uses logarithms | Requires entropy calculations |
| Common Association | CART | ID3, C4.5 | ID3 and related methods |
| Scikit-learn Criterion | gini | entropy | Not a separate criterion |
Which One Is Better?
There is no universal winner.
- Gini Impurity: Computationally simple and commonly used as a practical default.
- Entropy: Provides an information-theoretic interpretation and can produce different split preferences.
- Information Gain: Helps evaluate how much uncertainty is removed by a candidate split.
Both Gini and Entropy often produce similar trees, but their split rankings can differ. The best choice should be determined through validation on the target dataset.
Important: Gini and Entropy do not guarantee identical tree structures or predictive performance. The outcome depends on the data, candidate splits, stopping criteria, and implementation.
6. How Decision Trees Handle Continuous Features
Decision trees can work with both categorical and numerical features.
For numerical features, the algorithm considers candidate thresholds that divide observations into groups.
For example, suppose a dataset contains customer ages:
Age = [18, 22, 25, 30, 35, 40, 45, 50]
A decision tree might evaluate conditions such as:
Age <= 27.5
Age <= 32.5
Age <= 37.5
Age <= 42.5
Each threshold divides the observations into two child nodes.
The algorithm calculates the weighted impurity after each split and selects the threshold that produces the largest impurity reduction.
For a numerical feature \(X\), a candidate binary split can be represented as:
\[ X\leq t \]
and:
\[ X>t \]
Where \(t\) is the candidate threshold.
In many tree implementations, candidate thresholds are considered between sorted distinct feature values.
Categorical Features
Categorical features contain values such as:
City = Bangalore, Delhi, Mumbai, Pune
Depending on the algorithm, a categorical split may create multiple branches or use a binary partition of categories.
Scikit-learn's standard DecisionTreeClassifier expects numerical input features, so categorical variables generally need suitable encoding before training.
7. How Regression Trees Split Data
Gini Impurity and Entropy are used for classification trees because they measure the distribution of discrete classes.
For regression trees, the target variable contains continuous numerical values.
Examples include:
- House prices.
- Monthly sales.
- Temperature.
- Customer spending.
Instead of reducing class impurity, regression trees select splits that reduce variation in the target values.
7.1 Mean Squared Error (MSE)
A common regression-tree split criterion is Mean Squared Error.
\[ MSE(S)=\frac{1}{|S|} \sum_{i\in S}(y_i-\bar{y}_S)^2 \]
Where:
- \(|S|\) = Number of observations in the node.
- \(y_i\) = Actual target value.
- \(\bar{y}_S\) = Mean target value in the node.
The algorithm selects a split that minimizes the weighted MSE of the resulting child nodes.
Equivalently, it maximizes the reduction in squared error.
7.2 Example: House Price Prediction
Suppose a node contains four house prices:
[20, 25, 80, 85]
The parent mean is:
\[ \bar{y}=\frac{20+25+80+85}{4}=52.5 \]
The parent MSE is:
\[ MSE=\frac{ (20-52.5)^2+ (25-52.5)^2+ (80-52.5)^2+ (85-52.5)^2 }{4} \]
\[ MSE=851.25 \]
Now suppose the tree splits the observations into:
Left Child: [20, 25]
Right Child: [80, 85]
The mean of the left child is 22.5, and the mean of the right child is 82.5.
Each child has:
\[ MSE=6.25 \]
The weighted child MSE is also 6.25 because both child nodes contain two observations.
The reduction in MSE is:
\[ \Delta MSE=851.25-6.25 \]
\[ \boxed{\Delta MSE=845} \]
This is a substantial improvement because the split separates lower-priced houses from higher-priced houses.
8. Preventing Overfitting: Tree Constraints and Pruning
Decision trees are flexible models. If allowed to grow without restrictions, they can create very complex structures that memorize the training data.
This results in overfitting.
An overfitted tree may achieve nearly perfect training accuracy but perform poorly on unseen data.
To improve generalization, decision trees use stopping constraints and pruning.
8.1 max_depth
Controls the maximum depth of the tree.
DecisionTreeClassifier(max_depth=5)
A smaller depth creates a simpler tree, while a larger depth allows more complex decision rules.
8.2 min_samples_split
Defines the minimum number of observations required in a node before the algorithm attempts another split.
DecisionTreeClassifier(min_samples_split=10)
This helps prevent splitting nodes containing very few observations.
8.3 min_samples_leaf
Defines the minimum number of training observations required in each leaf.
DecisionTreeClassifier(min_samples_leaf=5)
This can prevent the model from creating leaves that represent only a handful of observations.
8.4 max_leaf_nodes
Restricts the maximum number of terminal nodes.
DecisionTreeClassifier(max_leaf_nodes=20)
This provides direct control over the number of final prediction regions.
8.5 Cost-Complexity Pruning
Cost-complexity pruning removes branches that contribute relatively little improvement to predictive performance.
A common objective is:
\[ R_\alpha(T)=R(T)+\alpha|T| \]
Where:
- \(T\) = Decision tree.
- \(R(T)\) = Total leaf-node impurity or another defined training risk.
- \(|T|\) = Number of leaf nodes.
- \(\alpha\) = Complexity penalty.
A larger \(\alpha\) penalizes complex trees more strongly and encourages smaller trees.
In Scikit-learn, this is controlled by:
DecisionTreeClassifier(ccp_alpha=0.01)
The appropriate value should be selected using validation data or cross-validation.
Pre-Pruning vs. Post-Pruning
| Feature | Pre-Pruning | Post-Pruning |
|---|---|---|
| Approach | Stops growth early | Grows a tree, then removes branches |
| Examples | max_depth, min_samples_leaf | Cost-complexity pruning |
| Main Goal | Limit tree complexity during training | Simplify an existing tree |
| Risk | May stop useful splits too early | Requires selecting a suitable pruning level |
Both approaches help control overfitting.
9. Practical Implementation Using Python and Scikit-Learn
Let's build a classification decision tree using Python and Scikit-learn.
We will compare Gini Impurity and Entropy and evaluate their predictions.
Step 1: Import Required Libraries
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import (
DecisionTreeClassifier,
plot_tree
)
from sklearn.metrics import (
accuracy_score,
classification_report,
confusion_matrix
)
Step 2: Load the Dataset
data = load_breast_cancer()
X = data.data
y = data.target
print("Features:", X.shape)
print("Target:", y.shape)
print("Classes:", data.target_names)
This dataset is a binary classification problem containing measurements used to classify breast tumors as malignant or benign.
Step 3: Split the Dataset
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.20,
random_state=42,
stratify=y
)
Stratification helps preserve approximately the same class proportions in both datasets.
Step 4: Train a Decision Tree Using Gini
gini_model = DecisionTreeClassifier(
criterion="gini",
max_depth=4,
min_samples_leaf=5,
random_state=42
)
gini_model.fit(X_train, y_train)
Step 5: Train a Decision Tree Using Entropy
entropy_model = DecisionTreeClassifier(
criterion="entropy",
max_depth=4,
min_samples_leaf=5,
random_state=42
)
entropy_model.fit(X_train, y_train)
Scikit-learn also supports criterion="log_loss" for classification trees. Its split criterion is based on entropy.
Step 6: Make Predictions
gini_predictions = gini_model.predict(X_test)
entropy_predictions = entropy_model.predict(X_test)
Step 7: Compare Model Performance
print(
"Gini Accuracy:",
accuracy_score(y_test, gini_predictions)
)
print(
"Entropy Accuracy:",
accuracy_score(y_test, entropy_predictions)
)
The scores may differ because the two criteria can select different splits.
The result should be interpreted on the test dataset, not assumed in advance.
Step 8: Display Classification Reports
print("Gini Classification Report")
print(
classification_report(
y_test,
gini_predictions,
target_names=data.target_names
)
)
print("Entropy Classification Report")
print(
classification_report(
y_test,
entropy_predictions,
target_names=data.target_names
)
)
The classification report includes precision, recall, F1-score, and support for each class.
Step 9: Visualize the Decision Tree
plt.figure(figsize=(20, 10))
plot_tree(
gini_model,
feature_names=data.feature_names,
class_names=data.target_names,
filled=True,
rounded=True,
fontsize=8
)
plt.title("Decision Tree Using Gini Impurity")
plt.show()
The visualization shows:
- Feature used for each split.
- Split threshold.
- Impurity value.
- Number of training samples.
- Predicted class at each node.
This is one of the main advantages of decision trees: their prediction process can be inspected and explained.
10. Decision Tree Algorithms: ID3 vs. C4.5 vs. CART
Different decision tree algorithms use different strategies to select splits and handle data.
| Feature | ID3 | C4.5 | CART |
|---|---|---|---|
| Split Criterion | Information Gain | Gain Ratio | Gini or regression criteria |
| Classification | Yes | Yes | Yes |
| Regression | No, in its original form | Not in its original form | Yes |
| Split Structure | Often multiway | Often multiway | Binary |
| Continuous Features | Original ID3 primarily handles categorical features | Supports continuous features | Supports continuous features |
| Pruning | Limited in original ID3 | Supports pruning | Cost-complexity pruning is common |
ID3 (Iterative Dichotomiser 3)
ID3 is an early decision tree algorithm developed by Ross Quinlan.
It selects splits using Information Gain.
Its original form primarily handles categorical features and does not include the same pruning strategy found in later algorithms.
C4.5
C4.5 extends ID3 by introducing:
- Gain Ratio.
- Support for continuous attributes.
- Handling of missing attribute values.
- Pruning techniques.
It was designed to address several limitations of the original ID3 algorithm.
CART (Classification and Regression Trees)
CART is a widely used decision tree methodology.
It supports both classification and regression.
Common criteria include:
- Gini Impurity for classification.
- Squared-error-based criteria for regression.
CART creates binary splits and is the general approach used by Scikit-learn's decision tree estimators.
11. Advantages and Limitations of Decision Trees
Advantages
- Easy to Understand: Decision trees represent predictions as understandable if-else rules.
- Minimal Feature Scaling Requirements: Standardization and normalization are generally unnecessary for ordinary decision tree splitting.
- Handles Nonlinear Relationships: Trees can model complex nonlinear decision boundaries.
- Supports Numerical and Categorical Concepts: Tree methods can work with both types of features when represented appropriately for the implementation.
- Feature Importance: Trees can provide impurity-based feature importance estimates.
- Supports Classification and Regression: The same general tree structure can solve both problem types.
Limitations
- Overfitting: Deep trees can memorize training observations.
- High Variance: Small changes in training data can result in substantially different tree structures.
- Greedy Optimization: Standard tree-building algorithms do not generally search for the globally optimal tree.
- Bias in Impurity-Based Feature Importance: Features with many possible split points or categories can receive inflated importance estimates.
- Axis-Aligned Splits: Standard decision trees split one feature at a time, which can require many branches to approximate some diagonal or smooth relationships.
- Probability Calibration: Leaf-based class probabilities are not guaranteed to be well calibrated.
For improved predictive performance, decision trees are often combined into ensemble algorithms such as Random Forests, Extra Trees, and Gradient Boosting.
12. Real-World Applications of Decision Trees
Decision trees are used in many industries because they provide interpretable decision rules.
Banking and Finance
- Loan approval prediction.
- Credit risk classification.
- Fraud detection.
- Customer risk segmentation.
Healthcare
- Disease classification.
- Patient risk assessment.
- Medical screening support.
- Treatment outcome prediction.
E-Commerce
- Customer purchase prediction.
- Product recommendation rules.
- Customer segmentation.
- Return prediction.
Marketing
- Customer churn prediction.
- Campaign response prediction.
- Lead qualification.
- Customer behavior analysis.
Manufacturing
- Equipment failure prediction.
- Quality inspection.
- Defect classification.
- Predictive maintenance.
Conclusion
Decision Trees are powerful and interpretable machine learning algorithms that make predictions by recursively splitting datasets using feature-based conditions.
The quality of each split depends on how effectively it separates observations into homogeneous child nodes.
The three essential concepts are:
- Entropy: Measures uncertainty within a node.
- Information Gain: Measures how much entropy decreases after a split.
- Gini Impurity: Measures how mixed the classes are within a node.
For regression trees, squared-error-based criteria are commonly used instead of classification impurity measures.
Although decision trees are easy to understand and can capture nonlinear relationships, unrestricted trees can overfit. Techniques such as maximum depth, minimum leaf size, and cost-complexity pruning help control model complexity.
Understanding these concepts provides a foundation for more advanced tree-based ensemble algorithms, including Random Forests, AdaBoost, XGBoost, and LightGBM.