Skip to main content
Machine Learning

Ensemble Methods — Bagging, Random Forest, and Boosting

📅 Published: 2026-06-29
🎓 Level: postgraduate
👥 Audience: Postgraduate students in Machine Learning

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

  • Ensemble Learning — covered in Lecture 1: Introduction to Machine Learning
  • Random Forest — covered in Lecture 2: Data Preprocessing for Machine Learning
  • Ensemble Learning — covered in Lecture 3: Feature Engineering and Linear Regression
  • Ensemble Learning — covered in Lecture 4: Linear Regression Complete Lecture Notes
  • Ensemble Learning — covered in Lecture 10: Instance-Based Learning and K-Nearest Neighbors
  • Ensemble Learning — covered in Lecture 11: Instance-Based Learning — Distance-Weighted KNN, Locally Weighted Regression, and Bayesian Learning Foundations
  • Random Forest — covered in Lecture 11: Instance-Based Learning — Distance-Weighted KNN, Locally Weighted Regression, and Bayesian Learning Foundations
  • Ensemble Learning — covered in Lecture 13: Naive Bayes Classifier and Ensemble Learning
  • Bagging — covered in Lecture 13: Naive Bayes Classifier and Ensemble Learning
  • Bootstrap Aggregating — covered in Lecture 13: Naive Bayes Classifier and Ensemble Learning

Ensemble Methods — Bagging, Random Forest, and Boosting

> A single decision tree is like asking one doctor for a diagnosis. An ensemble is like convening a panel of specialists — each brings a different perspective, and together they rarely misdiagnose. This lecture covers the three most important ways to build that panel.

14.1 Ensemble Learning — Review and Foundations

Hook. Suppose you have five friends who each predict tomorrow's weather with 60% accuracy — they're right more often than they're wrong, but not by much. Alone, you wouldn't trust any of them. But if you let them vote and go with the majority, your combined accuracy can jump past 90%. How? Because their mistakes don't overlap perfectly. This is the central magic of ensemble learning: a committee of mediocre models can outperform any single expert.

14.1.1 What Is an Ensemble Model

Intuition. Think of a courtroom jury. Each juror hears the same case but brings their own life experience and reasoning. No single juror is infallible, but the group verdict — reached by majority vote — is far more reliable than any one person's judgment. An ensemble model works the same way: it's a committee of models that votes on the answer. The analogy breaks in one place: jurors deliberate and influence each other. In most ensembles (bagging, random forest), the models are trained independently and never talk to each other. Their independence is what makes the voting work.
An ensemble model combines predictions from multiple individual models — called base learners or weak learners — to make a single final prediction. Instead of trusting one model, a committee of models votes. When an input record arrives, it is fed to all the classifiers. Each base learner makes its own prediction. Those individual predictions are then combined to produce the final output. The combination is done through voting: each learner gets a vote, and the majority decides. Two major challenges drive the design of every ensemble method: 1. Diversity of base learners. The learners must be diverse — they cannot all be the same type of model or make the same mistakes. If every learner is identical, combining them adds nothing. 2. How to combine the votes. Once each learner has spoken, the system needs a rule to turn many predictions into one.

14.1.2 Creating Diversity Among Base Learners

Formal definition. Diversity among base learners is the property that different models make different errors on the same data. Without diversity, an ensemble degenerates into a single model repeated times — you gain nothing. Four practical strategies create diversity:
1. Different algorithms — use a decision tree for one learner, a neural network for another, logistic regression for a third. Informal phrase: "change the brain." 2. Different hyperparameters — use the same algorithm but vary its settings. For decision trees, change the depth or the number of features each tree sees. For neural networks, change the number of layers. Informal phrase: "change their settings." 3. Different input representations — feed different views of the data to different learners. For video analysis, one model gets the images; another gets the audio. Informal phrase: "change what they see." 4. Different training sets — the most common method. Take random samples (with replacement) from the full training data and train each learner on a different sample. Informal phrase: "change what they study." The fourth strategy — manipulating the training data — is the foundation of bagging, boosting, and random forest, the three techniques covered in this lecture.

14.1.3 Combining the Votes

Formal definition. Let there be base classifiers. For a test instance , each classifier produces a prediction . The ensemble prediction is got by applying a combination function to the individual predictions:
Several combination schemes exist: - Sum / Average: Take the sum of weighted predictions, then divide by (the number of models). Even though the literature often calls this "sum," it includes the division by — so it is effectively an average. When someone says "sum," check whether they mean with or without the factor. For regression, this is the standard: . - Weighted sum: Each learner's vote is multiplied by a weight reflecting its importance. AdaBoost uses this: the final prediction weights each classifier by , its measured reliability. - Majority voting (for classification): Pick the class that receives the most votes. Mathematically, , where is 1 when the condition holds and 0 otherwise. - Median, Minimum, Maximum, Product: Used in specific scenarios. The median is strong to outliers in regression ensembles. There is no hard-and-fast rule, but certain situations naturally favor certain schemes.
Student Q&A — several students asked about combination rules. The professor emphasized: "When the literature says 'sum,' verify whether they mean a raw sum or an average (sum divided by ). In most implementations, including scikit-learn, the default is majority voting for classification and averaging for regression. Weighted voting is used in boosting where each classifier has a different reliability score ."

14.1.4 Necessary Condition for Ensemble Success

Formal definition — two necessary conditions. An ensemble outperforms its individual members only when both conditions hold: 1. Base classifiers must be (about) independent. The output of one classifier must not determine the output of another. In practice, perfect independence is impossible, but decorrelation is the goal — we want errors to be uncorrelated so they cancel out rather than accumulate. 2. Every base classifier must be better than random guessing. Its error rate must satisfy . Equivalently, accuracy > 50%.
Why the second condition is non-negotiable: Suppose you combine 100 binary classifiers, each with error rate (worse than a coin flip). Each model is wrong more often than it is right. The majority vote now amplifies the wrong answer. The ensemble error can exceed 75%, far worse than any single model. This is because the models are systematically misleading — more votes means more wrong decisions. When , the model is right more often than it is wrong — that is the regime where ensemble methods work. When , the model is actively misleading and combining them makes things worse.
Scope — what breaks these conditions. If your base classifiers are highly correlated (e.g., identical decision trees trained on the same data), the ensemble offers zero benefit — it's just one model repeated. If your base classifiers are worse than random (), the ensemble is guaranteed to be worse than the individual models. This is why we never ensemble models that haven't been verified to beat random guessing on their own.

14.1.5 The Success Zone and Danger Zone (Graph Interpretation)

Visual intuition. Consider a graph where the x-axis is the base classifier error rate and the y-axis is the ensemble classifier error rate : - Diagonal line (): The baseline — points where the ensemble performs exactly the same as a single model. If a single model has error 0.4 and the ensemble also has error 0.4, the point sits on the diagonal. This happens when base classifiers are perfectly correlated (identical). - Success zone (below the diagonal): The ensemble curve bends downward, away from the diagonal. When base error is 0.2, ensemble error may be near zero. When base error is 0.4, ensemble error might be about 0.15. The gap between the diagonal and the curve is the ensemble gain. This is where we want to operate — with and some diversity among classifiers. - Danger zone (above the diagonal, when ): The ensemble curve crosses above the diagonal. The ensemble error exceeds the base classifier error. Combining bad models makes the system worse, not better. Landmark: The curves cross the diagonal at exactly . This is the tipping point — below 0.5, ensemble helps; above 0.5, ensemble hurts.
Worked example — verifying the ensemble gain formula. Consider an ensemble of binary classifiers, each with independent error rate . The ensemble predicts by majority vote. It makes a wrong prediction only when 13 or more of the 25 classifiers are wrong. The ensemble error is: The ensemble error drops from 35% to 6% — a dramatic improvement. Sense-check: with 25 voters each right 65% of the time, it's extremely unlikely that 13+ are simultaneously wrong.

