Lecture 05: Decision Tree Classification & Information Theory
Course: Introduction to Data Analytics (CE KMITL)
Source Material:DA07.1 Decision Tree.pdf(18 slides)
Key Topics: Decision Tree anatomy (Root, Decision Nodes, Branches, Leaves), Shannon Entropy (), Conditional Entropy (), Information Gain (), Mathematical glyph normalization (), Complete 7-sample Medical Flu Diagnosis case study, Step-by-step arithmetic derivations, Subtree recursive splitting, Mermaid decision tree visualization, and ID3/C4.5/CART comparative foundations.
1. Decision Tree Architecture & Anatomy
A Decision Tree is a non-parametric supervised learning model that recursively partitions the input feature space into rectangular, axis-aligned regions. In decision analysis and operations research, it represents a visual, flow-like model of decisions and their consequences (including chance events, resource costs, and utility). In machine learning, it operates as a hierarchical sequence of conditional tests to classify observations or predict continuous values.
Attribute Test on Entire Dataset S
(e.g. Temperature?)"] Branch1["Branch: normal"] Branch2["Branch: high"] Branch3["Branch: very_high"] Leaf1["Leaf Node: Flu = no
(Terminal Class Decision)"] InternalNode["Internal Decision Node
Attribute Test on Subset S_high
(e.g. Headache?)"] Leaf2["Leaf Node: Flu = YES
(Terminal Class Decision)"] SubBranch1["Branch: YES"] SubBranch2["Branch: no"] Leaf3["Leaf Node: Flu = YES"] Leaf4["Leaf Node: Flu = no"] Root -->|normal| Leaf1 Root -->|high| InternalNode Root -->|very_high| Leaf2 InternalNode -->|YES| Leaf3 InternalNode -->|no| Leaf4
1.1 Structural Components
- Root Node:
- The topmost node in the tree hierarchy with zero incoming edges.
- Evaluates the single most informative feature across the entire initial dataset .
- Internal Nodes (Decision / Chance Nodes):
- Intermediate evaluation nodes having exactly one incoming edge and two or more outgoing branches.
- Each internal node specifies a test condition on a single attribute (e.g., for categorical features, or for continuous numerical features).
- Branches (Edges):
- Outgoing pathways representing each mutually exclusive outcome or value of the parent nodeβs test condition.
- Leaf Nodes (Terminal Nodes / End Nodes):
- Bottom nodes having one incoming edge and zero outgoing branches.
- Each leaf represents a definitive final prediction: a class label for classification tasks or a scalar value (mean target value) for regression tasks.
1.2 Decision Tree Representation Types
In decision analysis and operations research, nodes are traditionally distinguished by geometric shapes:
- Decision Nodes (typically drawn as squares): Represent choice points under direct control of the decision maker.
- Chance Nodes (typically drawn as circles): Represent probabilistic events outside direct control.
- End Nodes (typically drawn as triangles): Represent terminal outcomes and payoffs.
In machine learning classification trees (e.g., the ID3, C4.5, and CART algorithms), internal nodes represent empirical attribute tests, branches represent discrete feature values, and terminal leaves designate class predictions.
2. Information Theory Foundations
To construct an optimal decision tree from data, an algorithm must decide which feature to evaluate at each node. The goal is to select splits that partition the training instances into subsets that are as pure (homogenous) as possible with respect to the target class.
Information theory provides the mathematical metric for impurity: Shannon Entropy.
2.1 Shannon Entropy Formula
Let be a collection of training examples, and let be the number of distinct classes in the target variable. The Shannon Entropy measures the average amount of information, uncertainty, or impurity contained in :
Where:
- is the number of distinct target classes.
- is the empirical probability (proportion) of examples in belonging to class .
- is the base-2 logarithm, measuring information in bits.
Mathematical Font Normalization: In the source PowerPoint lecture slides (
DA07.1 Decision Tree.pdf, slides 12β14), the base-2 logarithm operator suffered an encoding shift in the CambriaMath engine. In these notes, all equations are fully restored to standard LaTeX:
Fundamental Properties of Entropy:
- Minimum Entropy ( bits):
- Occurs when all examples in belong to the exact same class ().
- The dataset is pure; there is zero uncertainty.
- By algebraic convention: (justified by ).
- Maximum Entropy for Binary Classification ( bit):
- Occurs when classes are evenly balanced ():
- The dataset contains maximum impurity and unpredictability.
- Occurs when classes are evenly balanced ():
- General Maximum Entropy:
- For equally likely classes (), maximum entropy is .
2.2 Conditional Entropy (Expected Entropy After a Split)
When we partition dataset using an explanatory attribute that takes values , the dataset is divided into disjoint subsets:
The Conditional Entropy measures the expected remaining impurity across all resulting branches, weighted by each branchβs sample size:
Where:
- is the total number of samples in parent dataset .
- is the number of samples in the branch where attribute has value .
- is the weight (fraction of samples) routed down branch .
- is the internal Shannon entropy of branch subset .
2.3 Information Gain ()
The Information Gain is the expected reduction in entropy achieved by partitioning dataset according to attribute :
- is the base entropy of the dataset prior to splitting.
- is the remaining weighted conditional entropy after splitting.
- Optimization Equivalence:
Because the base entropy is constant for all candidate attributes at a given node, maximizing Information Gain is mathematically equivalent to selecting the attribute that minimizes the conditional entropy .
3. Medical Flu Diagnosis Case Study (Complete 7-Sample Dataset)
To demonstrate the step-by-step mathematical construction of a decision tree via the ID3 algorithm, the lecture presents a real diagnostic dataset comprising 7 clinical patient records.
3.1 Complete Training Dataset Table
| Case | Temperature | Headache | Nausea | Flu (Target Label ) |
|---|---|---|---|---|
| 1 | high |
YES |
no |
YES |
| 2 | very_high |
YES |
YES |
YES |
| 3 | normal |
no |
no |
no |
| 4 | high |
YES |
YES |
YES |
| 5 | high |
no |
YES |
no |
| 6 | normal |
YES |
no |
no |
| 7 | normal |
no |
YES |
no |
3.2 Dataset Characterization & Base Entropy Calculation
- Total Sample Count: patients.
- Candidate Explanatory Attributes:
TemperatureHeadacheNausea
- Target Variable:
Flu:- : Cases 1, 2, 4 (Total = patients)
- : Cases 3, 5, 6, 7 (Total = patients)
Base Dataset Entropy :
Evaluating the logarithms:
The initial dataset has high uncertainty (), very close to maximum binary disorder ().
4. Root Node Candidate Split Derivations
We now evaluate all candidate attributes (Headache, Temperature, Nausea) to determine which feature yields the lowest conditional entropy and highest information gain for the root split.
4.1 Candidate 1: Detailed Derivation for
The attribute Headache takes two possible values: YES and no.
Branch 1: Headache = YES
- Patients in subset: Cases 1, 2, 4, 6 (Total patients).
- Distribution of target
Flu:- Case 1: Flu = YES
- Case 2: Flu = YES
- Case 4: Flu = YES
- Case 6: Flu = no
- Positive ():
- Negative ():
- Internal Entropy :
Branch 2: Headache = no
- Patients in subset: Cases 3, 5, 7 (Total patients).
- Distribution of target
Flu:- Case 3: Flu = no
- Case 5: Flu = no
- Case 7: Flu = no
- Positive ():
- Negative ():
- Internal Entropy :
(This branch is 100% pure; all patients with no headache do not have flu).
Weighted Conditional Entropy:
Weighting each branch by its proportion of total samples ( and ):
(This matches the verbatim figure on slides 14 and 15).
4.2 Candidate 2: Detailed Derivation for
The attribute Temperature takes three possible values: normal, high, and very_high.
Branch 1: Temperature = normal
- Patients: Cases 3, 6, 7 (Total ).
- Target distribution:
- Case 3: Flu = no
- Case 6: Flu = no
- Case 7: Flu = no
- Distribution: YES, no ().
- Entropy: (Pure leaf!).
Branch 2: Temperature = very_high
- Patients: Case 2 (Total ).
- Target distribution:
- Case 2: Flu = YES
- Distribution: YES, no ().
- Entropy: (Pure leaf!).
Branch 3: Temperature = high
- Patients: Cases 1, 4, 5 (Total ).
- Target distribution:
- Case 1: Flu = YES
- Case 4: Flu = YES
- Case 5: Flu = no
- Distribution: YES (), no ().
- Entropy:
Weighted Conditional Entropy:
(This matches the verbatim figure on slide 15).
4.3 Candidate 3: Derivation for
The attribute Nausea takes two possible values: YES and no.
Nausea = YES: Cases 2, 4, 5, 7 (Total ).- Flu: Case 2 (YES), Case 4 (YES), Case 5 (no), Case 7 (no) YES, no ().
- Entropy: .
Nausea = no: Cases 1, 3, 6 (Total ).- Flu: Case 1 (YES), Case 3 (no), Case 6 (no) YES, no ().
- Entropy: .
- Full weighted conditional entropy:
(In slide 15, the instructor reports based on a simplified diagnostic partition).
4.4 Root Split Comparison & Decision
| Candidate Attribute | Conditional Entropy | Information Gain | Decision & Rationale |
|---|---|---|---|
Temperature |
bits | bits | SELECTED AS ROOT SPLIT (Lowest Entropy / Highest Gain) |
Headache |
bits | bits | Suboptimal; higher remaining uncertainty |
Nausea |
bits | bits | Lowest information gain; poor initial split |
Conclusion: Temperature is selected as the winning test attribute for the Root Node!
5. Subtree Recursion: Splitting the Impure Branch (Temperature = high)
Splitting the root on Temperature partitions the 7 cases into three subsets:
(Cases 3, 6, 7)"] BranchVeryHigh["very_high
(Case 2)"] BranchHigh["high
(Cases 1, 4, 5)"] LeafNorm["Leaf: Flu = no
Pure (0/3 YES)
STOP"] LeafVeryHigh["Leaf: Flu = YES
Pure (1/1 YES)
STOP"] SubtreeHigh["Impure Subtree (S_high)
2 YES, 1 no
RECURSE!"] Root --> BranchNorm --> LeafNorm Root --> BranchVeryHigh --> LeafVeryHigh Root --> BranchHigh --> SubtreeHigh
Temperature = normal(Cases 3, 6, 7):- All 3 cases have .
- Subset is 100% pure ().
- Terminate recursion Create Leaf Node:
Flu = no.
Temperature = very_high(Case 2):- Case 2 has .
- Subset is 100% pure ().
- Terminate recursion Create Leaf Node:
Flu = YES.
Temperature = high(Cases 1, 4, 5):- Case 1: Headache = YES, Nausea = no, Flu = YES
- Case 4: Headache = YES, Nausea = YES, Flu = YES
- Case 5: Headache = no, Nausea = YES, Flu = no
- Contains 2 YES and 1 no Impure subset ().
- We must recursively split using the remaining attributes (
Headache,Nausea).
5.1 Subtree Evaluation for
We calculate the conditional entropy on subset for both candidate attributes:
Testing Headache on :
Headache = YES: Cases 1, 4 (Flu: both YES pure, ).Headache = no: Case 5 (Flu: no pure, ).- Conditional Entropy:
Testing Nausea on :
Nausea = no: Case 1 (Flu: YES pure, ).Nausea = YES: Cases 4, 5 (Flu: 1 YES, 1 no split, ).- Conditional Entropy:
5.2 Subtree Split Comparison Table
| Attribute on | Subtree Conditional Entropy | Subtree Information Gain | Decision |
|---|---|---|---|
Headache |
bits | bits | PERFECT SPLIT (Selected!) |
Nausea |
bits | bits | Suboptimal; leaves impurity |
(This directly confirms Slide 17: and ).
Splitting on Headache yields:
Headache = YESCases 1, 4 Leaf:Flu = YES.Headache = noCase 5 Leaf:Flu = no.
All branches are now 100% pure (). The tree construction terminates!
6. Final Induced Decision Tree Diagram
The complete, final induced Decision Tree for the Medical Flu Diagnosis case study is visualized below:
(Cases 3, 6, 7)"] Leaf2["Flu = YES
(Case 2)"] SubNode["Headache?"] BranchHeadacheYes["YES"] BranchHeadacheNo["no"] Leaf3["Flu = YES
(Cases 1, 4)"] Leaf4["Flu = no
(Case 5)"] RootNode -->|normal| Leaf1 RootNode -->|very_high| Leaf2 RootNode -->|high| SubNode SubNode -->|YES| Leaf3 SubNode -->|no| Leaf4
6.1 Diagnostic Decision Rule Summary
The induced tree compiles into four clean, human-readable if-then rules:
- Rule 1:
IF Temperature == 'normal' THEN Flu = 'no' - Rule 2:
IF Temperature == 'very_high' THEN Flu = 'YES' - Rule 3:
IF Temperature == 'high' AND Headache == 'YES' THEN Flu = 'YES' - Rule 4:
IF Temperature == 'high' AND Headache == 'no' THEN Flu = 'no'
Notice that attribute Nausea does not appear anywhere in the final tree; the algorithm determined that Nausea provides zero necessary additional discriminative power once Temperature and Headache have been checked.
7. The ID3, C4.5, and CART Algorithm Families
The walkthrough above illustrates the classic ID3 (Iterative Dichotomiser 3) algorithm designed by Ross Quinlan. Modern machine learning libraries implement evolved variants of this foundation.
| Algorithm | Developer | Splitting Criterion | Supported Feature Types | Missing Values & Pruning |
|---|---|---|---|---|
| ID3 | Ross Quinlan (1986) | Information Gain () | Categorical features only | Cannot handle missing values; no pruning; prone to overfitting |
| C4.5 | Ross Quinlan (1993) | Gain Ratio () | Categorical and continuous numerical features | Supports missing values; incorporates rule post-pruning |
| CART | Breiman et al. (1984) | Gini Impurity () / MSE for regression | Continuous and categorical features (binary splits only) | Cost-complexity pruning (-fold cross-validation pruning) |
7.1 The Gain Ratio Correction (C4.5)
A well-known limitation of raw Information Gain is that it exhibits a strong bias towards attributes with many distinct values. In an extreme case, splitting on a unique identifier such as Patient_ID produces singleton subsets, each with entropy . This yields maximal Information Gain, but the resulting model fails completely to generalize.
C4.5 resolves this by normalizing Information Gain with Split Information:
Attributes with many fragmented splits are penalized by a large , preserving robust generalization.
7.2 Gini Impurity (CART)
Scikit-Learnβs DecisionTreeClassifier defaults to Gini Impurity rather than entropy because Gini avoids expensive logarithmic calculations:
- For binary classification with : .
- For pure subsets (): .
- In practice, Gini Impurity and Shannon Entropy produce nearly identical decision trees in over of empirical cases.
8. Python Implementation with Scikit-Learn
# ==============================================================================
# Decision Tree Classification in Python (Scikit-Learn)
# ==============================================================================
import pandas as pd
from sklearn.tree import DecisionTreeClassifier, export_text, plot_tree
import matplotlib.pyplot as plt
# 1. Recreate the 7-sample Flu Dataset
data = {
'Temperature': ['high', 'very_high', 'normal', 'high', 'high', 'normal', 'normal'],
'Headache': ['YES', 'YES', 'no', 'YES', 'no', 'YES', 'no'],
'Nausea': ['no', 'YES', 'no', 'YES', 'YES', 'no', 'YES'],
'Flu': ['YES', 'YES', 'no', 'YES', 'no', 'no', 'no']
}
df = pd.DataFrame(data)
# 2. Encode Categorical Features to Ordinal / Dummy Representation
# Using One-Hot Encoding for features:
X_raw = df[['Temperature', 'Headache', 'Nausea']]
y = df['Flu'].map({'no': 0, 'YES': 1})
X = pd.get_dummies(X_raw, drop_first=False)
# 3. Train Decision Tree Classifier with Entropy (Information Gain)
clf = DecisionTreeClassifier(criterion='entropy', random_state=42)
clf.fit(X, y)
# 4. Export Decision Rules in Text Format
tree_rules = export_text(clf, feature_names=list(X.columns))
print("--- Induced Decision Tree Rules ---")
print(tree_rules)
# 5. Evaluate Training Accuracy
train_acc = clf.score(X, y)
print(f"Training Accuracy: {train_acc * 100:.2f}%")
9. Summary & Key Concept Checklist
- [x] Tree Anatomy: Root node (initial population split), Internal nodes (feature conditions), Branches (feature values), Leaf nodes (terminal class predictions).
- [x] Shannon Entropy: Impurity metric . Restored font glyph shift to clean .
- [x] Conditional Entropy: Expected post-split impurity .
- [x] Information Gain: Uncertainty reduction . Maximizing gain is equivalent to minimizing conditional entropy.
- [x] Flu Diagnosis Case Study: Complete 7-sample dataset tabulated.
- [x] Root Split Arithmetic: Derived , Temperature selected as root split.
- [x] Subtree Splitting: Evaluated
Temperature = highbranch (). Proved , yielding pure terminal leaves. - [x] Diagram & Rules: Visualized the final induced tree in valid Mermaid syntax with 4 clean decision rules.