Simulate Bias and Variance of Polynomial Fits Versus Training Set Size

Quick Overview

Implement an empirical bias-variance decomposition for a matrix of model predictions, then refit polynomial models of several degrees on fresh noisy training sets of growing size. It tests careful NumPy work with seeded random draws and least squares, and whether you can explain how squared bias and variance change as training data grows.

Simulate Bias and Variance of Polynomial Fits Versus Training Set Size

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `decompose(predictions, f_test)`, which takes an `(n_refits, n_test)` prediction matrix and returns `(bias_sq, variance)` as floats. Then implement `bias_variance_vs_sample_size`, which refits polynomial models on fresh training sets of each size and decomposes their test predictions. ```python def decompose(predictions, f_test) -> tuple[float, float]: ... def bias_variance_vs_sample_size(true_fn, x_test, sizes, degrees, n_refits, noise_std, seed) -> dict: ... ``` Requirements: - `bias_sq` = mean over test points of `(mean_pred - f_test)**2`. `variance` = mean over test points of the per-point variance across refits (`ddof=0`). - `decompose` raises `ValueError` if `predictions` is not 2-D or its column count differs from `len(f_test)`. - Use one `rng = np.random.default_rng(seed)`. For each size `n` (in order), for each refit: draw `x = rng.uniform(-1, 1, n)`, then `rng.normal(0, noise_std, n)` noise, and set `y = true_fn(x) + noise`. - Fit every degree on the same `(x, y)` by least squares on `np.vander(x, d + 1, increasing=True)` (`np.linalg.lstsq`, `rcond=None`), then predict at `x_test` and decompose against `true_fn(x_test)`. - Return a dict with `"sizes"` and `"degrees"` (int arrays) plus `"bias_sq"` and `"variance"` of shape `(len(degrees), len(sizes))`. Example: ```python decompose(np.array([[1.0, 2.0], [3.0, 4.0]]), np.array([1.0, 1.0])) # mean_pred = [2, 3] -> bias_sq = (1 + 4) / 2 = 2.5 # per-point var = [1, 1] -> variance = 1.0 # returns (2.5, 1.0) ``` ```hint Axes Each row of `predictions` is one refit and each column is one test point. Work out which axis each average runs over before you write either line. ``` ```hint Random stream The seeded generator reproduces a reference run only if the draws happen in the stated order. Decide where the degree loop goes so that it never touches `rng`. ``` ### Constraints & Assumptions - `predictions` has one row per refit and one column per test point. `f_test` is a 1-D array of length `n_test`. - `true_fn` is vectorized: it maps a NumPy array of inputs to an array of the same length. - `sizes` and `degrees` are sequences of non-negative integers, and the output arrays are indexed `[degree_index, size_index]`. ### What a Strong Answer Covers - Both terms computed across refits for each test point and then averaged over test points, with population variance and the `ValueError` shape check. - The prescribed draw order (sizes, then refits, `x` before noise) with one training set shared by every degree. - A least squares fit on the increasing Vandermonde design, evaluated on the same basis at `x_test` and compared with `true_fn(x_test)`. - A result dict with integer `sizes` and `degrees` arrays and `(len(degrees), len(sizes))` metric arrays. - An explanation of how squared bias and variance should move as the training set grows and as the degree rises, and why the two add up to the mean squared error against the truth. ### Follow-up Questions - How would you include the noise term so the decomposition matches the expected error against noisy test labels? - What happens when a training size is smaller than `degree + 1`, and how would it show in the variance curve? - Why fit every degree on the same training set, and what does that choice do to the comparison between degrees? - How would you use these curves to decide between collecting more data and changing model capacity?

Overview: Implement an empirical bias-variance decomposition for a matrix of model predictions, then refit polynomial models of several degrees on fresh noisy training sets of growing size. It tests careful NumPy work with seeded random draws and least squares, and whether you can explain how squared bias and variance change as training data grows.

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

Implement decompose(predictions, f_test), which takes an (n_refits, n_test) prediction matrix and returns (bias_sq, variance) as floats. Then implement bias_variance_vs_sample_size, which refits polynomial models on fresh training sets of each size and decomposes their test predictions.

def decompose(predictions, f_test) -> tuple[float, float]:
    ...


def bias_variance_vs_sample_size(true_fn, x_test, sizes, degrees, n_refits, noise_std, seed) -> dict:
    ...

Requirements:

  • bias_sq = mean over test points of (mean_pred - f_test)**2 . variance = mean over test points of the per-point variance across refits ( ddof=0 ).
  • decompose raises ValueError if predictions is not 2-D or its column count differs from len(f_test) .
  • Use one rng = np.random.default_rng(seed) . For each size n (in order), for each refit: draw x = rng.uniform(-1, 1, n) , then rng.normal(0, noise_std, n) noise, and set y = true_fn(x) + noise .
  • Fit every degree on the same (x, y) by least squares on np.vander(x, d + 1, increasing=True) ( np.linalg.lstsq , rcond=None ), then predict at x_test and decompose against true_fn(x_test) .
  • Return a dict with "sizes" and "degrees" (int arrays) plus "bias_sq" and "variance" of shape (len(degrees), len(sizes)) .

Example:

decompose(np.array([[1.0, 2.0], [3.0, 4.0]]), np.array([1.0, 1.0]))
# mean_pred = [2, 3] -> bias_sq = (1 + 4) / 2 = 2.5
# per-point var = [1, 1] -> variance = 1.0
# returns (2.5, 1.0)

Constraints & Assumptions

  • predictions has one row per refit and one column per test point. f_test is a 1-D array of length n_test .
  • true_fn is vectorized: it maps a NumPy array of inputs to an array of the same length.
  • sizes and degrees are sequences of non-negative integers, and the output arrays are indexed [degree_index, size_index] .

What a Strong Answer Covers Guidance

  • Both terms computed across refits for each test point and then averaged over test points, with population variance and the ValueError shape check.
  • The prescribed draw order (sizes, then refits, x before noise) with one training set shared by every degree.
  • A least squares fit on the increasing Vandermonde design, evaluated on the same basis at x_test and compared with true_fn(x_test) .
  • A result dict with integer sizes and degrees arrays and (len(degrees), len(sizes)) metric arrays.
  • An explanation of how squared bias and variance should move as the training set grows and as the degree rises, and why the two add up to the mean squared error against the truth.

Follow-up Questions Guidance

  • How would you include the noise term so the decomposition matches the expected error against noisy test labels?
  • What happens when a training size is smaller than degree + 1 , and how would it show in the variance curve?
  • Why fit every degree on the same training set, and what does that choice do to the comparison between degrees?
  • How would you use these curves to decide between collecting more data and changing model capacity?