Stochastic Gradient Boosting with Row and Column Subsampling

Quick Overview

Implement squared-loss gradient boosting in Python where each tree is fit on a random subset of rows and columns, with reproducible draws and optional per-round overrides. It tests residual fitting, per-tree feature masks, full-data prediction updates and staged prediction.

Stochastic Gradient Boosting with Row and Column Subsampling

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `fit`, `predict` and `staged_predict` for a `StochasticGradientBoostingRegressor` that uses squared loss. Start from the constant prediction `init_ = mean(y)`. In each round, fit a `DecisionTreeRegressor(max_depth=self.max_depth, random_state=0)` to the residuals of a random subset of rows, using only a random subset of columns. Then update the predictions for every training row by `learning_rate * tree.predict(X[:, cols])`. The constructor takes `n_estimators=100`, `learning_rate=0.1`, `max_depth=3`, `subsample=1.0`, `colsample=1.0` and `random_state=0`. The class must meet these requirements: - Create one generator, `rng = np.random.default_rng(random_state)`, and use it for every draw. In each round, draw the rows first with `np.sort(rng.choice(n, max(1, int(subsample * n)), replace=False))`, then draw the columns the same way using `p` and `colsample`. - `fit(X, y, row_indices=None, feature_masks=None)` accepts optional overrides. `row_indices[m]` is the row set for round `m` and `feature_masks[m]` is the boolean column mask for round `m`. A supplied value replaces the corresponding draw, and that draw is skipped, so the generator does not advance for it. Raise `ValueError` if `row_indices` does not have exactly `n_estimators` entries, or if `feature_masks` does not have shape `(n_estimators, n_features)`. - Store `estimators_` (the fitted trees), `row_indices_` (a list holding the rows used in each round), `feature_masks_` (a boolean array of shape `(n_estimators, p)`) and `train_loss_` (the mean squared error on the full training set after each round). `fit` returns `self`. - `predict(X)` applies tree `m` to `X[:, feature_masks_[m]]`. `staged_predict(X)` is a generator that yields a copy of the prediction after each round. For example: ```python X = [[0], [1], [2], [3]]; y = [0, 0, 4, 10] m = StochasticGradientBoostingRegressor(n_estimators=1, learning_rate=0.5, max_depth=1) m.fit(X, y, row_indices=[[0, 2, 3]], feature_masks=[[True]]) m.init_ # 3.5 m.predict(X) # [2.75, 2.75, 2.75, 6.75] ``` ```hint Keep the random stream in order Every draw that is not overridden consumes the generator in a fixed order: rows, then columns, round after round. Check each override separately so a supplied value never touches `rng`. ``` ```hint Remember the columns per tree A tree fitted on k columns expects exactly k features when it predicts. Think about what has to be saved during `fit` so `predict` can slice new inputs the same way. ``` ### Constraints & Assumptions - `X` is numeric with shape `(n, p)` and `y` has length `n`. Inputs may arrive as Python lists. - `0 < subsample <= 1` and `0 < colsample <= 1`. Each draw has at least one row and one column. - Rows and columns are drawn without replacement and kept in ascending order. - Only NumPy and scikit-learn's `DecisionTreeRegressor` are needed. ### Clarifying Questions to Ask - If a supplied feature mask row has no `True` entries, should `fit` raise an error or skip that round? - Should supplied `row_indices` be checked for duplicates and out-of-range values, or trusted as given? - When only one of the two overrides is supplied, does the other still draw from the same generator in the usual order? ### What a Strong Answer Covers - Mean initialization and fitting each tree to the residuals as the negative gradient of squared loss - Draws from a single generator in the specified order, with each override skipping its own draw - Updating the predictions for all rows each round and recording the full-data training loss - Saving a column mask per tree and applying it in both `predict` and `staged_predict` - Validation of the override shapes, edge cases such as tiny sample sizes, and the training and prediction cost ### Follow-up Questions - Why does row subsampling often improve test error, and how could the rows left out of a round be used to estimate that round's improvement? - How would the leaf values change to support log loss for binary classification? - How does sampling columns once per tree differ from sampling them at every split, and when would you choose each? - How would you add early stopping using `staged_predict` on a validation set?