14.1.6 Three Main Ensemble Techniques

Three broad families manipulate the training data in different ways: 1. Bagging (Bootstrap Aggregating): Pick random rows with replacement from the full dataset. Each learner trains on a different bootstrap sample. Training is parallel — all models are independent. 2. Boosting: Models are applied sequentially. Model 2 focuses on the records Model 1 got wrong. Model 3 focuses on whatever Model 2 got wrong. The focus is on hard rows — examples that previous models misclassified. Each model's vote is weighted by its accuracy. 3. Random Forest: Uses bootstrapping (like bagging) but also randomly selects a subset of features at every split. It not only randomizes the rows but also the columns. This double randomization makes it a hybrid between manipulating the training set and manipulating the input features. Why decision trees? Most ensemble implementations use decision trees as base learners. Decision trees can handle non-linear data, are comparatively fast, and are easy to understand. But the base learner can be any model — logistic regression, neural network, linear regression, KNN. The concept is model-agnostic. Parallel vs. sequential training: Bagging trains all models in parallel — they are independent. Boosting trains sequentially — each model depends on the errors of the previous one. Conceptually, boosting is slower, but implementations like XGBoost engage all CPU cores for internal parallel processing and run very fast in practice.
Pitfalls. 1. Assuming any ensemble beats any single model. If your base models are already near-perfect (e.g., 99% accuracy), ensembling adds complexity with negligible gain. The biggest wins come when base models are in the accuracy range. 2. Believing "more models = always better." There is a point of diminishing returns. After a certain number of estimators, accuracy plateaus and training time grows linearly. Plot accuracy vs. number of estimators to find the elbow. 3. Forgetting the rule. A student once tried to ensemble models that were systematically wrong (accuracy 40%). The ensemble accuracy dropped to 20%. The models were "actively misleading" — the professor's exact phrase. 4. Confusing "diverse" with "random." Diversity must be structured — randomizing for the sake of it without ensuring base models are individually competent produces worse results. Every base model must still beat random guessing.
Recap. An ensemble combines multiple diverse base classifiers, each better than random (), to produce a prediction more accurate than any single member. The three main families — bagging, boosting, and random forest — differ in how they create diversity. Bagging randomizes rows. Random forest randomizes rows and features. Boosting focuses sequentially on hard examples. Next: Section 14.2 dives deep into bagging.
Real-world & domain connection. Ensemble methods power some of the most visible machine learning systems. Netflix's recommendation engine uses ensemble techniques to combine hundreds of models. Kaggle competition winners almost invariably use ensembles — XGBoost (a boosting variant) and random forests appear in over 80% of winning solutions. In medical diagnosis, ensembles of classifiers reduce false negatives by ensuring that a disease missed by one model is caught by another. The fundamental insight — that a diverse committee outperforms any single expert — applies far beyond ML. It is why peer review works. It is why prediction markets beat individual forecasters. And it is why Wikipedia is more accurate than any single author.

14.2 Bagging (Bootstrap Aggregating)

Hook. Imagine you're studying for an exam using a single textbook. You know that textbook well, but it has blind spots — some topics are glossed over, others explained poorly. Now imagine you have 50 different textbooks, each covering roughly the same material but with different emphases and examples. If you average what all 50 say about each topic, you'll get a far more reliable answer than any single book could give. That's bagging: train many models on different random slices of the data, then average their predictions. The averaging cancels out the random quirks of any one training sample.

14.2.1 Definition and Concept

Intuition. Think of a chef tasting a soup. If she tastes just one spoonful from the top, she might get a misleading impression — too salty or too bland depending on where she dipped. But if she takes 50 spoonfuls from different parts of the pot and averages the taste, she gets the true flavor. Bagging does this for machine learning: each bootstrap sample is a different "spoonful" of the data, and averaging across them cancels out the sampling noise. The analogy breaks in one place: the chef's spoonfuls don't overlap, but bootstrap samples do — the same data point can appear in multiple samples (sometimes repeatedly within one sample). This overlap is what creates the 63.2% phenomenon (see Section 14.2.4).
Bagging stands for Bootstrap Aggregating. - Bootstrap: Random sampling with replacement from the original training data . - Aggregating: Combining the predictions from all models.

14.2.2 Bagging Algorithm

Purpose. Bagging reduces variance (overfitting) by training multiple models on different random subsets of the data and averaging their predictions. It is most effective with unstable base learners (like deep decision trees) whose predictions change significantly with small data perturbations. Inputs: Training data with observations; number of bootstrap samples ; a base learning algorithm (default: decision tree). Outputs: An ensemble of trained classifiers , plus a combination rule for final prediction.
Steps — the bagging procedure.

Let K = number of bootstrap samples (number of base learners)
For i = 1 to K:
    Create bootstrap sample D_i of size N from D
        (random sampling with replacement — same record can appear multiple times)
    Train base classifier C_i on D_i
End For

For a new instance x:
    Classification: C*(x) = argmax over classes y of Σ δ(C_i(x) = y)
        where δ outputs 1 if C_i predicts class y, 0 otherwise.
    Regression:     ŷ = (1/K) Σ_{i=1}^{K} ŷ_i
For classification: The final prediction is the majority vote. Mathematically, we take the argmax over the class votes. If 3 out of 4 models say "apple" and 1 says "orange," the confidence is 75% and the prediction is "apple." For regression: The final prediction is the average of all individual predictor outputs:

14.2.3 Worked Example — Bagging with Decision Stumps

Fully worked example — bagging on 10 data points with 10 rounds. Setup: - Original dataset: 10 data points with one attribute and class label . - values and true labels:
0.10.20.30.40.50.60.70.80.91.0
+1+1+1−1−1−1−1+1+1+1
- Base learner: Decision stump — a decision tree with only one internal node (one split point). The stump classifies based on a single threshold : → one class, → the other. - Number of rounds (base learners): 10. Round 1 — Bootstrap sample and split: The first decision tree, after seeing its bootstrap sample, identified the split point at . The rule: → class +1, → class −1. Looking at the bootstrap sample: values like 0.2 appeared repeatedly, 0.4 appeared repeatedly, 0.9 appeared repeatedly. Some original values (0.7, 0.8) were not even selected in this round. This is the nature of random sampling with replacement. Observation across rounds: Different bootstrap samples lead to different split points: - Round 1: split at 0.35 → rule: , - Round 2: split at 0.70 — but this stump predicted all records as +1 regardless of (a degenerate classifier caused by a bootstrap sample skewed toward +1) - Round 3: split at 0.35 (same as Round 1 — different bootstrap sample, same split) - Round 4: split at some intermediate point - Round 6: split at 0.75 → rule: , - Round 10: another degenerate classifier (all predictions = +1) due to extreme skew in the bootstrap sample A degenerate classifier occurs when the bootstrap sample is so skewed that one class dominates, making the stump predict the same class on both sides of the split. Combining the votes: The test set is the same as the original set (all 10 records). For each record, we look at what all 10 decision stumps predicted. Below is a representative voting table:
True Round votes (+1/−1)SumPredictionResult
0.1+16 votes +1, 4 votes −1+2+1
0.2+12 votes +1, 8 votes −1−6−1
0.3+15 votes +1, 5 votes −10tie
0.4−12 votes +1, 8 votes −1−6−1
0.5−11 vote +1, 9 votes −1−8−1
0.6−11 vote +1, 9 votes −1−8−1
0.7−12 votes +1, 8 votes −1−6−1
0.8+16 votes +1, 4 votes −1+2+1
0.9+17 votes +1, 3 votes −1+4+1
1.0+18 votes +1, 2 votes −1+6+1
Result: The ensemble correctly classifies 9 out of 10 records (assuming the tie at is broken one way). Even though individual stumps had at best ~70% accuracy, the bagged ensemble achieves ~90%. Sense-check: the hard boundary at is where classes flip; bagging smooths this out through voting.

