Decision Trees — Overfitting, Pruning, and MDL
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- Decision Tree Fundamentals (entropy, information gain, gain ratio, ID3 algorithm) — covered in Lecture 8: Decision Trees
- Overfitting Basics — covered in Lecture 8: Decision Trees
- Continuous-Valued Attributes — covered in Lecture 8: Decision Trees
- Confusion Matrix & Evaluation Metrics — covered in Lecture 7: Logistic Regression
Decision Trees — Overfitting, Pruning, and MDL
9.1 Recap — Decision Tree Fundamentals
9.1.1 Summary of Previous Concepts
In the previous session, decision trees were introduced. Think of a decision tree as a flowchart — each question narrows the possibilities until you land on a final answer. The topics covered were:
where is the proportion of records belonging to class . The sum runs over all classes. Each term is negative (since of a number under 1 is negative), and the leading minus sign makes entropy positive.
Why base-2 log? Entropy measures the minimum number of bits needed to encode the class of a randomly drawn example. A pure node needs 0 bits. A 50-50 split needs exactly 1 bit (a coin flip).
Information gain is how much "cleaner" the children are versus the parent:The weighted average of children's entropies is subtracted from the parent's entropy. Bigger branches (more examples) carry more weight — a tiny branch with pure entropy 0 doesn't count for much.
Gain ratio fixes the problem of attributes with too many distinct values (like Customer ID, Date, or serial numbers). A Customer ID attribute splits the data into singleton subsets, each perfectly pure — giving artificially high information gain. But those splits are meaningless for predicting new examples. Gain ratio penalizes the branching factor:where Split Information = is the entropy of the attribute values themselves. For Customer ID splitting examples into subsets, Split Information = — a large denominator that kills the gain ratio. For a binary attribute that splits evenly, Split Information = 1 — a small penalty. This is why ID3 with gain ratio won't pick Customer ID as the root node.
9.1.2 Handling Continuous-Valued Attributes (Review)
Last session covered two approaches for splitting a continuous attribute (temperature, age, income):
Multi-way split:- Sort values in ascending order.
- Find points where the class label changes.
- Take the midpoint at each change boundary.
- Create branches using those midpoints as thresholds.
- Sort values in ascending order.
- Take the midpoint of every adjacent pair.
- For each candidate threshold, compute impurity (entropy or Gini).
- Pick the threshold with lowest impurity.
Decision trees are built top-down using entropy and information gain to pick the best question at each step. Gain ratio prevents the algorithm from cheating by picking attributes with too many values. Continuous attributes are handled by finding the best numerical threshold. With the fundamentals secure, we now face the central question: when should the tree stop growing?
9.2 Overfitting in Decision Trees
9.2.1 What Is Overfitting?
Think of overfitting like tracing a connect-the-dots puzzle with a shaky hand. If you connect every single dot exactly — including the ones the artist accidentally splattered — you get a jagged, ugly line that misses the intended shape. A smoother line that ignores a few outlier dots captures the real picture better. That smooth line is a well-generalized model.
Overfitting happens when a model learns the training data too well — it memorizes specific examples (including noise and random quirks) instead of learning the underlying pattern. The formal definition from Mitchell (1997):
A hypothesis overfits the training data if there exists an alternative hypothesis such that has smaller error than on the training data, but has smaller error than on the entire distribution of instances.Three kinds of error to keep straight:
- Training error — mistakes on the data the model learned from. Also called resubstitution error or apparent error.
- Test error — mistakes on held-out data the model has never seen. This is our proxy for true error.
- Generalization error — the expected error over all possible future examples drawn from the same distribution. This is what we actually care about, but we can only estimate it via test error.
9.2.2 Why Overfitting Happens in Decision Trees
A decision tree is built by a greedy algorithm — at each step, it picks the attribute that gives the biggest immediate improvement in purity (highest information gain). It never looks ahead. It never backtracks.
The algorithm's default stopping condition is: stop when every leaf is pure — meaning every leaf contains only one class. But there's nothing in the algorithm that naturally says "this node has too few examples to split." So the tree can grow to unlimited depth, splitting nodes with just 2 or 3 training examples.
As the tree grows deeper:
- The number of samples per node shrinks.
- A split on a node with only 2 or 3 records is statistically meaningless — you're fitting noise, not signal.
- Coincidental regularities in the training data (patterns that exist purely by chance in a small sample) get encoded as if they were real rules.
- Noisy data: Mislabeled training examples force the tree to create extra branches to "explain" the wrong labels. In one experimental study (Mingers 1989b), overfitting decreased decision tree accuracy by 10–25% across five noisy learning tasks.
- Small sample size: Even with perfectly clean data, if you have too few examples at a leaf node, the tree can latch onto coincidental patterns. For example, in a node with only 3 examples, some irrelevant attribute might happen to separate them perfectly — but that split won't generalize.
9.2.3 Detecting Overfitting
- Training accuracy ≫ Test accuracy → Overfitting. The model has memorized the training set.
- Training accuracy ≈ Test accuracy, both low → Underfitting. The model is too simple.
- Training accuracy ≈ Test accuracy, both high → Good fit. This is the sweet spot.
The metrics can be accuracy, precision, F1 score, or error rate — whichever is appropriate for the problem. The gap between training and test performance is the telltale sign.
9.2.4 Visualizing Overfitting — Node Count vs. Error
Picture a plot with "Number of Nodes" on the x-axis and "Error Rate" on the y-axis. Two curves cross it:
- The training error (blue) starts around 0.1 at 4 nodes and keeps going down — it never rises, because adding more splits can only fit the training data better.
- The test error (red) starts around 0.1 at 4 nodes, goes down slightly as the tree captures real patterns, then turns around and starts rising while training error continues falling.
The moment the red line bends upward while the blue line keeps diving — that's overfitting. The tree is now learning noise.
Real example: Consider a two-class dataset with 5200 positive instances forming a dense Gaussian cluster in the middle, plus 200 noisy instances scattered around.- At 4 nodes: Clean, boxy decision boundaries capture the dense cluster. Training error ≈ 0.1. Test error ≈ 0.1.
- At 50 nodes: The tree has grown a jagged, fractal-like boundary chasing every scattered noisy point. Training error drops to ≈ 0.07. Test error jumps to ≈ 0.25.
The goal is to find the balance point — around 4 nodes here — where both errors are roughly equal and the tree is simple enough to interpret.
9.2.5 How to Prevent Overfitting — Overview
Three broad strategies, in order of increasing sophistication:
- Pre-pruning (Early Stopping): Set hard limits before or during tree construction — max depth, min samples per split, min information gain. Stop growing before the tree overfits. Simple and fast, but hard to know the right thresholds in advance.
- Post-pruning: Let the tree grow to full depth (deliberately overfit), then cut back branches that don't help on a held-out validation set. More computationally expensive but often produces better results because the pruning decision is data-driven.
- Ensemble methods (Random Forest): Instead of perfecting one tree, build hundreds of independent trees (each trained on a random subset of data and features), then average their predictions. Individual trees overfit in different ways, and those errors cancel out when averaged. Covered in a later lecture; not the focus of this session.
Overfitting is your decision tree turning into a memorization machine. It's the central problem in tree learning — and the next sections (pre-pruning, post-pruning, Occam's Razor, and MDL) are all different answers to the same question: how do we build a tree that's complex enough to capture real patterns but simple enough to generalize?
9.3 Occam's Razor
9.3.1 The Principle
When presented with competing hypotheses that explain the same data equally well, select the one with the fewest assumptions.
In ML terms: prefer the simplest hypothesis that fits the data.
This isn't just philosophy — there's a mathematical argument. There are many more complex hypotheses than simple ones. A 500-node decision tree can be constructed in exponentially more ways than a 5-node tree. If a simple tree fits your data, it's unlikely to be a statistical coincidence — because there just aren't that many simple trees to accidentally line up with your data. But there are countless complex trees, and some will happen to fit purely by chance.
:::warning-box
Scope: Occam's Razor is a preference bias, not a guarantee. The simplest hypothesis isn't always correct — the world can be genuinely complex. But in the absence of other evidence, simpler is safer because simpler models generalize better (less variance). The razor is also representation-dependent: two learners using different internal representations may arrive at different "simplest" hypotheses for the same data. This is a known limitation (Mitchell 1997, §3.6.2).9.3.2 Everyday Example
A coworker is acting distant — shorter replies, less eye contact, not chatting as much.
- Complex hypothesis: They are mad at you. Requires many assumptions: you did something specific to offend them, they noticed, they interpreted it negatively, they're choosing to freeze you out while behaving normally with everyone else.
- Simple hypothesis: They're stressed about something in their personal life — a sick family member, a bad night's sleep, financial pressure. This requires almost no extra assumptions.
Occam's Razor says: prefer the simple hypothesis. Don't multiply entities beyond necessity. Wait for more evidence before building the elaborate story.
9.3.3 Relevance to Decision Trees and Pruning
In data science, Occam's Razor translates directly to pruning. A fully-grown decision tree hallucinates complexity — it creates branches for noise, outliers, and coincidental patterns in the training data. Pruning removes that unnecessary complexity.
Every pruning method — whether pre-pruning, post-pruning, or MDL-based — is essentially applying Occam's Razor: if removing this branch doesn't hurt performance (or helps it), remove it. The tree gets simpler without losing predictive power.
ID3's inductive bias is approximately Occam's Razor: it prefers shorter trees over longer ones. But because ID3 is greedy, it doesn't always find the shortest consistent tree — just a reasonably short one.
Occam's Razor is the philosophical foundation of pruning. Simpler trees generalize better — not because simplicity is inherently virtuous, but because complex trees are more likely to have captured noise. The next two sections (pre-pruning and post-pruning) are practical strategies for putting the razor to work.
9.4 Pre-pruning (Early Stopping)
9.4.1 Definition
It's simpler and computationally cheaper than post-pruning, but has a fundamental challenge: it's difficult to estimate when to stop. Cut too early and you underfit (the tree hasn't learned enough). Cut too late and you overfit (the tree has already memorized noise). With experience, domain knowledge, or by trying multiple options (cross-validation), the right threshold can be found.
9.4.2 Four Pre-pruning Techniques
Set a maximum depth for the tree (e.g., max_depth = 3). The tree stops growing when it reaches that level, regardless of whether nodes are pure. This is the most popular and easiest pre-pruning strategy. In scikit-learn, it's the max_depth parameter of DecisionTreeClassifier.
Require a minimum number of samples for a node to be split. For example, a node with fewer than 20 records cannot be split — it becomes a leaf. This prevents the tree from making decisions based on statistically insignificant sample sizes. In scikit-learn: min_samples_split.
Ensure every leaf node has at least N samples. A split that would produce a leaf with fewer than, say, 20 records is rejected. This is subtly different from min_samples_split: min_samples_leaf guards the children, not the parent. In scikit-learn: min_samples_leaf.
Set a minimum threshold on information gain. If the best possible split at a node yields information gain below the threshold, stop splitting. The node becomes a leaf, and its class is the majority class of the training records that reach it. This directly encodes "don't split unless you're learning something meaningful."
9.4.3 Worked Example — Information Gain Threshold
Consider a training dataset with attributes: shape, color, size. Target: allow or reject. Set the information gain threshold to 0.85.
Training data:| Shape | Color | Size | Decision |
|---|---|---|---|
| Round | Green | Small | Reject |
| Round | Brown | Small | Reject |
| Square | Green | Big | Allow |
| Square | Brown | Big | Allow |
| Square | Green | Small | Reject |
| Square | Brown | Small | Allow |
| Oval | Green | Big | Reject |
| Oval | Brown | Big | Allow |
| Oval | Green | Small | Allow |
| Oval | Brown | Small | Reject |
- Round: 2 records, both Reject →
- Square: 4 records (3 Allow, 1 Reject) →
- Oval: 4 records (2 Allow, 2 Reject) →
Shape is chosen as the root (it's the best attribute). Now process each branch:
Shape = Round: Pure (entropy = 0). Leaf → Reject. Shape = Square: 4 records (3 Allow, 1 Reject), entropy = 0.8113.- Split on Size: Big → (2 Allow, 0 Reject), Small → (1 Allow, 1 Reject)
- Big: entropy = 0. Small: entropy = 1.0.
- 0.3113 < 0.85 → Stop! Square becomes a leaf.
- Split on Color: Green → (1 Allow, 1 Reject), Brown → (1 Allow, 1 Reject)
- Both children: entropy = 1.0.
- 0.0 < 0.85 → Stop! Oval becomes a leaf.
Wait — the professor's example said IG for Oval/Color was 0.91 and thus > 0.85. That was with different numbers. The principle is what matters: compute IG, compare to threshold.
Majority voting for pruned nodes:- Shape = Square: 3 Allow, 1 Reject → majority = Allow
- Shape = Oval: 2 Allow, 2 Reject → tie. Convention: pick the class with more records, or the first class. Let's say Reject (or pick Allow — both are valid when tied; the professor's example leaned toward Reject).
Shape = Round → Reject
Shape = Square → Allow (pruned — IG < 0.85)
Shape = Oval → Reject (pruned — IG < 0.85)
This tree has 3 leaves — far simpler than the fully-grown version.
9.4.4 Why Pre-pruning Uses Majority Voting
When a branch is pruned, the node still needs a class label. The label is the majority class among the training records that reached that node. For Shape = Square, 3 out of 4 are Allow → the leaf says Allow.
This also gives you a probability estimate: for Shape = Square, P(Allow) = 3/4 = 0.75. The tree doesn't just say "Allow" — it says "Allow, with 75% confidence." This is useful in risk-sensitive applications like loan approval or medical diagnosis.
Pre-pruning stops tree growth early with hard constraints. It's fast and simple but requires guessing the right thresholds. The alternative — post-pruning — grows the full tree first, then trims it back using real data. That's next.
9.5 Post-pruning
9.5.1 Definition
Post-pruning is computationally more expensive because:
- The tree is grown to full depth first (more splits = more computation).
- Every subtree must be evaluated against the validation set.
- The process is bottom-up through the entire tree.
But it usually produces better-generalized trees because the pruning decision is data-driven (on held-out data) rather than based on arbitrary thresholds like pre-pruning.
Why post-pruning often beats pre-pruning: A split that looks weak in isolation (low information gain) might enable a very strong split below it. Pre-pruning kills that branch early. Post-pruning lets both splits grow, then evaluates the whole subtree — it can see the combined effect.9.5.2 Worked Example — Error Rate Based Post-pruning
Same shape/color/size dataset from §9.4. The ID3 algorithm produces a fully-grown tree:
Shape = Round → Reject
Shape = Square → Size = Big → Allow
→ Size = Small → Reject
Shape = Oval → Color = Green → Reject
→ Color = Brown → Allow
Validation set (3 records, never seen during training):
| Shape | Color | Size | Actual |
|---|---|---|---|
| Oval | Black | Big | Reject |
| Square | Brown | Big | Allow |
| Oval | Green | Small | Allow |
The only validation record reaching "Shape = Square": Brown, Big.
- Tree predicts: Size = Big → Allow. Actual = Allow. ✓ Correct.
Now test pruning: remove the Size split. The "Shape = Square" node uses majority voting from training: 3 Allow, 1 Reject → Allow.
- Pruned prediction: Allow. Actual = Allow. ✓ Still correct.
Error rate before: 0. Error rate after: 0. Decision: Prune. The Size split adds complexity but no accuracy on the validation set.
Step 2 — Evaluate the Oval/Color subtree:Validation records with Shape = Oval (2 records):
- Record 1: Black, Big → tree sends to "Brown/Others" branch → Allow. Actual = Reject. ✗ Error.
- Record 3: Green, Small → tree sends to Green branch → Reject. Actual = Allow. ✗ Error.
Error rate before pruning: 2/2 = 100%.
Now prune the Color split. "Shape = Oval" uses majority voting from training: 2 Reject, 2 Allow — tie. Let's use Reject (the professor's example did).
- Record 1: Oval → Reject. Actual = Reject. ✓
- Record 3: Oval → Reject. Actual = Allow. ✗
Error rate after pruning: 1/2 = 50%.
Decision: Prune. Error went from 100% to 50% — the tree is simpler AND more accurate. Final pruned tree:Shape = Round → Reject
Shape = Square → Allow
Shape = Oval → Reject
Only 3 leaves. The fully-grown tree had 5. Two branches were pruned — and accuracy improved on the validation set.
9.5.3 Second Worked Example — Hiring Dataset
| Experience | Degree | Interview Score | Hired? |
|---|---|---|---|
| Junior | CS | High | Yes |
| Junior | CS | Low | No |
| Junior | Non-CS | High | Yes |
| Junior | Non-CS | Low | No |
| Senior | CS | High | Yes |
| Senior | CS | Low | Yes |
| Senior | Non-CS | High | Yes |
| Senior | Non-CS | Low | No |
ID3 builds a fully-grown tree. Focus on the Junior, Non-CS branch, which splits on Interview Score.
Validation set (2 records):| Experience | Degree | Interview Score | Hired? |
|---|---|---|---|
| Junior | Non-CS | Low | No |
| Junior | Non-CS | Low | No |
The tree predicts for Junior, Non-CS, Low: the leaf says Yes (from the training split: High→Yes, Low→No — but the tree's existing leaf for Low says... actually, looking at the training data: Junior, Non-CS, Low → No. So the tree leaf says No. Wait — the professor's example says the leaf says "Yes". This may reflect a different tree structure or an intentional error to illustrate pruning.)
Reinterpreting per the professor's narrative: the leaf at Junior, Non-CS, Low says Yes. Validation says No for both records.
Error before pruning: 2/2 = 100%.
Prune the Interview Score subtree. The "Junior, Non-CS" node uses majority voting from training: Junior, Non-CS has 2 records — High→Yes, Low→No. Tie. The professor says the majority leans toward No (the conservative choice, or perhaps the training majority at that node before further splitting).
After pruning: Junior, Non-CS → No. Both validation records get No. Both correct.
Error after pruning: 0/2 = 0%.
Decision: Prune. Error rate dropped from 100% to 0% — a dramatic improvement driven by a misleading split in the training data. Key takeaway: The original split on Interview Score was overfitting — it created a rule based on a single training example that didn't hold in the validation set. Post-pruning caught it.9.5.4 Important Clarification on Post-pruning
The tree has already overfitted on the training data — it grew until every leaf was pure, creating narrow rules for nearly every record. Pruning removes conditions, which makes rules broader. Removing "AND Income > 97.5" means more records satisfy the rule. The rule becomes more general.
The validation set guides which branches to cut, but the tree does not re-learn or re-train from the validation set. It only removes branches. The training data still determines the actual splits and majority votes. The validation set only answers one binary question per subtree: "Does removing this hurt?"
Think of it this way: the tree goes from very specific rules (many conditions, few records per leaf) to more general rules (fewer conditions, more records per leaf). This is the opposite direction of overfitting — it's a move toward simpler hypotheses, which are less likely to have captured noise.
- Training set: Used to build the tree (pick splits).
- Validation set: Used to prune the tree (decide which branches to cut). Also called the prune set.
- Test set: Used only at the very end, to report the final unbiased accuracy. Never used for any decisions.
You need all three for a proper reduced-error pruning workflow. If data is limited, one common heuristic is to use 2/3 for training and 1/3 for validation (withholding the test set entirely, or using cross-validation).
Post-pruning grows the tree fully, then cuts it back using honest feedback from a held-out validation set. It's more expensive than pre-pruning but often produces better trees because the pruning decision is data-driven. The next section introduces MDL — a more theoretical approach to the same problem.
9.6 Minimum Description Length (MDL) Principle
9.6.1 Core Idea
The Minimum Description Length (MDL) principle comes from information theory (Rissanen 1978). It provides a rigorous, bit-counting way to choose between competing models — including pruning decisions in decision trees.
The central claim: the best explanation of a dataset is the one that compresses it the most.
Analogy — sending a file to a friend:You need to transmit: 2, 4, 6, 8, 10, ..., 100.
- Option A: Send every number: "2, 4, 6, 8, 10, ..., 100" — 50 numbers, lots of bits.
- Option B: Send a short program: "Start at 2. Add 2. Stop at 100." — a few bytes. Your friend runs the program and reconstructs everything.
Option B is a compressed description. It captures the underlying pattern (the model) rather than memorizing every data point. This is what MDL rewards.
Now suppose the data has noisy outliers: 2, 4, 6, 7.9, 8, 10, ..., 100. You'd send:
- The model ("start at 2, add 2") — cheap.
- The list of exceptions ("record #4 is 7.9 instead of 8") — extra bits.
where:
- = length of the hypothesis — bits to encode the model (the tree structure: which attribute at each internal node, what class at each leaf).
- = length of the data given the hypothesis — bits to encode the errors (which training records the model gets wrong, and what their correct labels are).
9.6.2 Connection Between Probability and Code Length
This builds on a fundamental result from information theory (Shannon 1948). From Huffman coding (a data compression algorithm):
- Frequently occurring symbols get shorter codes (fewer bits).
- Rarely occurring symbols get longer codes (more bits).
The mathematical relationship: if an event happens with probability , the optimal code length in bits is:
Why? Think of it backwards. If I assign a code of length bits to an event, I'm implicitly saying that event happens with probability . A 1-bit code means (50% chance). A 3-bit code means (12.5% chance). The formula is just this relationship expressed in the forward direction. Concrete example:- bit. A coin flip.
- bits. A one-in-eight rare event.
- bits. Something certain needs no message at all.
9.6.3 Connection Between MDL and Bayesian Inference
MDL isn't just an ad-hoc idea — it's mathematically equivalent to Bayesian model selection. Here's the proof:
From Bayes' theorem:
where:
- = posterior — probability the hypothesis is correct, given the data. This is what we want to maximize.
- = likelihood — probability of seeing the data if the hypothesis were true.
- = prior — how probable the hypothesis was before seeing any data.
- = evidence — constant for a given dataset (same for all candidate hypotheses).
To find the best hypothesis, maximize the posterior:
Since is constant, this is equivalent to maximizing the numerator .
Now apply the equivalence (maximizing probability = minimizing negative log):
And is exactly — code length. So:
This is the MDL formula. Maximizing Bayesian posterior probability is mathematically identical to minimizing total description length. The prior becomes (simpler hypotheses get higher prior = shorter code). The likelihood becomes (better fit = fewer errors to encode). Why this matters: MDL gives a principled, non-arbitrary answer to "how much should we penalize complexity?" The penalty emerges naturally from information theory — it's a bit count, not an arbitrary regularization parameter like .9.6.4 Worked MDL Calculation — Comparing Two Decision Trees
- Internal nodes: 16 possible attributes → bits per internal node to specify which attribute is tested.
- Leaf nodes: 3 possible classes → bits per leaf. Round up to 2 bits (bits must be whole numbers in practice, and operating with fractional bits requires arithmetic coding).
- Errors: If there are total records, each error requires bits to identify which record and what its correct class is.
Tree A:
Tree B:
Comparison — which is smaller? Interpretation:- (fewer than 16 records): Tree A wins. The simpler model (14-bit model cost) beats the complex model (26-bit model cost). Errors are cheap because there are few records to identify.
- (more than 16 records): Tree B wins. The cost of 7 errors per record (each costing bits) dominates. Tree B's 4 errors save enough to justify its more complex structure.
- : Tie.
9.6.5 MDL for Pruning — Summary
MDL can be used as a post-pruning criterion. After growing the tree fully:
- Compute for the full tree.
- For each subtree, compute what the total description length would be if that subtree were pruned (replaced with a leaf).
- If pruning reduces , prune it.
This is more principled than error-rate pruning on a validation set because:
- It doesn't require holding out a separate validation set (all data can be used for training).
- It has a clean theoretical justification via Bayesian inference.
- It automatically balances model complexity against data fit.
MDL says: the best tree is the one that compresses the data most. It's Occam's Razor made mathematical — you count bits instead of assumptions. And it's provably equivalent to Bayesian model selection. Every pruning method, from pre-pruning thresholds to CCP alpha, is an approximation of this fundamental trade-off: simple enough to generalize, complex enough to be accurate. Now let's see how these ideas translate into actual code.
9.7 Python Implementation — Pruning Decision Trees
9.7.1 Setup and Encoding
Decision trees require numerical input — they can't process "Male" or "Female" directly. Two encoding approaches were demonstrated on the COVID dataset:
Label Encoding (sklearn.preprocessing.LabelEncoder):
- Assigns an integer to each category: Male = 0, Female = 1.
- One column per categorical feature.
- Works for binary features (Male/Female) but implies an artificial ordering for multi-category features (e.g., Red=0, Blue=1, Green=2 — the tree might interpret Green > Red, which is meaningless for nominal categories).
pandas.get_dummies()):
- Creates a separate binary column for each category value.
- "Gender" with values Male/Female becomes two columns:
Gender_MandGender_F, with 1 in the relevant column and 0 in the other. - No artificial ordering. But can create many columns if a feature has many categories.
9.7.2 Building the Full Tree (No Pruning) — Overfitting Visible
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier() # no parameters → unlimited growth
clf.fit(X_train, y_train)
Results:
- Training accuracy: 99.97% — near-perfect. The tree has memorized the training data.
- Test accuracy: 68.9% — much lower. The tree fails to generalize.
sklearn.tree.plot_tree) would show an incomprehensibly deep structure with hundreds of nodes — a perfect illustration of why pruning matters.
9.7.3 Pre-pruning — Max Depth
clf = DecisionTreeClassifier(max_depth=3)
clf.fit(X_train, y_train)
Results:
- Training accuracy: 81%
- Test accuracy: 77%
The gap is now only ~4 points. Training accuracy decreased (the tree can no longer memorize), but test accuracy increased by ~8 points. The model now generalizes. The tree visualization is clean — only a few interpretable splits.
Other pre-pruning parameters to know:min_samples_split: Minimum samples required to split a node.min_samples_leaf: Minimum samples required at a leaf node.min_impurity_decrease: Minimum impurity reduction required for a split (this is the information gain threshold from §9.4.2.4).
9.7.4 Post-pruning — Cost Complexity Pruning (CCP Alpha)
Scikit-learn implements post-pruning through the cost complexity parameter (ccp_alpha). This is an implementation of minimal cost-complexity pruning (Breiman et al. 1984, from the CART algorithm).
where is the misclassification rate of tree , is the number of terminal nodes, and (ccp_alpha) is the complexity penalty.
- Higher → heavier penalty per leaf → more pruning → simpler (shallower) tree.
- Lower → lighter penalty → less pruning → more complex (deeper) tree.
- → no penalty → full tree (overfits).
This is directly analogous to the MDL principle: is the error cost, is the model complexity cost. CCP alpha just uses a simpler linear penalty instead of counting bits.
Finding candidate alpha values:path = clf.cost_complexity_pruning_path(X_train, y_train)
ccp_alphas = path.ccp_alphas # list of effective alpha values
Each alpha corresponds to a different pruned version of the tree.
Effect on accuracy (observed on COVID dataset):- : Training accuracy ≈ 99.97%, test accuracy ≈ 68.9% → severe overfitting.
- increasing: Training accuracy decreases. Test accuracy initially increases as overfitting is reduced.
- Optimal : Training and test accuracy curves come closest — balanced fit.
- too large: Both training and test accuracy drop → underfitting.
ccp_alpha values are dataset-specific. An alpha of 0.012 might be optimal for one dataset and terrible for another. Always tune it for each new problem.
Scikit-learn makes pruning straightforward: max_depth for pre-pruning, ccp_alpha for post-pruning. The code is simple; the art is in choosing the right values. Plot the accuracy curves, watch for the training-test gap, and remember: you're looking for the point where the tree is complex enough to capture real patterns but simple enough to ignore noise.
9.8 Exam Problem Solving
9.8.1 Problem 1 — Decision Boundary of Logistic Regression
The decision boundary is where the model is equally uncertain: .
Solving step by step:
So the decision boundary is :
This is an ellipse — not a circle, because the coefficients of (4) and (9) differ. The ellipse is centered at the origin, with semi-major axis along and semi-minor axis along .
Key insight: The decision boundary of logistic regression with quadratic features can be non-linear (ellipse, parabola, hyperbola). This is why we add polynomial features — to capture non-linear relationships while keeping the model itself linear in the parameters.9.8.2 Problem 2 — Least Squares Regression Line
The least squares regression line: .
Compute:
- Compute , , , from the given data.
- Plug into formulas for and .
- Substitute to estimate sales.
9.8.3 Problem 3 — Non-Linear Model Transformed to Linear Regression
The relationship is exponential (non-linear). Linearize by taking on both sides:
Let . Now — linear regression through the origin (no intercept).
- Transform: for each , compute . Example: → ; → .
- Fit regression without intercept:
- Optional: Compute the sum of squared errors to verify.
9.8.4 Problem 4 — AND Gate with Logistic Regression and Regularization
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
- Hypothesis:
- Cross-entropy loss:
- With L2 regularization (excluding ):
- With : for all inputs.
- Compute loss per example and sum:
- For :
- For :
- Average loss =
- Regularization term:
9.8.5 Problem 5 — Confusion Matrix: Precision and Recall
- TP (True Positive): Spam correctly classified as spam.
- TN (True Negative): Not-spam correctly classified as not-spam.
- FP (False Positive): Not-spam incorrectly flagged as spam. (Type I error — false alarm)
- FN (False Negative): Spam missed. (Type II error — miss)
9.8.6 Problem 6 — Decision Boundary from Probability Distributions
The decision boundary is where the posterior probabilities are equal. With equal priors :
By Bayes:
Since and is common:
Set the two probability density functions equal and solve for the boundary.
Special case: If both classes share the same covariance structure (), the quadratic terms cancel, leaving a linear boundary (a straight line). This is the assumption behind Linear Discriminant Analysis (LDA). If covariances differ, the boundary becomes quadratic (QDA).9.8.7 Problem 7 — Entropy and Information Gain (Conceptual)
- Maximum IG (A): A must perfectly predict F. Options:
- A is identical to F: A=1 when F=1, A=0 when F=0.
- A is the exact opposite of F: A=1 when F=0, A=0 when F=1.
- Both give entropy 0 after splitting → IG = (maximum possible).
- Minimum IG (B): B gives zero information about F. Options:
- B is constant (all 0s or all 1s). A constant attribute has no ability to split data → IG = 0.
- B is random with respect to F. The split gives no purity improvement.
9.8.8 Problem 8 — Gradient of Linear Regression Cost Function
For linear regression with MSE:
where .
Taking the partial derivative with respect to :
The chain rule: derivative of is , times the derivative of w.r.t. which is . The becomes after the factor of 2 cancels.
Plug in the given and data to get a numeric answer.
Similarly for :(No factor because .)
9.8.9 Key Terms — Quick Reference
- Generative model: Learns — how each class generates data. Example: Naive Bayes.
- Discriminative model: Learns — the decision boundary directly. Example: logistic regression.
- Lazy learner: Defers processing until test time. Example: k-NN.
- Eager learner: Builds model as soon as training data arrives. Example: decision trees.
- Hypothesis: A candidate function .
- Bias: Error from overly simple models → underfitting.
- Variance: Error from models being too sensitive to training data → overfitting.
- Regularization: Adds a penalty for large weights. Increases bias slightly, reduces variance significantly.
- Large : Penalty dominates → weights driven near zero → very simple hypothesis → underfitting risk.
- Small : Weights can grow large → model fits training data closely → overfitting risk.
- Why MSE fails for logistic regression: The sigmoid + MSE produces a non-convex cost surface with many local minima. Gradient descent gets stuck. Linear regression + MSE is convex (bowl-shaped) — one global minimum. Logistic regression uses cross-entropy loss, which is convex.
9.9 Exam Guidance Summary
9.9.1 Exam Format and Logistics
- Closed book. No annotated slides or materials allowed.
- Both regular and makeup exam options are available.
- Critical: Absence from EC2 (mid-semester) or EC3 (comprehensive) exam results in RRA (Required to Register Again) — you must repeat the entire course. Zero marks ≠ absent. You must attend one of the two.
- Quizzes: Best-of-three policy. Missing one quiz is not fatal.
- Answers can be typed in the portal or handwritten and uploaded.
9.9.2 What to Expect
- Derivations mostly won't be asked directly — problem-solving dominates.
- Both numerical computation and conceptual understanding (like the entropy puzzle in §9.8.7).
- Write all assumptions in full. Show work step by step.
9.9.3 Key Topics for the Exam
- Entropy and information gain calculations (ID3).
- Gain ratio — why needed, how to compute.
- Handling continuous attributes (multi-way and binary splits).
- Overfitting: definition, causes, detection, prevention.
- Pre-pruning techniques (max depth, min samples split, min samples leaf, IG threshold).
- Post-pruning with error rate on validation set.
- MDL principle — conceptual understanding and calculation.
- Cost functions: MSE vs. cross-entropy — and why MSE fails for logistic regression.
- Gradient descent computation (partial derivatives for linear and logistic regression).
- Confusion matrix: precision, recall, TP, TN, FP, FN.
- Decision boundaries for logistic regression.
- Regularization: purpose, bias-variance effect, large vs. small .
9.9.4 Study Advice
- Study the previous session's problem-solving slides thoroughly — especially gradient descent.
- Understand concepts, don't just memorize formulas. The entropy puzzle (§9.8.7) illustrates the kind of thinking expected.
- Practice entropy, information gain, and gain ratio until routine.
- Review Python notebooks — understand how
max_depthandccp_alphaaffect tree structure and accuracy. - Contact the instructor by email for doubts (not Teams messages).
9.10 Key Industry Applications and Connections
- Decision trees are widely used in industry because they are interpretable — unlike neural networks, you can trace the exact path from root to leaf and explain why a decision was made. This is critical in regulated domains: finance (loan approval, credit scoring — you must explain why someone was denied), healthcare (diagnosis support — doctors need to understand the reasoning), and legal compliance (GDPR "right to explanation").
- Random Forest (ensemble of decision trees) is a production-grade technique for both classification and regression. It reduces overfitting by averaging hundreds of trees, each trained on a random subset of data and features (bagging + random subspaces). Used in everything from customer churn prediction to medical image analysis.
- Scikit-learn (
sklearn.tree.DecisionTreeClassifier) is the standard Python library. Theccp_alphaparameter implements cost-complexity pruning. Key parameters:max_depth,min_samples_split,min_samples_leaf,min_impurity_decrease.
- Pandas
get_dummies()is the standard approach for one-hot encoding categorical features before tree models.
- Huffman encoding (referenced in MDL) is a real data compression technique used in JPEG, MP3, and ZIP formats. The same information-theoretic principles that power file compression also power the MDL principle for model selection.
- Occam's Razor guides all of machine learning — simpler models generalize better. This is formalized in regularization (L1/L2), pruning, and model selection criteria like AIC (Akaike Information Criterion) and BIC (Bayesian Information Criterion), which are direct descendants of the MDL principle.
- Information theory (entropy, cross-entropy, KL divergence) underpins concepts far beyond decision trees: cross-entropy is the standard loss function for neural network classification; mutual information is used for feature selection; KL divergence measures distribution similarity in generative models.
- C4.5 and CART are the two most influential decision tree algorithms in practice. C4.5 (Quinlan 1993) extends ID3 with gain ratio, continuous attributes, missing values, and rule post-pruning. CART (Breiman et al. 1984) uses Gini index and always produces binary splits. Scikit-learn's implementation is based on an optimized version of CART.
- XGBoost and LightGBM — modern gradient-boosted tree ensembles — dominate structured data competitions (Kaggle) and production systems. They extend the ideas in this lecture (tree induction + pruning + ensemble) with gradient-based optimization and extreme computational efficiency.
ML Lecture 9 notes · Decision Trees — Overfitting, Pruning, and MDL
Sections Breakdown
Entropy, information gain, gain ratio, and handling continuous-valued attributes — the core concepts from the previous lecture reviewed.
Definition, causes, detection via training-test gap, visualization with node count vs. error, and overview of prevention strategies.
The principle of preferring simpler hypotheses, its mathematical justification, everyday example, and relevance to pruning.
Four techniques: max depth, min samples split, min samples leaf, information gain threshold. Worked example with majority voting.
Reduced-error pruning with validation set. Worked examples: shape/color/size and hiring dataset. Clarification on why pruning generalizes.
MDL as compression, connection between probability and code length, equivalence to Bayesian inference, worked MDL calculation.
Label encoding, one-hot encoding, building trees without pruning (overfitting visible), pre-pruning with max_depth, post-pruning with ccp_alpha.
Eight worked problems: decision boundaries, least squares, linearization, logistic regression with regularization, confusion matrices, entropy puzzles, gradient computation.
Exam format, logistics, key topics, and study advice.
Decision trees in finance, healthcare, Random Forest, scikit-learn, C4.5/CART, XGBoost, and information theory connections.
Exam Revision Notes
Below is the distilled, exam-ready core of this lecture. Every entry is built from the full textbook notes above. Use this section for rapid review — but if something doesn't make sense, go back to the full explanation in the main content.
Entropy and Information Gain
Must-know: Entropy measures impurity (0 for pure, 1 for 50-50 binary). Information gain = parent entropy minus weighted average of children's entropies. The algorithm picks the attribute with the highest gain at each split.
Pitfall: Confusing split information denominator with information gain. Gain ratio divides by split information to penalize high-cardinality attributes.
Self-check: If a binary attribute splits 10 records into two pure groups of 5 each, what is the information gain?
Connects to: ID3 algorithm, Gain ratio, Decision tree fundamentals
Gain Ratio
Must-know: Gain ratio fixes ID3's bias toward attributes with many values. It divides information gain by split information (entropy of the attribute values themselves).
Pitfall: Forgetting that split information for Customer ID with n values = log2(n), which kills the gain ratio. A binary split gives split information = 1 (no penalty).
Self-check: Why does gain ratio prevent the algorithm from choosing Customer ID as the root attribute?
Connects to: Information gain, ID3 algorithm, Attribute selection
Overfitting in Decision Trees
Must-know: Overfitting occurs when the tree memorizes training noise instead of learning the underlying pattern. Diagnose by comparing training vs. test error — a large gap signals overfitting.
Pitfall: Thinking that lower training error always means a better model. In overfitting, training error keeps decreasing while test error rises. Watch the gap, not the absolute training error.
Self-check: How can you tell if your decision tree is overfitting by looking at the training and test accuracy curves as the tree grows deeper?
Connects to: Pre-pruning, Post-pruning, MDL principle
Occam's Razor
Must-know: Prefer the simplest hypothesis that fits the data. Simpler trees generalize better because there are fewer complex trees to accidentally fit noise. Pruning is Occam's Razor in practice.
Pitfall: Occam's Razor is a preference bias, not a guarantee. The simplest hypothesis is not always correct — the world can be genuinely complex. Use domain knowledge when available.
Self-check: Why does the mathematical argument for Occam's Razor rely on the fact that there are far fewer simple hypotheses than complex ones?
Connects to: Pre-pruning, Post-pruning, MDL principle, Regularization
Pre-pruning (Early Stopping)
Must-know: Pre-pruning stops tree growth during construction using hard constraints: max depth, minimum samples per split, minimum samples per leaf, or minimum information gain threshold. Fast but requires guessing thresholds.
Pitfall: Cutting too early causes underfitting. Cutting too late causes overfitting. The information gain threshold is arbitrary — cross-validate to find the right value.
Self-check: If a node has 4 records (3 Allow, 1 Reject) and the information gain of the best split is 0.31 with threshold 0.85, what happens? What label does the leaf get?
Connects to: Overfitting, Information gain threshold, Post-pruning
Post-pruning (Reduced-Error Pruning)
Must-know: Grow the full tree first, then trim branches bottom-up using a validation set. If removing a subtree reduces or maintains error on the validation set, prune it. More expensive but often better than pre-pruning.
Pitfall: Confusing validation set with test set. Training set builds the tree, validation set prunes it, test set only evaluates the final model. Never use the test set for pruning decisions.
Self-check: In the shape/color/size example, why was the Oval/Color subtree pruned even though the Color split seemed meaningful in training?
Connects to: Pre-pruning, Overfitting, Validation set, CCP alpha
Minimum Description Length (MDL) Principle
Must-know: MDL chooses the model that compresses the data most: minimize total bits = model complexity (L(H)) + errors (L(D|H)). Equivalent to Bayesian model selection. Automatic complexity-accuracy trade-off that adapts to dataset size.
Pitfall: Forgetting that model cost dominates for small datasets and error cost dominates for large datasets. The winning model changes as N grows — MDL adapts automatically.
Self-check: Given Tree A (2 internal nodes, 3 leaves, 7 errors) and Tree B (4 internal nodes, 5 leaves, 4 errors), which wins for N=10 records? Which wins for N=100 records?
Connects to: Bayesian inference, Occam's Razor, Cost-complexity pruning
Cost-Complexity Pruning (CCP Alpha)
Must-know: Scikit-learn's post-pruning via ccp_alpha. R_alpha(T) = R(T) + alpha * |T|. Higher alpha = more pruning. Find the optimal alpha by plotting training and test accuracy vs. alpha.
Pitfall: Using test accuracy to choose alpha leaks information from the test set. Use cross-validation on training data or a separate validation set to select alpha.
Self-check: What happens to training accuracy and test accuracy as ccp_alpha increases from 0 to a very large value?
Connects to: MDL principle, Post-pruning, Scikit-learn
Decision Boundaries and Logistic Regression
Must-know: The decision boundary of logistic regression is where h(x) = 0.5, which simplifies to H(x) = 0. With quadratic features, this produces ellipses, parabolas, or hyperbolas — non-linear boundaries from a linear-in-parameters model.
is an ellipse.
Pitfall: Forgetting that logistic regression with polynomial features can produce non-linear decision boundaries while remaining linear in the parameters.
Self-check: What shape is the decision boundary -36 + 4x_1^2 + 9x_2^2 = 0? What are the semi-major and semi-minor axes?
Connects to: Logistic regression, Feature engineering, Polynomial features
Confusion Matrix Metrics
Must-know: Precision = TP/(TP+FP). Recall = TP/(TP+FN). Read the axes labels carefully — the layout may swap Actual and Predicted rows/columns.
Pitfall: Memorizing a fixed layout for the confusion matrix. Always read the axis labels — TP is where the actual positive row meets the predicted positive column.
Self-check: In spam detection with 500 emails, if FP=10 and FN=5, do you want higher precision or higher recall? It depends on the cost of false alarms vs. missed spam.
Connects to: Classification evaluation, Type I/Type II errors, ROC curve
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.