Build a random forest classifier on top of scikit-learn decision trees

Quick Overview

Implement a random forest classifier on top of scikit-learn decision trees, with helpers that resolve max_features, draw bootstrap samples and take a majority vote. It tests bagging, reproducible seeding, probability column alignment when a bootstrap misses a class, and vectorized tie-breaking.

Build a random forest classifier on top of scikit-learn decision trees

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement a random forest classifier in Python that uses scikit-learn's `DecisionTreeClassifier` as its base tree, along with three helper functions. `fit` trains each tree on its own sample of rows, `predict_proba` averages the trees' class probabilities, and `predict` takes a hard majority vote over the trees' predicted labels. The helpers: - `resolve_max_features(max_features, n_features)` returns how many features each split considers, with `d = n_features`. `"sqrt"` and `"log2"` give the floor of $\sqrt{d}$ and $\log_2 d$, `None` gives `d`, an int is used as given, and a float `f` gives `int(f * d)`. Clip the result to the range 1 to `d`. Any other value raises `ValueError`. - `bootstrap_indices(n, rng)` returns `rng.integers(0, n, size=n)`, where `rng` is a NumPy `Generator`. - `majority_vote(preds, classes)` takes tree predictions of shape `(n_trees, n_samples)` and the sorted array of class labels, and returns the most voted label for each sample. Ties go to the lowest label. The class is `RandomForestClassifier(n_estimators=10, max_features="sqrt", max_depth=None, bootstrap=True, random_state=0)`, with these rules: - `fit(X, y, sample_indices=None)` creates one `np.random.default_rng(random_state)` and draws the trees' bootstrap samples from it in order, one tree after another. Tree `i` is a `DecisionTreeClassifier` with `max_features=max_features_`, the forest's `max_depth`, and `random_state=random_state + i`. - When `sample_indices` (a list of index arrays) is passed, it replaces sampling: tree `i` trains on rows `sample_indices[i]`, and the number of trees is `len(sample_indices)`. With `bootstrap=False` and no `sample_indices`, every tree trains on `np.arange(n)`. - After `fit`, the forest exposes `classes_` (sorted unique labels), `max_features_`, `estimators_` (the fitted trees) and `estimator_samples_` (the row indices each tree trained on). - A tree's `predict_proba` columns follow that tree's own `classes_`. Align them to the forest's `classes_` before averaging, with 0 for any class the tree never saw. Example calls: ```python resolve_max_features("sqrt", 10) # 3 resolve_max_features(0.01, 9) # 1 majority_vote(np.array([[1, 0], [0, 1]]), np.array([0, 1])) # array([0, 0]) ``` ```hint Missing classes A bootstrap sample of a small or imbalanced dataset can leave out a class entirely. Look at a fitted tree's `classes_` before you add its probabilities to the forest's total. ``` ```hint Ties without extra code If you count votes into an array whose rows follow the sorted `classes`, check which index `np.argmax` returns when two counts are equal. ``` ```hint One generator, many trees Think about what happens to the first tree's rows when `n_estimators` goes from 10 to 20, for each way you could seed the sampling. ``` ### Constraints & Assumptions - `X` is a numeric array of shape `(n_samples, n_features)` and `y` holds one label per row. Labels only need to be sortable, so strings work. - NumPy and scikit-learn are available. Sampling, column alignment and voting are written by hand; scikit-learn's own forest and bagging classes are off limits. - `random_state` is an int. - A bool `max_features` counts as unknown and raises `ValueError`, even though Python treats `True` as an int. ### What a Strong Answer Covers - Handling of every `max_features` input type, booleans included, and the clip to the range 1 to `d`. - A seeding scheme that makes fits reproducible, and its effect on existing trees when more trees are added. - Precedence between `sample_indices` and `bootstrap`, and what `estimator_samples_` records in each case. - Alignment of each tree's probability columns to the forest's `classes_`, including the case where skipping it fails without an error. - A vectorized vote count with the required tie rule, and the cost of `fit` and `predict`. ### Follow-up Questions - How would you compute an out-of-bag accuracy estimate from this forest? - Why can `predict` and `predict_proba(X).argmax(axis=1)` disagree, and when do they agree? - How would you report feature importances for the forest, and what bias should you watch for?

Overview: Implement a random forest classifier on top of scikit-learn decision trees, with helpers that resolve max_features, draw bootstrap samples and take a majority vote. It tests bagging, reproducible seeding, probability column alignment when a bootstrap misses a class, and vectorized tie-breaking.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement a random forest classifier in Python that uses scikit-learn's DecisionTreeClassifier as its base tree, along with three helper functions. fit trains each tree on its own sample of rows, predict_proba averages the trees' class probabilities, and predict takes a hard majority vote over the trees' predicted labels.

The helpers:

  • resolve_max_features(max_features, n_features) returns how many features each split considers, with d = n_features . "sqrt" and "log2" give the floor of d\sqrt{d} and log⁡2d\log_2 d , None gives d , an int is used as given, and a float f gives int(f * d) . Clip the result to the range 1 to d . Any other value raises ValueError .
  • bootstrap_indices(n, rng) returns rng.integers(0, n, size=n) , where rng is a NumPy Generator .
  • majority_vote(preds, classes) takes tree predictions of shape (n_trees, n_samples) and the sorted array of class labels, and returns the most voted label for each sample. Ties go to the lowest label.

The class is RandomForestClassifier(n_estimators=10, max_features="sqrt", max_depth=None, bootstrap=True, random_state=0), with these rules:

  • fit(X, y, sample_indices=None) creates one np.random.default_rng(random_state) and draws the trees' bootstrap samples from it in order, one tree after another. Tree i is a DecisionTreeClassifier with max_features=max_features_ , the forest's max_depth , and random_state=random_state + i .
  • When sample_indices (a list of index arrays) is passed, it replaces sampling: tree i trains on rows sample_indices[i] , and the number of trees is len(sample_indices) . With bootstrap=False and no sample_indices , every tree trains on np.arange(n) .
  • After fit , the forest exposes classes_ (sorted unique labels), max_features_ , estimators_ (the fitted trees) and estimator_samples_ (the row indices each tree trained on).
  • A tree's predict_proba columns follow that tree's own classes_ . Align them to the forest's classes_ before averaging, with 0 for any class the tree never saw.

Example calls:

resolve_max_features("sqrt", 10)  # 3
resolve_max_features(0.01, 9)     # 1
majority_vote(np.array([[1, 0], [0, 1]]), np.array([0, 1]))  # array([0, 0])

Constraints & Assumptions

  • X is a numeric array of shape (n_samples, n_features) and y holds one label per row. Labels only need to be sortable, so strings work.
  • NumPy and scikit-learn are available. Sampling, column alignment and voting are written by hand; scikit-learn's own forest and bagging classes are off limits.
  • random_state is an int.
  • A bool max_features counts as unknown and raises ValueError , even though Python treats True as an int.

What a Strong Answer Covers Guidance

  • Handling of every max_features input type, booleans included, and the clip to the range 1 to d .
  • A seeding scheme that makes fits reproducible, and its effect on existing trees when more trees are added.
  • Precedence between sample_indices and bootstrap , and what estimator_samples_ records in each case.
  • Alignment of each tree's probability columns to the forest's classes_ , including the case where skipping it fails without an error.
  • A vectorized vote count with the required tie rule, and the cost of fit and predict .

Follow-up Questions Guidance

  • How would you compute an out-of-bag accuracy estimate from this forest?
  • Why can predict and predict_proba(X).argmax(axis=1) disagree, and when do they agree?
  • How would you report feature importances for the forest, and what bias should you watch for?