14.2.4 The 63.2% Problem — A Disadvantage of Bagging

Assumptions & Scope. Bagging assumes each bootstrap sample is drawn uniformly with replacement. Under this scheme, the probability that any given data point appears in a particular bootstrap sample of size is: As , this converges to . So on average, only about 63.2% of the unique original data points end up in a given bootstrap sample. This means each training set is about 37% smaller than the original data in terms of unique records. Some records may not be picked by any model at all (if the number of models is small). Mitigation: Increase the number of base learners (estimators). With 100 or 150 estimators, the chance that a record is never seen by any model becomes very small. Trade-off: Increasing the number of estimators too much can cause overfitting. Individual models may start predicting exactly one or two records, skewing the final prediction. There is no fixed rule for the optimal number — it must be tried for each dataset.

14.2.5 Sensitivity to Base Classifier Stability

Formal explanation — bias-variance decomposition. Bagging reduces variance, not bias. The expected prediction error of any model decomposes as: Bagging attacks the variance term: by averaging across bootstrap samples, the random fluctuations of individual models cancel out. The bias (systematic error from model assumptions) remains unchanged. If a base classifier is stable — meaning its predictions do not change much with minor perturbations in the training set — then bagging may not significantly improve performance. The ensemble's error is primarily caused by bias in the base learner, and bagging reduces variance, not bias. Examples of stable classifiers: linear regression, KNN with large . If a base classifier is unstable — meaning small changes in training data cause large changes in predictions (e.g., deep unpruned decision trees) — then the classifier has high variance. Bagging helps by averaging out the variance across different samples. This is why decision trees are the most common base learner for bagging.
Key point: The accuracy of a bagging ensemble largely depends on the accuracy of the individual models. If the base learners are highly accurate, the ensemble will be highly accurate. If they are weak, bagging may not improve things much — it could even degrade performance because each training set is about 37% smaller.

14.2.6 Student Q&A on Bagging

Q: Won't models get overlapping rows? Some models may not even see all records. A: Yes, because of random sampling with replacement, the same record can be picked multiple times within a single bootstrap sample and across different samples. Some records may not be picked at all by some models. This is overcome by increasing the number of models. With, say, 100 base learners, it is highly unlikely that every model picks the same records or that some records are never seen. The probability that a given record is never selected across bootstrap samples is . For , this is astronomically small ().
Q: Can we select which base learners to use? A: Yes. In the code, the estimator parameter lets you specify the type. The default is decision tree, but you can set it to logistic regression, linear regression, KNN, or other models. However, decision trees are the most common choice because they are unstable (high variance) — exactly the property bagging is designed to fix. Using a stable base learner like logistic regression with bagging typically yields minimal improvement.
Pitfalls. 1. Using too few estimators. With only 5–10 bootstrap samples, the 37% data loss per sample significantly hurts performance. Start with at least 50 and increase until accuracy plateaus. 2. Bagging a stable model. If your base model is already low-variance (e.g., linear regression with strong regularization), bagging adds computation without benefit. Bagging works best on high-variance, low-bias models like deep decision trees. 3. Expecting bias reduction. Bagging only reduces variance. If your base model is systematically wrong (high bias), averaging 100 copies of it won't fix the underlying problem. Fix the bias first, then bag. 4. Ignoring the 63.2% problem for small . When is small (e.g., ), losing 37% of unique data per model is severe. Consider using smaller bootstrap fractions or switching to a different ensemble method.
Recap. Bagging (Bootstrap Aggregating) trains models in parallel on bootstrap samples, then averages (regression) or majority-votes (classification) their predictions. It reduces variance and works best with unstable base learners like decision trees. The cost: each model trains on only ~63% of the unique data. Next: Section 14.3 extends bagging by also randomizing features — this is Random Forest.
Real-world & domain connection. Bagging was introduced by Leo Breiman in 1996 and remains a foundational ensemble technique. In practice, pure bagging is less common than random forest (which adds feature randomization on top of bagging), but the bootstrap principle underpins nearly all modern ensemble methods. Bagging is used in medical risk models where training data is limited and overfitting is a serious concern — averaging over bootstrap samples produces more strong risk estimates. In finance, bagged decision trees help predict loan defaults by reducing the variance that comes from training on volatile historical data.

14.3 Random Forest

Hook. Bagging decorrelates models by giving each one a different random sample of rows. But what if two features are strongly correlated — say, height_in_cm and height_in_inches? Every bagged tree will split on one or the other at the root, making all trees functionally similar despite different row samples. Random forest fixes this by also randomly restricting which columns each tree can see at each split. The result: trees that are forced to discover different patterns in the data, producing genuinely diverse opinions.

14.3.1 Definition and How It Differs from Bagging

Intuition. Imagine you're assembling a panel of doctors to diagnose patients. Bagging gives each doctor a different random subset of patient files (row randomization). But if every doctor was trained at the same medical school and looks at the same set of symptoms, they'll still make similar diagnoses. Random forest goes further: it also forces each doctor to only look at a random subset of symptoms (column randomization). Doctor A sees {temperature, blood pressure, age}. Doctor B sees {cholesterol, weight, heart rate}. Now their diagnoses are truly independent, and the majority vote is much more reliable. The analogy breaks in one place: real doctors would be impaired by missing key symptoms. Random forest trees compensate because each tree still picks the best feature among its random subset — so important features still get used, just not by every tree at every split.
A random forest is an ensemble method specifically designed for decision trees. It combines two forms of randomization: 1. Row randomization (bootstrapping): Like bagging, each tree is trained on a bootstrap sample of the data. 2. Column randomization (feature subsetting): At every internal node of each decision tree, only a random subset of attributes is considered for the split. The tree does not look at all features — it randomly samples features and picks the best among those . This double randomization forces the trees to be decorrelated. If every tree looked at the same data and the same features, they would all make the same mistakes. By forcing different trees to use different features, we ensure they make different mistakes — which is exactly what an ensemble needs. In bagging: Only rows are randomized; all features are available to every model. In random forest: Both rows AND features are randomized at every split.

14.3.2 Random Forest Algorithm

Purpose. Random forest extends bagging by adding feature randomization, producing a more diverse set of decision trees. The double randomization (rows + columns) decorrelates the trees more aggressively than bagging alone, typically yielding better generalization. Inputs: Training data with observations and features; number of trees ; number of features to sample per split (default: for classification, for regression). Outputs: A forest of unpruned decision trees, plus feature importance scores.
Steps — the random forest procedure. 1. For each tree : - Create a bootstrap sample of size from (sampling with replacement). 2. Grow each tree by recursively repeating at every node: - Randomly sample attributes from the total features. - Compute the best split (via information gain, Gini impurity, or entropy) using only those features. - Split the node on the best feature and threshold among the . - Do NOT prune — let the tree grow until all leaves are pure (or until min_samples_split is reached). 3. For prediction on a new instance : - Classification: majority vote across all trees. - Regression: average of all tree predictions.
Why no pruning? Individual trees are allowed to overfit because the final prediction averages across all trees. The overfitting of any single tree is cancelled out by the other trees in the forest. Pruning would reduce variance but also increase bias — exactly the opposite of what we want for an ensemble base learner.

