KatInterview

Build a Bagging Ensemble Classifier from Scratch

Machine LearningModel answer
HardModel answerMachine Learningensemble learningdecision treesbootstrap sampling

Last 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 seed to initialize a local random.Random instance (not the global random module).
  • The pairing between feature vectors and labels must be preserved.

2. fit(X, y)

Train the ensemble:

  • Create n_estimators bootstrap samples.
  • Fit one fresh DecisionTree on 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, or None for non-deterministic behaviour.
  • tree_params: optional dict passed as keyword arguments to each DecisionTree.

Constraints and edge cases to handle

  • len(X) != len(y) → raise ValueError
  • Empty training set or empty prediction input
  • predict called before fit
  • Re-calling fit must 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.