KNN Bias-Variance Decomposition Across k

Quick Overview

Implement k-nearest-neighbors regression over repeated training draws and split its expected error into squared bias, variance and noise for every k. It tests NumPy vectorization, stable tie-breaking, seeded simulation and how neighborhood size trades bias for variance.

KNN Bias-Variance Decomposition Across k

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `knn_bias_variance(X_train, Y_train, X_test, f_test, noise_var, k_values=None)` for `R` refits of a training set. `X_train` has shape `(R, n)` or `(R, n, d)` and `Y_train` has shape `(R, n)`. The test points `X_test` have shape `(m,)` or `(m, d)`, with true function values `f_test`. For each k, decompose the expected error of k-nearest-neighbors regression into bias², variance and noise. Also implement `simulate_knn_tradeoff(seed, n_refits, n_train, x_test, noise_sd)`. Requirements: - A prediction is the mean `Y` of the k nearest training points by Euclidean distance. Distance ties go to the lower training index. - `bias_sq` is the mean over test points of (refit-mean prediction minus `f_test`)². `variance` is the variance of the prediction across refits (`ddof=0`), averaged over test points. - Return a dict with `k` (int array), `bias_sq`, `variance`, `expected_error` (all aligned with `k`), `noise` (the float `noise_var`) and `best_k` (the int k that minimizes `expected_error`; ties go to the earliest k). - `k_values` defaults to `1..n`. Any k outside `[1, n]` raises `ValueError`. - The simulation creates `rng = np.random.default_rng(seed)`. For each refit it draws `x = rng.uniform(0, 1, n_train)`, then `eps = rng.normal(0, noise_sd, n_train)`, and sets `y = sin(2πx) + eps`. It then calls `knn_bias_variance` with `f_test = sin(2π·x_test)`, `noise_var = noise_sd**2` and the default `k_values`. Example: ```python X = [[0, 1, 2], [0, 1, 2]]; Y = [[1, 2, 3], [3, 2, 1]] knn_bias_variance(X, Y, [0.1, 1.9], [1.0, 3.0], 0.5) # k=[1,2,3], bias_sq=[1,1,1], variance=[1,0.25,0] # expected_error=[2.5,1.75,1.5], noise=0.5, best_k=3 ``` ```hint Reuse one sort for every k Once a test point's training labels are sorted by distance, look for a way to read off the k-NN mean for every k in a single pass. ``` ```hint Tie order Check whether the sort you call keeps equal distances in their original index order. ``` ### Constraints & Assumptions - `X_train` is `(R, n)` for one-dimensional inputs or `(R, n, d)`; `Y_train` is `(R, n)`. Every refit has the same n. - `X_test` is `(m,)` or `(m, d)` with the same feature dimension as the training inputs; `f_test` is `(m,)`. - `noise_var` is the known variance of the label noise and enters the decomposition as a constant. - Inputs may arrive as nested Python lists, as in the example. ### What a Strong Answer Covers - k-NN predictions for every refit, test point and k, with distance ties broken toward the lower training index. - The decomposition across refits: squared bias from the refit-mean prediction, variance with `ddof=0`, and noise added as a constant. - Validation of `k_values`, and `best_k` reported as a k value with the earliest-k tie rule. - A way to get all k from one sort per refit, with the time and memory cost stated. - A seeded simulation that draws `x` and then `eps` for each refit in the stated order, so results reproduce. ### Follow-up Questions - Why does variance fall and bias rise as k grows toward n? - How does the finite number of refits R affect your estimates? - How would you vectorize this for large n and m?

Overview: Implement k-nearest-neighbors regression over repeated training draws and split its expected error into squared bias, variance and noise for every k. It tests NumPy vectorization, stable tie-breaking, seeded simulation and how neighborhood size trades bias for variance.

Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement knn_bias_variance(X_train, Y_train, X_test, f_test, noise_var, k_values=None) for R refits of a training set. X_train has shape (R, n) or (R, n, d) and Y_train has shape (R, n). The test points X_test have shape (m,) or (m, d), with true function values f_test. For each k, decompose the expected error of k-nearest-neighbors regression into bias², variance and noise. Also implement simulate_knn_tradeoff(seed, n_refits, n_train, x_test, noise_sd).

Requirements:

  • A prediction is the mean Y of the k nearest training points by Euclidean distance. Distance ties go to the lower training index.
  • bias_sq is the mean over test points of (refit-mean prediction minus f_test )². variance is the variance of the prediction across refits ( ddof=0 ), averaged over test points.
  • Return a dict with k (int array), bias_sq , variance , expected_error (all aligned with k ), noise (the float noise_var ) and best_k (the int k that minimizes expected_error ; ties go to the earliest k).
  • k_values defaults to 1..n . Any k outside [1, n] raises ValueError .
  • The simulation creates rng = np.random.default_rng(seed) . For each refit it draws x = rng.uniform(0, 1, n_train) , then eps = rng.normal(0, noise_sd, n_train) , and sets y = sin(2πx) + eps . It then calls knn_bias_variance with f_test = sin(2π·x_test) , noise_var = noise_sd**2 and the default k_values .

Example:

X = [[0, 1, 2], [0, 1, 2]]; Y = [[1, 2, 3], [3, 2, 1]]
knn_bias_variance(X, Y, [0.1, 1.9], [1.0, 3.0], 0.5)
# k=[1,2,3], bias_sq=[1,1,1], variance=[1,0.25,0]
# expected_error=[2.5,1.75,1.5], noise=0.5, best_k=3

Constraints & Assumptions

  • X_train is (R, n) for one-dimensional inputs or (R, n, d) ; Y_train is (R, n) . Every refit has the same n.
  • X_test is (m,) or (m, d) with the same feature dimension as the training inputs; f_test is (m,) .
  • noise_var is the known variance of the label noise and enters the decomposition as a constant.
  • Inputs may arrive as nested Python lists, as in the example.

What a Strong Answer Covers Guidance

  • k-NN predictions for every refit, test point and k, with distance ties broken toward the lower training index.
  • The decomposition across refits: squared bias from the refit-mean prediction, variance with ddof=0 , and noise added as a constant.
  • Validation of k_values , and best_k reported as a k value with the earliest-k tie rule.
  • A way to get all k from one sort per refit, with the time and memory cost stated.
  • A seeded simulation that draws x and then eps for each refit in the stated order, so results reproduce.

Follow-up Questions Guidance

  • Why does variance fall and bias rise as k grows toward n?
  • How does the finite number of refits R affect your estimates?
  • How would you vectorize this for large n and m?