14.3.3 How Many Features Per Split

The number of features to sample at each split follows some standard heuristics: - For classification: where is the total number of features. Example: with 25 features, each split looks at about 5 features. - For regression: . Example: with 24 features, each split looks at about 8 features. These are ballpark numbers — practical rules of thumb derived from empirical studies, not mathematical certainties. In scikit-learn, max_features='sqrt' and max_features='auto' apply these defaults automatically. The algorithm also supports max_features='log2' and explicit integer values.

14.3.4 Random Forest as Dimensionality Reduction

Visual intuition. Imagine a bar chart where each of the features has a bar showing its importance score. After training a random forest, you'll see a few tall bars (the features that consistently produced good splits) and many short bars near zero. The short bars are features the forest learned to ignore — they never helped separate the classes. This is feature selection happening automatically, without any explicit dimensionality reduction step.
Random forest is sometimes considered a dimensionality reduction method. Here is why: Even though features are randomly selected at each split, the algorithm tracks feature importance (based on information gain or Gini impurity reduction). Features with very low predictive power — those that rarely produce good splits — are effectively ignored across the forest. No tree will pick them because they do not help classification. This means the forest naturally identifies which features matter and which do not, similar to how a dimensionality reduction technique prunes irrelevant dimensions. Important clarification: Although we say features are chosen "randomly," the selection is not completely blind. At each split, the algorithm picks the best feature among the randomly chosen ones. Truly useless features are never selected as the best. So the "random" selection still operates within the set of useful features — this is why random forest works despite the apparent randomness.

14.3.5 Code Example Walkthrough

Worked example — training and interpreting a random forest on Iris. Basic random forest in Python:

from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris

iris = load_iris()
X, y = iris.data, iris.target

rf = RandomForestClassifier(
    n_estimators=500,      # 500 trees in the forest
    n_jobs=-1              # use all CPU cores for parallel training
)
rf.fit(X, y)
- n_estimators=500: 500 base learners (trees). Each tree is independent, so all 500 train in parallel. - n_jobs=-1: Performance optimization — uses all available CPU cores. Feature importances after fitting (Iris dataset):
FeatureImportance
Petal length (cm)~0.45
Petal width (cm)~0.42
Sepal length (cm)~0.08
Sepal width (cm)~0.05
The forest overwhelmingly relies on petal dimensions because they cleanly separate the three Iris species. Sepal dimensions contribute little — the forest has effectively performed dimensionality reduction by learning to ignore them. Visualizing individual trees: When max_features=1 is set, each split looks at exactly one randomly chosen feature. A tree might pick "redness" at the root and split on redness <= 50. Another tree might pick "size" at the root, then "redness" at the next split. When max_features=3 (out of, say, 5 total features), at each split the tree randomly picks 3 features, computes information gain only for those 3, and splits on the best among them. The tree does not remember which features were used at previous splits — at every split it freshly samples 3 from all 5. Key parameters: - n_estimators: number of trees (start with 100–500). - max_features: number of features to consider at each split (default: 'sqrt'). - max_depth: maximum depth of each tree (default: None — trees grow unpruned). - min_samples_split: minimum records a node must have to be split (default: 2). - bootstrap=True: enables bootstrapping (default: True). Degenerate trees: In some bootstrap samples, all records may belong to a single class. The tree has nothing to split — the node is already pure. This is normal and expected; the other trees compensate.

14.3.6 Student Q&A on Random Forest

Q: Is the only difference between bagging and random forest the feature selection? A: Yes — that's the key structural difference. In random forest, all base learners are decision trees, and at every split, features are randomly subsetted. In bagging, the base learners can be any model type, and all features are available to every model. Feature importance is a side benefit of random forest that bagging does not provide. The feature importance scores come from aggregating the information gain (or Gini impurity reduction) each feature produces across all trees — this is effectively automatic dimensionality reduction.
Q: How exactly does the random feature selection work during tree building? A: At every split point, the tree randomly picks features from all available features. It does NOT remember which features were already used at higher levels — the sampling is with replacement across splits (though without replacement within a single split). When deciding to split on "cholesterol," it randomly picked 3 features, say {cholesterol, blood pressure, age}, computed information gain for each, and chose cholesterol as the best. At the next split, it again randomly picks 3 features from all available features — it does not eliminate previously-used features. This "reset" at every node is what keeps the trees diverse. The process continues until a leaf is reached or max_depth is hit.
Exam note — from the professor. For exam problems on random forest: know how it differs from bagging (more feature randomization). Know the concept of unpruned trees. And know the ballpark rules — features per split for classification, for regression. The split points will be provided; you do not need to compute information gain for ensemble method problems. For AdaBoost exam problems specifically, you also get the split points. Only for pure decision tree problems must you calculate split points yourself.
Pitfalls. 1. Setting max_features too high. If max_features = d (all features), random forest degrades to bagging. The whole point is to force trees to use different features. Stick to the defaults: sqrt for classification, n/3 for regression. 2. Setting max_features too low. With max_features = 1, every split is essentially random — the tree can't pick the best feature because it only sees one. Accuracy drops sharply. The sweet spot is typically 20–50% of total features. 3. Using too few trees. Random forest needs enough trees for the double randomization to work. With 10 trees, variance reduction is minimal. Start at 100 and increase until out-of-bag error stabilizes. 4. Pruning individual trees. Never prune random forest trees. The entire design relies on individual trees overfitting, then averaging away the overfit. Pruning adds bias and removes the very variance the forest is designed to cancel.
Recap. Random forest = bagging + feature randomization. It trains unpruned decision trees on bootstrap samples, and at every split, each tree only sees a random subset of features. This double randomization produces highly diverse trees whose averaged predictions are more accurate than bagging alone. Feature importance scores provide automatic dimensionality reduction as a bonus. Next: Section 14.4 introduces boosting, which takes a completely different approach — sequential training focused on hard examples.
Real-world & domain connection. Random forest is one of the most widely deployed ML algorithms in industry. It's used in credit scoring (FICO scores incorporate random forest models), medical diagnosis (predicting disease from patient biomarkers), ecology (species distribution modeling), and fraud detection. Its key strengths — resistance to irrelevant features, built-in feature importance, minimal hyperparameter tuning — make it the go-to "first try" algorithm for tabular data problems. In Kaggle competitions, random forest frequently appears in top solutions, often ensembled with gradient boosting models for more gains.

14.4 Boosting and AdaBoost

Hook. You're studying for a final exam. You do a practice test and get 70%. Instead of re-studying everything, you focus intensely on the 30% you got wrong. You take another practice test — now you get 85%, with new mistakes. You focus on those. Repeat. Each round, you get smarter about your specific weaknesses. That's boosting: each new model in the sequence specializes in the mistakes of its predecessors. The final ensemble isn't any single model — it's the weighted wisdom of the entire learning journey.

14.4.1 The Boosting Concept