Overview: Implement squared-loss gradient boosting in Python where each tree is fit on a random subset of rows and columns, with reproducible draws and optional per-round overrides. It tests residual fitting, per-tree feature masks, full-data prediction updates and staged prediction.

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

Implement fit, predict and staged_predict for a StochasticGradientBoostingRegressor that uses squared loss. Start from the constant prediction init_ = mean(y). In each round, fit a DecisionTreeRegressor(max_depth=self.max_depth, random_state=0) to the residuals of a random subset of rows, using only a random subset of columns. Then update the predictions for every training row by learning_rate * tree.predict(X[:, cols]).

The constructor takes n_estimators=100, learning_rate=0.1, max_depth=3, subsample=1.0, colsample=1.0 and random_state=0. The class must meet these requirements:

  • Create one generator, rng = np.random.default_rng(random_state) , and use it for every draw. In each round, draw the rows first with np.sort(rng.choice(n, max(1, int(subsample * n)), replace=False)) , then draw the columns the same way using p and colsample .
  • fit(X, y, row_indices=None, feature_masks=None) accepts optional overrides. row_indices[m] is the row set for round m and feature_masks[m] is the boolean column mask for round m . A supplied value replaces the corresponding draw, and that draw is skipped, so the generator does not advance for it. Raise ValueError if row_indices does not have exactly n_estimators entries, or if feature_masks does not have shape (n_estimators, n_features) .
  • Store estimators_ (the fitted trees), row_indices_ (a list holding the rows used in each round), feature_masks_ (a boolean array of shape (n_estimators, p) ) and train_loss_ (the mean squared error on the full training set after each round). fit returns self .
  • predict(X) applies tree m to X[:, feature_masks_[m]] . staged_predict(X) is a generator that yields a copy of the prediction after each round.

For example:

X = [[0], [1], [2], [3]]; y = [0, 0, 4, 10]
m = StochasticGradientBoostingRegressor(n_estimators=1, learning_rate=0.5, max_depth=1)
m.fit(X, y, row_indices=[[0, 2, 3]], feature_masks=[[True]])
m.init_       # 3.5
m.predict(X)  # [2.75, 2.75, 2.75, 6.75]

Constraints & Assumptions

  • X is numeric with shape (n, p) and y has length n . Inputs may arrive as Python lists.
  • 0 < subsample <= 1 and 0 < colsample <= 1 . Each draw has at least one row and one column.
  • Rows and columns are drawn without replacement and kept in ascending order.
  • Only NumPy and scikit-learn's DecisionTreeRegressor are needed.

Clarifying Questions to Ask Guidance

  • If a supplied feature mask row has no True entries, should fit raise an error or skip that round?
  • Should supplied row_indices be checked for duplicates and out-of-range values, or trusted as given?
  • When only one of the two overrides is supplied, does the other still draw from the same generator in the usual order?

What a Strong Answer Covers Guidance

  • Mean initialization and fitting each tree to the residuals as the negative gradient of squared loss
  • Draws from a single generator in the specified order, with each override skipping its own draw
  • Updating the predictions for all rows each round and recording the full-data training loss
  • Saving a column mask per tree and applying it in both predict and staged_predict
  • Validation of the override shapes, edge cases such as tiny sample sizes, and the training and prediction cost

Follow-up Questions Guidance

  • Why does row subsampling often improve test error, and how could the rows left out of a round be used to estimate that round's improvement?
  • How would the leaf values change to support log loss for binary classification?
  • How does sampling columns once per tree differ from sampling them at every split, and when would you choose each?
  • How would you add early stopping using staged_predict on a validation set?