Build a Bagging Ensemble Classifier from Scratch
Machine LearningModel answerLast updated
Implement bootstrap sampling, multi-tree training, and majority-vote aggregation for a bagging classifier using only Python lists and the standard library.
Build a Bagging Ensemble Classifier from Scratch
Ensemble methods are a cornerstone of practical machine learning. One of the simplest and most effective is bagging (bootstrap aggregating): train several independent models on slightly different views of the data, then combine their outputs. The result typically has lower variance than any single model alone.
Your task is to implement a BaggingClassifier that wraps a provided DecisionTree class. Do not use NumPy. Represent all data as plain Python lists and use only the standard library.
What you are given
A DecisionTree class (already implemented in the template) with the following interface:
tree = DecisionTree(**params)
tree.fit(X, y) # X: list of feature vectors, y: list of labels
preds = tree.predict(X) # returns a list of predicted labels
You do not need to implement DecisionTree itself.
What you must implement
1. bootstrapping(X, y, seed=None)
Draw a bootstrap sample of size n = len(X) with replacement from the rows of X and y. Return the pair (X_sample, y_sample).
- Use
seedto initialize a localrandom.Randominstance (not the globalrandommodule). - The pairing between feature vectors and labels must be preserved.
2. fit(X, y)
Train the ensemble:
- Create
n_estimatorsbootstrap samples. - Fit one fresh
DecisionTreeon each sample. - Store the trained trees for later use.
- Seed each tree's bootstrap draw independently but reproducibly, derived from a master
random_state.
3. predict(X)
Return one final prediction per row:
- Collect predictions from every tree.
- Combine them via majority vote.
- State explicitly how you break ties, and make sure the rule works for any hashable label type.
Constructor signature
BaggingClassifier(n_estimators=10, random_state=None, tree_params=None)
n_estimators: number of trees; must be ≥ 1.random_state: integer seed for the master RNG, orNonefor non-deterministic behaviour.tree_params: optional dict passed as keyword arguments to eachDecisionTree.
Constraints and edge cases to handle
len(X) != len(y)→ raiseValueError- Empty training set or empty prediction input
predictcalled beforefit- Re-calling
fitmust not carry over trees from a previous run n_estimators < 1→ reject in the constructor
What a complete answer looks like
- Working implementation of all three methods, with error handling
- A clear statement of your tie-breaking rule and why it is deterministic
- Time and space complexity for each method
- Discussion of at least two non-trivial edge cases
Hints
Hint 1
Bootstrap sampling means drawing with replacement: pick n random indices from range(len(X)) and use those same indices to index both X and y. Sampling X and y separately is a classic bug that silently destroys the label pairing.
Hint 2
For reproducibility without global side effects, construct a local random.Random(seed) inside bootstrapping rather than calling random.seed() globally. In fit, use one master RNG seeded by random_state to generate a distinct integer seed for each tree's bootstrap call.
Hint 3
Majority vote with max(counts, key=counts.get) returns the first key inserted that reaches the maximum count, because Python dicts preserve insertion order and max() returns the first maximum it encounters. Build the counts dict by iterating trees in order, and that becomes your tie-break rule: the label first predicted by the lowest-indexed tree wins.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Bagging works in three phases: sample, train, and vote. Each phase has its own correctness considerations and common pitfalls.
Phase 1 — Bootstrap sampling
A bootstrap sample of size n is n draws with replacement from the original n rows. The right implementation is:
- Generate
nrandom indices, each in[0, n). - Use those same indices to slice both
Xandy.
Sampling X and y with independent index lists is the single most common bug here — it silently shuffles labels away from their feature vectors.
For reproducibility, construct a local random.Random(seed) instance rather than calling random.seed() globally. The global RNG is shared state; touching it from inside a helper method causes hard-to-trace non-determinism in anything else that uses randomness.
def bootstrapping(self, X, y, seed=None):
if len(X) != len(y):
raise ValueError("X and y must have the same length")
n = len(X)
if n == 0:
raise ValueError("cannot bootstrap an empty dataset")
rng = random.Random(seed)
indices = [rng.randrange(n) for _ in range(n)]
return [X[i] for i in indices], [y[i] for i in indices]
On average, each bootstrap sample contains about 1 − (1 − 1/n)^n ≈ 63.2% of the unique original rows. The remaining ~36.8% ("out-of-bag" rows) could be used as a free internal validation set — a useful extension to mention.
Phase 2 — Fitting the ensemble
The master RNG, seeded by random_state, generates one integer seed per tree. This makes the whole ensemble reproducible while ensuring every tree sees a different bootstrap sample.
def fit(self, X, y):
if len(X) != len(y):
raise ValueError("X and y must have the same length")
if len(X) == 0:
raise ValueError("cannot fit on an empty dataset")
master_rng = random.Random(self.random_state)
self.trees = [] # reset: no leakage from prior fit calls
for _ in range(self.n_estimators):
seed = master_rng.randrange(2**32)
X_s, y_s = self.bootstrapping(X, y, seed=seed)
tree = DecisionTree(**self.tree_params)
tree.fit(X_s, y_s)
self.trees.append(tree)
return self
Resetting self.trees = [] before the loop is essential. Forgetting it means re-calling fit doubles (or triples, etc.) the ensemble silently.
Phase 3 — Majority vote with deterministic tie-breaking
Call each tree's predict once on the whole batch rather than once per row — that cuts the number of Python-level method calls from B × m down to B.
def predict(self, X):
if not self.trees:
raise RuntimeError("call fit before predict")
if len(X) == 0:
return []
all_preds = [list(tree.predict(X)) for tree in self.trees]
results = []
for j in range(len(X)):
counts = {}
for preds in all_preds:
label = preds[j]
counts[label] = counts.get(label, 0) + 1
results.append(max(counts, key=counts.get))
return results
Tie-breaking rule: max() returns the first maximal element it encounters. Because dict preserves insertion order (Python 3.7+) and we iterate trees from index 0 upward, the tied label that was first predicted by the lowest-indexed tree wins. This rule is fully deterministic given the seed, requires no comparison between labels, and therefore works for any hashable type — including mixed or non-orderable labels. An alternative is to sort tied labels and pick the lexicographically smallest, but that breaks if labels are not comparable.
Complete implementation
import random
class BaggingClassifier:
def __init__(self, n_estimators=10, random_state=None, tree_params=None):
if n_estimators < 1:
raise ValueError("n_estimators must be >= 1")
self.n_estimators = n_estimators
self.random_state = random_state
self.tree_params = dict(tree_params) if tree_params else {}
self.trees = []
def bootstrapping(self, X, y, seed=None):
if len(X) != len(y):
raise ValueError("X and y must have the same length")
n = len(X)
if n == 0:
raise ValueError("cannot bootstrap an empty dataset")
rng = random.Random(seed)
indices = [rng.randrange(n) for _ in range(n)]
return [X[i] for i in indices], [y[i] for i in indices]
def fit(self, X, y):
if len(X) != len(y):
raise ValueError("X and y must have the same length")
if len(X) == 0:
raise ValueError("cannot fit on an empty dataset")
master_rng = random.Random(self.random_state)
self.trees = []
for _ in range(self.n_estimators):
seed = master_rng.randrange(2**32)
X_s, y_s = self.bootstrapping(X, y, seed=seed)
tree = DecisionTree(**self.tree_params)
tree.fit(X_s, y_s)
self.trees.append(tree)
return self
def predict(self, X):
if not self.trees:
raise RuntimeError("call fit before predict")
if len(X) == 0:
return []
all_preds = [list(tree.predict(X)) for tree in self.trees]
results = []
for j in range(len(X)):
counts = {}
for preds in all_preds:
label = preds[j]
counts[label] = counts.get(label, 0) + 1
results.append(max(counts, key=counts.get))
return results
Complexity
Let n = training rows, d = features, B = n_estimators, m = test rows.
| Method | Time | Extra space |
|---|---|---|
bootstrapping | O(n) | O(n) for indices and sampled lists |
fit | O(B · d · n log n) with CART trees | O(n) per sample + O(B · tree size) |
predict | O(B · m · depth + B · m) | O(B · m) for stored predictions |
Rows in the bootstrap sample are references, not deep copies, so memory usage is proportional to n, not to the size of each row object.
Why bagging helps
If each tree has variance σ² and pairwise correlation ρ, the ensemble variance is ρσ² + (1−ρ)σ²/B. More trees drive the second term toward zero. Bootstrap sampling keeps ρ < 1 because each tree sees a different dataset. Bias is roughly unchanged — bagging is purely a variance-reduction technique, which is why it works best on low-bias, high-variance learners like deep decision trees.
Common mistakes
- Sampling
Xandywith separate index draws — destroys label pairing. - Using the global
randommodule insidebootstrapping— causes side effects and non-reproducibility. - Calling
tree.predictonce per row in a loop — unnecessary overhead. - Forgetting to reset
self.treesinfit— old trees contaminate re-fits. - Tie-breaking by sorting labels — fails for non-comparable label types.