Intuition. Think of a student (Model 1) who studies the entire syllabus and takes a test. The questions she gets wrong become her "high-priority" study list. The next student (Model 2) inherits this weighted study guide — spending 80% of time on the hard questions and only 20% on the easy ones. Model 2 takes the test, makes different mistakes, and hands an updated priority list to Model 3. After several rounds, the "committee" of students votes, but each student's vote is weighted by how well they did on their own test. The students who aced it get louder votes. The analogy breaks in one place: real students might overfit to the weighted study guide and forget the basics. Boosting guards against this by using shallow trees (depth 2–3) as base learners — they can't overfit much because they're too simple.
Boosting is a sequential ensemble method. Unlike bagging (where all models train independently in parallel), boosting trains models one after another. The core idea: Each subsequent model focuses on the hard rows — the training examples that previous models got wrong. Process: 1. Train Model 1 on the data (or a bootstrap sample of it). 2. Identify which records Model 1 misclassified. 3. Train Model 2, giving extra attention to those misclassified records. 4. Identify which records Model 2 misclassified. 5. Train Model 3, focusing on those new misclassified records. 6. Continue until the error stabilizes or the maximum number of estimators is reached. 7. The final prediction combines the predictions of ALL models (not just the last one). Why sequential works: Individual models do not perform well on the entire dataset, but each works well on some part of it. Model 1 covers most records. Model 2 tackles the ones Model 1 missed. Model 3 tackles the ones Model 2 missed. The errors keep decreasing. When combined, the whole is better than any single part. Dynamic weighting: How does Model 2 "focus" on the misclassified records? The weight of those records is increased, and the weight of correctly classified records is decreased. The next model naturally pays more attention to higher-weighted records.

14.4.2 AdaBoost (Adaptive Boosting) — The Algorithm

Purpose. AdaBoost (Adaptive Boosting) is the foundational boosting algorithm. It sequentially trains weak classifiers (typically shallow decision trees), reweighting training examples after each round so that misclassified examples get higher weight. The final prediction is a weighted majority vote where more accurate classifiers get larger voting weights. Inputs: Training data with samples where ; number of boosting rounds ; a base learning algorithm (typically decision stump or shallow tree). Outputs: A sequence of classifiers with associated importance weights , and a combination rule for final prediction.
Steps — the AdaBoost algorithm (professor's formulation). Let there be training samples and base classifiers . Step 1 — Initialize weights: All records start with equal weight: Step 2 — For each classifier to : (a) Train classifier on the weighted training data (some versions use the full dataset; some versions use a bootstrap sample weighted by ). (b) Compute the error rate : where is the indicator function: outputs 1 if the condition is true (misclassification), 0 otherwise. The professor calls this "the weighted average of the mistakes." (c) Compute the classifier importance : determines how much "voice" classifier has in the final ensemble: - Low (accurate) → large → high importance. - (random) → → no contribution. - (worse than random) → negative → the algorithm resets all weights to and restarts. (d) Update the weights for the next round: For each record : - If classified it correctly: - If classified it incorrectly: Since for a useful classifier, (weight shrinks) and (weight grows). Misclassified records become heavier; correctly classified records become lighter. (e) Normalize the weights: The normalization factor ensures the weights sum to 1 for the next round. Step 3 — Final prediction: For a new instance : Multiply each classifier's prediction by its importance , sum them, and take the sign.
Notation note. The standard reference (Bishop, §14.3) writes the importance as without the factor, and defines the error as . When weights are normalized (sum to 1), this is equivalent to the professor's formulation — the factor simply scales all values, which does not affect the sign of the final prediction. The weight update in Bishop uses , which is consistent with the professor's form when you account for the scaling difference. For exams, use the professor's version exactly as given above.

14.4.3 Full Worked Example — AdaBoost with 10 Data Points

Fully worked example — three boosting rounds on 10 data points. Setup: - 10 data points: - Class labels : +1 for ; −1 for . - Base learner: decision stump (depth-1 tree). - Initial weight for every record: .
Boosting Round 1: Bootstrap sample: The first stump was trained on a weighted subset. Values 0.2 and 0.3 were NOT in the training sample (they were not drawn in this bootstrap). Decision stump split: , . Prediction vs. truth:
True Correct?
0.1+1−1
0.2+1−1
0.3+1−1
0.4−1−1
0.5−1−1
0.6−1−1
0.7−1−1
0.8−1−1
0.9+1+1
1.0+1+1
3 errors out of 10. Error rate: Classifier importance: Weight update: - Correct (7 records): - Incorrect (3 records): Normalization sum: Normalized weights: - Correct records: - Incorrect records (0.1, 0.2, 0.3): Observation: The three misclassified records now carry ~31.1% weight each (up from 10%). The seven correct records carry ~0.96% each (down from 10%). The weight ratio between a hard and easy record is ~32:1.
Boosting Round 2: Weighted bootstrap: Records 0.1, 0.2, 0.3 appear very frequently (high weight). Records 0.4, 0.5, 0.6, 0.7 also present. Decision stump split: , . (Since all , this stump predicts +1 for all 10 records.) Misclassified: (true −1, predicted +1). These had weight ~0.0096 from Round 1. So 4 errors. Weight update (selective examples): - Record 0.1 (was ~0.31, now correct): - Record 0.4 (was ~0.0096, now incorrect): Normalization: Sum of raw weights ≈ 1.000 (after normalizing), giving new normalized weights. Records 0.4–0.7 now carry higher weight than before.
Boosting Round 3: Decision stump split: , . (The assignment flips because, in this bootstrap sample, the left side has more +1 examples.) Misclassified: Records 0.4, 0.5, 0.6 (about, depending on exact boundary). The procedure for , , and weight update follows the same formulas.
Final Ensemble Prediction: For each record , compute: Example for (true label = −1): - (since ) - (since ) - (since ) Full voting table:
True SumPredResult
0.1+1−1.738+2.779+4.119+5.160+1
0.2+1−1.738+2.779+4.119+5.160+1
0.3+1−1.738+2.779+4.119+5.160+1
0.4−1−1.738+2.779−4.119−3.078−1
0.5−1−1.738+2.779−4.119−3.078−1
0.6−1−1.738+2.779−4.119−3.078−1
0.7−1−1.738+2.779−4.119−3.078−1
0.8−1−1.738+2.779−4.119−3.078−1
0.9+1+1.738+2.779−4.119+0.398+1
1.0+1+1.738+2.779−4.119+0.398+1
Result: The AdaBoost ensemble correctly classifies ALL 10 records. Sense-check: the three classifiers cover each other's mistakes — handles the right side, handles the leftmost records, and cleans up the middle. The weighted vote produces perfect classification.

14.4.4 Weight Dynamics — Visual Interpretation

Visual intuition. Imagine a bar chart tracking one record's weight across boosting rounds. For an "easy" record (correctly classified early), the bar shrinks rapidly — like a student who aces every practice test, the system stops worrying about them. For a "hard" record (repeatedly misclassified), the bar grows taller each round — the system screams "pay attention to me!" A record whose bar keeps growing after many rounds may be an outlier or mislabeled; the algorithm is wasting capacity trying to fit noise.
Look at how weights change across rounds for representative records:
RecordRound 1 WeightRound 2 WeightRound 3 WeightInterpretation
Easy (e.g., 0.9)0.10 → 0.010→ 0.005→ 0.002Correctly classified every round. Weight steadily decreases.
Hard type A (e.g., 0.1)0.10 → 0.311→ 0.019→ 0.010Misclassified R1, then corrected R2–R3. Weight spiked then fell.
Hard type B (e.g., 0.5)0.10 → 0.010→ 0.155→ 0.350Correct R1, then misclassified R2–R3. Weight keeps increasing.
A record whose weight keeps increasing is hard to classify — multiple models struggle with it. If the weight keeps increasing even after many rounds, the record may be an outlier or the data may be noisy. This is one failure mode of boosting (see Section 14.4.5).

14.4.5 When Boosting Fails

Assumptions & Scope. AdaBoost assumes: 1. Enough data. Boosting needs enough training examples for the sequential correction to work. With very small , the reweighting mechanism has too few data points to redistribute meaningfully. 2. Weak base learners. The base classifiers should be weak — slightly better than random. Using deep, complex trees (depth > 5) as base learners causes the ensemble to overfit aggressively. Standard practice: decision stumps (depth 1) or shallow trees (depth 2–3). 3. Clean(ish) labels. Boosting is sensitive to outliers and mislabeled data. Because misclassified records get exponentially increasing weight, a single mislabeled point can dominate the later rounds, causing the ensemble to chase noise. What breaks when assumptions fail: - Not enough data: The reweighting has no meaningful effect — all records end up with similar weights, and boosting degenerates to training the same model repeatedly. - Deep base learners: Individual trees overfit their weighted subset, and the ensemble overfits the training data as a whole. Test accuracy drops sharply. - Noisy labels: The algorithm assigns ever-increasing weight to points that cannot be correctly classified (because their label is wrong). The ensemble wastes all its capacity on these points.

14.4.6 AdaBoost Properties

Formal properties of AdaBoost. - Exponential loss minimization. AdaBoost can be derived as greedy minimization of the exponential loss where . Each round adds the classifier that most reduces this loss. - Fast and simple to program. The algorithm has no hyperparameters besides (the number of rounds). No learning rate tuning, no regularization parameter. - No assumption on the weak learner. Unlike linear models (which assume linear decision boundaries), AdaBoost with decision tree base learners handles both linear and non-linear data. This is why decision trees are the preferred base learner. - Sensitivity to outliers. Because the exponential loss penalizes large negative margins exponentially (not linearly), a single badly misclassified outlier can dominate the later rounds. Cross-entropy loss (used in logistic regression) grows only linearly with margin violation, making it more strong. This is one reason gradient boosting (which can use any differentiable loss) is often preferred over AdaBoost in practice.

14.4.7 Code Example — Ensemble Methods Comparison

Worked code comparison — bagging, random forest, AdaBoost, and gradient boosting on breast cancer data. Setup:

from sklearn.ensemble import (
    BaggingClassifier,
    RandomForestClassifier,
    AdaBoostClassifier,
    GradientBoostingClassifier
)
from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer

data = load_breast_cancer()
X, y = data.data, data.target
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, stratify=y, random_state=42
)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
Baseline single decision tree: Accuracy ≈ 0.9123. Bagging:

