Implement a Bootstrap Bias-Variance Decomposition of Regression Test Error

Quick Overview

Implement a bootstrap bias-variance decomposition for a scikit-learn regressor by refitting clones on resampled training data and splitting the test squared error into bias, variance, noise and a residual term. It tests reproducible seeding, careful NumPy axis handling, and where the cross term in the decomposition comes from.

Implement a Bootstrap Bias-Variance Decomposition of Regression Test Error

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `bias_variance_decomposition`, which refits clones of `estimator` on `n_rounds` bootstrap resamples of `(X_train, y_train)`, predicts `X_test`, and decomposes the test error using the true function values `f_test` and the noisy targets `y_test`. Return a dict. ```python def bias_variance_decomposition(estimator, X_train, y_train, X_test, y_test, f_test, n_rounds=50, seed=0): ... ``` The function must follow these rules: - Create `rng = np.random.default_rng(seed)` once. Each round draws `idx = rng.integers(0, n, size=n)` and fits `clone(estimator)` on the resampled rows. - `"predictions"` is an array of shape `(n_rounds, m)` holding each round's test predictions. - Let `main` be the per-point mean prediction. Then `bias_sq = mean((main - f_test)²)`, `variance` is the mean of the per-point variance (`ddof=0`), `noise = mean((y_test - f_test)²)`, and `mse` is the mean of `(pred - y_test)²` over all rounds and points. - `"residual" = mse - (bias_sq + variance + noise)`. All five scalars are Python `float`s. - `n_rounds < 1` or mismatched lengths raise `ValueError`. A 1-D `X` is treated as a single feature column. For example, with a single round the variance is zero: ```python out = bias_variance_decomposition(LinearRegression(), X_tr, y_tr, X_te, y_te, f_te, n_rounds=1) out["predictions"].shape # (1, len(X_te)) out["variance"] # 0.0 set(out) == {"mse", "bias_sq", "variance", "noise", "residual", "predictions"} ``` ```hint Reproducible draws The expected numbers depend on the exact sequence of random draws. Decide where the generator is created and make sure nothing else consumes it between rounds. ``` ```hint Sanity check for the residual Write `pred - y` as `(pred - main) + (main - f) + (f - y)`, square it, and average over rounds before averaging over points. Look at which cross terms cancel. ``` ### Constraints & Assumptions - `estimator` follows the scikit-learn API (`fit`, `predict`) and can be copied with `sklearn.base.clone`. - `X_train` has shape `(n, d)`, or is 1-D with length `n`. `y_train` has length `n`. - `X_test` has shape `(m, d)`, or is 1-D with length `m`. `y_test` and `f_test` both have length `m`. - `n_rounds` defaults to 50 and `seed` defaults to 0. ### What a Strong Answer Covers - One seeded generator created before the loop and a fresh `clone` per round, so the result is reproducible and no fitted state carries over between rounds. - The right axes: mean and variance over rounds (`axis=0`, `ddof=0`) for each test point, then averages over test points. - Input handling that matches the spec: 1-D inputs reshaped to one column, length checks, and `ValueError` for `n_rounds < 1`. - An algebraic account of the residual and why it is not zero on a finite noisy test set. - The cost in model fits and the memory for the prediction matrix. ### Follow-up Questions - Why is `residual` non-zero, and when is it exactly zero? - How do bootstrap resamples bias the variance estimate compared with truly independent training sets? - How would you extend this to classifiers under 0-1 loss?

Overview: Implement a bootstrap bias-variance decomposition for a scikit-learn regressor by refitting clones on resampled training data and splitting the test squared error into bias, variance, noise and a residual term. It tests reproducible seeding, careful NumPy axis handling, and where the cross term in the decomposition comes from.

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

Implement bias_variance_decomposition, which refits clones of estimator on n_rounds bootstrap resamples of (X_train, y_train), predicts X_test, and decomposes the test error using the true function values f_test and the noisy targets y_test. Return a dict.

def bias_variance_decomposition(estimator, X_train, y_train, X_test, y_test, f_test, n_rounds=50, seed=0):
    ...

The function must follow these rules:

  • Create rng = np.random.default_rng(seed) once. Each round draws idx = rng.integers(0, n, size=n) and fits clone(estimator) on the resampled rows.
  • "predictions" is an array of shape (n_rounds, m) holding each round's test predictions.
  • Let main be the per-point mean prediction. Then bias_sq = mean((main - f_test)²) , variance is the mean of the per-point variance ( ddof=0 ), noise = mean((y_test - f_test)²) , and mse is the mean of (pred - y_test)² over all rounds and points.
  • "residual" = mse - (bias_sq + variance + noise) . All five scalars are Python float s.
  • n_rounds < 1 or mismatched lengths raise ValueError . A 1-D X is treated as a single feature column.

For example, with a single round the variance is zero:

out = bias_variance_decomposition(LinearRegression(), X_tr, y_tr, X_te, y_te, f_te, n_rounds=1)
out["predictions"].shape  # (1, len(X_te))
out["variance"]           # 0.0
set(out) == {"mse", "bias_sq", "variance", "noise", "residual", "predictions"}

Constraints & Assumptions

  • estimator follows the scikit-learn API ( fit , predict ) and can be copied with sklearn.base.clone .
  • X_train has shape (n, d) , or is 1-D with length n . y_train has length n .
  • X_test has shape (m, d) , or is 1-D with length m . y_test and f_test both have length m .
  • n_rounds defaults to 50 and seed defaults to 0.

What a Strong Answer Covers Guidance

  • One seeded generator created before the loop and a fresh clone per round, so the result is reproducible and no fitted state carries over between rounds.
  • The right axes: mean and variance over rounds ( axis=0 , ddof=0 ) for each test point, then averages over test points.
  • Input handling that matches the spec: 1-D inputs reshaped to one column, length checks, and ValueError for n_rounds < 1 .
  • An algebraic account of the residual and why it is not zero on a finite noisy test set.
  • The cost in model fits and the memory for the prediction matrix.

Follow-up Questions Guidance

  • Why is residual non-zero, and when is it exactly zero?
  • How do bootstrap resamples bias the variance estimate compared with truly independent training sets?
  • How would you extend this to classifiers under 0-1 loss?