bag = BaggingClassifier(
    estimator=DecisionTreeClassifier(),
    n_estimators=50,
    max_samples=0.8,      # each tree sees 80% of rows
    max_features=0.8      # each tree sees 80% of columns
)
bag.fit(X_train, y_train)

Accuracy ≈ 0.95 — ~4.4% improvement over baseline

Random Forest:

rf = RandomForestClassifier(
    n_estimators=100,
    max_depth=10,
    min_samples_split=5
)
rf.fit(X_train, y_train)

Accuracy ≈ 0.9561

AdaBoost:

ada = AdaBoostClassifier(
    estimator=DecisionTreeClassifier(max_depth=1),
    n_estimators=50,
    learning_rate=1.0     # scales α_i; 1.0 = no scaling
)
ada.fit(X_train, y_train)
Learning rate effect: Accuracy vs. learning rate followed an inverted-U shape — peaked around 1.0–1.5, then dropped as learning rate increased further. The learning rate scales , controlling how aggressively weights are updated each round. Number of trees effect: Accuracy initially dipped (1→5 trees), then rose steadily, plateauing at ~23–24 trees. Beyond 25 trees, adding more trees gave no meaningful improvement — the ensemble had saturated. Summary: On this relatively clean dataset, all ensemble methods performed similarly (within ~1–2% of each other). The key takeaway: ensemble methods consistently beat a single decision tree, and the choice among them often depends on data characteristics (size, noise, feature correlations) rather than one being universally "best."

14.4.8 Student Q&A on AdaBoost

Q (several students): Why is the same used for both correctly-classified and misclassified weight updates? A: is the importance of the classifier — it's a single number that captures how reliable this classifier is. For correctly classified records, multiplying by reduces the weight — the classifier already handles them well, so the next classifier can pay them less attention. For misclassified records, multiplying by increases the weight — they need more attention. Using the same in both places is the mathematical mechanism that redistributes focus from easy examples to hard ones. The symmetry is elegant: a highly accurate classifier ( large) dramatically shrinks weights of its correct predictions and dramatically inflates weights of its mistakes.
Q: How is the normalization factor calculated? A: is the sum of all raw (unnormalized) weights after the update step. After computing for every record , sum those raw values: . Then divide each raw weight by to get normalized weights that sum to 1. In the worked example Round 1, . Without normalization, the weights would grow or shrink unboundedly across rounds.
Q: Why did the decision boundary assignment flip in Round 3 (left side = +1, right side = −1)? A: The assignment of +1 or −1 to the left or right side depends on the majority class in each region of the weighted data. The decision stump chooses the split point and then assigns each side the majority class among the (weighted) training points falling there. Since the weights change dramatically between rounds, the majority class on each side can flip. What matters is consistency within a single tree — each stump uses its own assignment consistently. The final ensemble doesn't care which side is which; it only cares that each classifier's vote is weighted by .
Pitfalls. 1. Using deep trees as base learners. AdaBoost is designed for weak learners. Using DecisionTreeClassifier(max_depth=10) as the base estimator causes severe overfitting. Always use max_depth=1 (decision stump) or max_depth=2. 2. Not tuning the learning rate. The learning_rate parameter scales . Too high → aggressive weight updates, overfitting. Too low → slow convergence, needs many more estimators. Grid search over [0.1, 0.5, 1.0, 1.5, 2.0]. 3. Running too many rounds on noisy data. If the data has mislabeled examples, AdaBoost will assign them exponentially growing weight. After many rounds, the ensemble chases noise. Monitor validation error and stop early. 4. Forgetting that triggers a reset. If any round produces , the algorithm resets all weights to . This is a safety valve — it means the current weighting is hopeless and the algorithm starts fresh. Don't be surprised if this happens on very noisy data.
Recap. Boosting trains classifiers sequentially, with each new model focusing on the examples its predecessors got wrong. AdaBoost formalizes this with: (1) weighted error , (2) classifier importance , (3) weight updates , and (4) final prediction . The algorithm works best with weak base learners (shallow trees) and clean labels. Next: Section 14.5 compares all three ensemble methods side-by-side.
Real-world & domain connection. AdaBoost was invented by Freund and Schapire in 1996 and won the Gödel Prize in 2003 — one of the rare ML algorithms recognized with a major theoretical computer science award. In practice, AdaBoost has been largely superseded by gradient boosting (XGBoost, LightGBM, CatBoost) which offer better handling of arbitrary loss functions, built-in regularization, and faster training. However, AdaBoost remains the clearest introduction to the boosting concept. It is still used in face detection (the Viola-Jones face detector uses AdaBoost with Haar-like features) and in domains where interpretability of the sequential weighting is valued.

14.5 Model Comparison and Practical Considerations

Hook. You've now seen three different ways to build an ensemble. The natural question: which one should you use? The answer depends on your data, your compute budget, and what kind of mistakes you can afford. This section puts bagging, random forest, and boosting side by side so you can choose intelligently — and introduces the modern boosting variants that dominate Kaggle.

14.5.1 Summary of Three Ensemble Techniques

Comparison — when to pick which.
DimensionBaggingRandom ForestBoosting (AdaBoost)
Core ideaAverage over random data subsetsBagging + random feature subsetsSequentially focus on hard examples
Row randomizationYes (bootstrap)Yes (bootstrap)Optional (version-dependent)
Feature randomizationNoYes (at every split)No
TrainingParallelParallelSequential
Base learnersAny modelDecision trees onlyUsually decision trees (shallow)
Variance reductionHighVery highModerate (can increase variance if overfit)
Bias reductionNoneNoneYes — sequential correction reduces bias
Overfitting riskLowLowModerate–High (sensitive to noisy data)
Best forHigh-variance base modelsTabular data with many featuresClean data where base models are weak
InterpretabilityLowMedium (feature importance)Low
When to pick which: - Bagging: When you have a high-variance base model (like a deep decision tree) and want a simple, strong ensemble. Good first choice when you're not sure. - Random Forest: When you have many features, some of which may be irrelevant. The built-in feature selection and strongness make it the best "default" ensemble for tabular data. - Boosting: When your base models are genuinely weak (barely better than random) and you need to reduce bias as well as variance. Best on clean, well-labeled data.

14.5.2 Practical Coding Parameters

Practical guidance — selecting hyperparameters. In Python (scikit-learn), the key parameter for the number of base learners is n_estimators. Typical starting values:
MethodTypical n_estimators rangeNotes
Bagging50–200Fewer needed if base model is strong
Random Forest100–500More trees = smoother decision boundary
AdaBoost50–200Stop when validation error plateaus
Gradient Boosting100–1000Need more than AdaBoost due to learning rate scaling
Trade-off with too many trees: More trees → more computation time (linear), marginal accuracy gains diminish. Too few trees → not enough randomization, some records may never be seen (especially in bagging). Determining the right number: Plot validation accuracy against number of trees. Find where the curve flattens (the "elbow"). Use that number. For most datasets, 100–200 trees is enough for random forest; 50–100 for AdaBoost.

14.5.3 Gradient Boosting and XGBoost

Preview — beyond AdaBoost. AdaBoost is the pedagogical entry point to boosting, but modern practice uses gradient boosting. The key differences: - Gradient Boosting: Generalizes AdaBoost by allowing any differentiable loss function (not just exponential loss). Each new tree fits the negative gradient (residuals) of the loss with respect to the current ensemble prediction. This makes it strong to outliers (using Huber loss or absolute error instead of exponential). - XGBoost (Extreme Gradient Boosting): Adds regularization (L1/L2 on leaf weights), tree pruning (max_depth), column subsampling (like random forest), and highly optimized parallel computation. Despite boosting being conceptually sequential, XGBoost parallelizes the split-finding within each tree across CPU cores. - LightGBM and CatBoost: Further optimizations — LightGBM uses histogram-based splitting for speed; CatBoost handles categorical features natively.
These topics will be covered in detail in a subsequent session. For now, know that XGBoost is the algorithm behind most Kaggle competition winners and is the go-to choice for structured/tabular data when maximum accuracy is the goal.

14.5.4 Student Discussion — Exam Format and Course Logistics

Q: Are past papers available? A: The learning facilitator will upload past papers. Check the course portal.
Q: Are annotated slides (handwritten notes on slides) allowed in the exam? A: Only watermarked common slides are allowed. Individual faculty annotations will not be present because a common set of watermarked slides is distributed across all parallel batches. Handwritten notes are not allowed. Only the officially watermarked slides and textbooks may be used during the exam.
Q: When are extra/review sessions held? A: Extra sessions are typically held on Fridays, which makes it difficult for working professionals to catch up before Saturday's class. The faculty acknowledged this concern and will pass the feedback to the operations team to consider scheduling extra sessions on Monday or Tuesday for future semesters.
Pitfalls. 1. Blindly defaulting to XGBoost for everything. While XGBoost is powerful, it has many hyperparameters and can overfit on small datasets. For , random forest is often more strong with less tuning. 2. Using boosting on noisy data without regularization. AdaBoost's exponential loss explodes on outliers. If your data has label noise, use gradient boosting with a strong loss (Huber) or stick to bagging/random forest. 3. Ignoring the sequential nature of boosting for latency. In production systems where inference latency matters, boosting requires evaluating all trees sequentially (though tree traversal is fast). Bagging and random forest can evaluate all trees in parallel.
Recap. Bagging, random forest, and boosting are the three pillars of ensemble learning. Bagging reduces variance through parallel bootstrap samples. Random forest adds feature randomization for stronger decorrelation. Boosting reduces both bias and variance through sequential focus on hard examples. For modern applications, gradient boosting (XGBoost, LightGBM) is the state of the art, but random forest remains the best "no-tuning-required" baseline. The exam will test your ability to work through bagging and AdaBoost examples by hand — study the worked examples in Sections 14.2 and 14.4 carefully.
Real-world & domain connection. The ensemble methods covered in this lecture power critical systems across industries. Random forest is used in Microsoft's Kinect for body-part recognition, in computational biology for gene selection, and in finance for credit risk modeling. XGBoost dominates structured-data competitions and is deployed at companies like Uber (demand prediction), Airbnb (pricing), and Stripe (fraud detection). The ensemble principle — combining many weak models into one strong one — is a reliable way to improve performance on tabular data. It is often the difference between a prototype and a production-ready model.

Exam Guidance Summary

Exam note — what to expect and how to prepare. The professor gave specific guidance on the exam format. Focus your study time on the problem types listed below. The problems in the lecture slides are representative — expect different numerical values but the same structure.

Concept Questions (Ensemble Foundations)

- Two core challenges: Know that every ensemble method must solve (1) creating diversity among base learners and (2) combining their votes. - Four diversity strategies: Be able to list and give an example of each — different algorithms, different hyperparameters, different input representations, different training sets. - Necessary condition: for every base classifier. Be able to explain why — because combining models that are wrong more often than right amplifies errors. - Success/danger zone graph: Know the x-axis (base classifier error), y-axis (ensemble error), the diagonal baseline, and which side is which zone. Be able to sketch and label it.

Bagging Problems

- Format: You will be given a dataset (typically 10 points, one feature, binary labels), a set of bootstrap samples with their split points, and the split rules for each round. - What you must do: For each test record, compute what each stump predicts, aggregate the votes (sum or majority), and determine the final ensemble prediction. - Key skill: Tallying votes correctly and handling degenerate classifiers (stumps that predict the same class regardless of input). - Study: Work through the Section 14.2.3 example until you can do it without looking.

Random Forest (Conceptual)

- Know the difference from bagging: random forest adds feature randomization at every split. - Know why trees are unpruned: individual overfitting is cancelled by averaging. - Know the ballpark rules: features per split for classification, for regression. - You will not be asked to compute information gain for random forest problems on the exam — split points are given.

AdaBoost Numerical Problems

- Format: Similar to bagging but with sequential rounds and dynamic weights. You'll be given split points for each round. - What you must compute (for each round): 1. Error rate: 2. Classifier importance: 3. Weight updates: (correct) or (incorrect) 4. Normalize: divide by - Final prediction: - Common mistake: Forgetting to normalize weights after each round. The weights must sum to 1 before computing the next round's error. - Study: Work through the Section 14.4.3 three-round example. Then try it with different split points to build fluency.

What Is NOT on This Exam

- You will not need to compute information gain / entropy for ensemble method problems. Split points are provided. - You will not be tested on gradient boosting or XGBoost details — coverage is conceptual only. - Naive Bayes problems (mentioned by the professor) are from a different lecture — they may appear on the same exam but are separate from ensemble methods.

Study Strategy

The professor emphasized: "Minimum 3 problems are included per concept in the slides. Study those." The worked examples in Sections 14.2.3 and 14.4.3 are your primary study material for numerical questions. For conceptual questions, know the comparison table in Section 14.5.1 cold.

Key Industry Applications

Where Ensemble Methods Are Used Today

- Random Forest and XGBoost: The two most commonly deployed ensemble methods in production ML systems. Random forest is preferred when interpretability and stability matter; XGBoost when raw predictive power is the priority. - XGBoost in competitions: Dominates Kaggle competitions — used in over 50% of winning solutions for structured data problems. Its speed comes from parallelizing the split-finding within each tree (evaluating all candidate splits simultaneously across CPU cores), even though trees are built sequentially. LightGBM (Microsoft) and CatBoost (Yandex) are strong alternatives with different speed/accuracy trade-offs. - Decision trees as base learners: Preferred across all ensemble methods. They handle both linear and non-linear relationships without feature engineering. They are fast to train compared to neural networks. They work naturally with bootstrap and reweighting frameworks. And they produce interpretable rules when needed.

Python Libraries and Tools

- scikit-learn (sklearn.ensemble): The standard library for ensemble methods in Python. Provides BaggingClassifier, BaggingRegressor, RandomForestClassifier, RandomForestRegressor, AdaBoostClassifier, AdaBoostRegressor, GradientBoostingClassifier, GradientBoostingRegressor. The estimator parameter in bagging can be set to any scikit-learn model. - XGBoost (xgboost): Standalone library with its own API (xgboost.XGBClassifier, xgboost.XGBRegressor). Supports GPU acceleration, early stopping, and built-in cross-validation. - LightGBM (lightgbm): Microsoft's gradient boosting framework. Uses histogram-based splitting for faster training on large datasets. Particularly good for high-dimensional data. - CatBoost (catboost): Yandex's gradient boosting library. Handles categorical features natively without one-hot encoding. Often the best out-of-the-box performance with default hyperparameters.

Real-World Datasets and Benchmarks

- Breast Cancer Wisconsin dataset: Built into scikit-learn (sklearn.datasets.load_breast_cancer). 569 samples, 30 features, binary classification. Commonly used for demonstrating ensemble methods. - Wine dataset: Also in scikit-learn. 178 samples, 13 features, 3-class classification. Good for showing multi-class ensemble behavior. - Iris dataset: 150 samples, 4 features, 3-class classification. Used in the Random Forest code walkthrough (Section 14.3.5).

Feature Importance in Practice

Random forest and gradient boosting both provide feature importance scores automatically. In industry, these are used to: - Feature selection: Drop low-importance features to reduce model complexity and training time. - Model interpretability: Show stakeholders which factors drive predictions (e.g., "credit score is the #1 predictor of loan default"). - Debugging: Identify data leakage — if a suspicious feature (like a customer ID) has abnormally high importance, something is wrong with the data pipeline. The importance is computed by aggregating the impurity reduction (Gini or entropy) each feature produces across all trees in the forest. Features that consistently produce large impurity reductions get high importance scores.

ML Lecture 14 notes · Ensemble Methods — Bagging, Random Forest, and Boosting

Machine Learning· postgraduate· 2026-06-29

Sections Breakdown

114.1 Ensemble Learning — Review and Foundations

Core ensemble concepts: diversity, combining votes, the E < 0.5 rule, success vs. danger zones

214.2 Bagging (Bootstrap Aggregating)

Bootstrap sampling, parallel training, the 63.2% problem, bias-variance decomposition

314.3 Random Forest

Double randomization (rows + columns), feature importance, unpruned trees, code walkthrough

414.4 Boosting and AdaBoost

Sequential training, AdaBoost algorithm, weight dynamics, worked example with 10 data points

514.5 Model Comparison and Practical Considerations

Comparison table, practical coding parameters, gradient boosting and XGBoost preview

6Exam Guidance Summary

Exam format, bagging and AdaBoost numerical problems, study strategy

7Key Industry Applications

Real-world usage, Python libraries, feature importance in practice

Postgraduate students in Machine Learning

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.

Ensemble Learning Foundations

Must-know: An ensemble combines multiple diverse base classifiers, each with error rate , to produce a prediction more accurate than any single member. Two necessary conditions: (1) base classifiers must be approximately independent, (2) every classifier must beat random guessing ().

Top pitfall: Assuming any ensemble beats any single model. If base models are already near-perfect (99% accuracy), ensembling adds complexity with negligible gain.

Self-check: Why does the ensemble error drop below the individual error rate when ?

Connects to: Bagging, Random Forest, Boosting, Bias-Variance Decomposition

Bagging (Bootstrap Aggregating)

Must-know: Bagging trains models in parallel on bootstrap samples (random sampling with replacement). It reduces variance (not bias) and works best with unstable base learners like deep decision trees. Final prediction: majority vote (classification) or average (regression).

Top pitfall: Each bootstrap sample contains only ~63.2% of unique records. Using too few estimators (e.g., 5-10) means significant data loss per model.

Self-check: In the bagging worked example, why does a degenerate classifier (predicting all +1) occur?

Connects to: Bootstrapping, Random Forest, Bias-Variance Tradeoff

Random Forest

Must-know: Random Forest = bagging + feature randomization. At every split, each tree randomly samples features from the total . Defaults: for classification, for regression. Trees are unpruned \u2014 individual overfitting is cancelled by averaging. Provides feature importance scores as a side benefit.

Top pitfall: Setting max_features = d (all features) degrades random forest to plain bagging. Never prune individual trees.

Self-check: How does the double randomization (rows + columns) make random forest trees more decorrelated than bagging?

Connects to: Bagging, Feature Importance, Dimensionality Reduction

Boosting and AdaBoost

Must-know: AdaBoost trains classifiers sequentially, each focusing on misclassified examples from the previous round. Key formulas: weighted error , classifier importance , weight update , final prediction . Works best with weak learners (decision stumps, depth 1).

Top pitfall: Using deep trees as base learners (depth > 2) causes severe overfitting. AdaBoost is designed for weak learners. Also, forgetting to normalize weights after each round.

Self-check: Walk through one AdaBoost round: compute error rate, alpha, update weights for correct and incorrect records, and normalize.

Connects to: Gradient Boosting, XGBoost, Ensemble Diversity

Model Comparison

Must-know: Bagging reduces variance (parallel, any base model). Random Forest reduces variance more via feature randomization (decision trees only, parallel). Boosting reduces both bias and variance (sequential, weak learners). For modern applications: XGBoost/LightGBM for maximum accuracy, Random Forest for strong no-tuning baseline.

Top pitfall: Blindly defaulting to XGBoost for everything. For N < 1000, random forest is often more stable with less tuning.

Self-check: When would you choose bagging over random forest, and when would you choose boosting over both?

Connects to: Bias-Variance Decomposition, Gradient Boosting, XGBoost

Was this lecture useful?

Loading comments…
🤖

BitsNotes AI Assistant

Subject Notes Assistant

Configure AI Chat

Choose how to access the chatbot
Have your own API key?

Switch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.

🔑 Enter API key above to fetch live models from provider, or enter model name manually.
OpenAI-Compatible API Support

Choose any provider preset (Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenAI, Groq, Ollama, etc.) or enter a custom endpoint URL.

Security & Privacy First

Your API key is sent directly from your browser to your specified provider. BitsNotes servers never store or see your key.