Effective Degrees of Freedom and Cp Optimism for KNN and Polynomial Smoothers

Quick Overview

Build hat matrices for a KNN smoother and a polynomial fit on 1-D data, compute effective degrees of freedom from the trace, and trace train error, test error and Mallows' Cp across model capacities. It tests linear smoothers, tie-breaking details and why training error understates test error.

Effective Degrees of Freedom and Cp Optimism for KNN and Polynomial Smoothers

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `knn_hat_matrix(x, k)`, `polynomial_hat_matrix(x, degree)`, `effective_df(S)` and `optimism_curve(x, y_train, y_test, sigma2, method, capacities)` for 1-D inputs. For each capacity, fit `fitted = S @ y_train` and report the effective degrees of freedom, the train MSE, the test MSE (with `y_test` observed at the same `x`) and the Mallows' Cp estimate. Example: ```python optimism_curve(x=[0, 1, 2, 3], y_train=[1, 2, 3, 6], y_test=[2, 2, 4, 4], sigma2=0.5, method="poly", capacities=[0]) # capacity=[0.], df=[1.], train_error=[3.5], test_error=[1.0], cp_estimate=[3.75] knn_hat_matrix([0, 1, 2], 2) # [[.5, .5, 0], [.5, .5, 0], [0, .5, .5]] # row 1 tie: index 0 wins over 2 ``` A degree-0 polynomial fits the mean 3 everywhere, so the train MSE is (4 + 1 + 0 + 9) / 4 = 3.5, the test MSE is 1, and Cp adds 2 · 1 · 0.5 / 4 = 0.25. In the KNN example, row 1 has two candidates at distance 1, and the lower index wins. ```hint Tie-breaking Look for a sort that keeps equal distances in their original index order. ``` ```hint Where the optimism comes from The train and test targets share the same `x`. Ask how strongly each fitted value moves with its own training target, and which entries of `S` measure that. ``` ### Constraints & Assumptions - KNN: `S[i, j] = 1/k` for the `k` nearest points by `|x - x[i]|`, the point itself included, with ties going to the lower index. `k` outside `[1, n]` raises `ValueError`. - Polynomial: `S = X @ pinv(X)` with the design `[1, x, ..., x^degree]`. `degree < 0` raises `ValueError`. - `effective_df` returns `float(trace(S))` for any square matrix. - `cp_estimate = train_error + 2 * df * sigma2 / n`. A `method` outside `{"knn", "poly"}` raises `ValueError`. - Return a dict with keys `capacity`, `df`, `train_error`, `cp_estimate` and `test_error`, each a float ndarray aligned with `capacities`. ### What a Strong Answer Covers - Both hat matrices built so that `fitted = S @ y_train`, with the KNN self-inclusion and lower-index tie rule implemented exactly. - Effective degrees of freedom as `trace(S)`, and what that trace equals for KNN and for the polynomial projection. - Why `2 * df * sigma2 / n` is the expected gap between test and train error for a linear smoother when the test targets sit at the same `x`. - Validation of `k`, `degree` and `method`, and the cost per capacity. ### Follow-up Questions - Why does the KNN df equal `n/k`, and when would it not? - How would you estimate `sigma2` when it is unknown? - Why is the raw-power Vandermonde design risky at high degree?

Overview: Build hat matrices for a KNN smoother and a polynomial fit on 1-D data, compute effective degrees of freedom from the trace, and trace train error, test error and Mallows' Cp across model capacities. It tests linear smoothers, tie-breaking details and why training error understates test error.

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

Implement knn_hat_matrix(x, k), polynomial_hat_matrix(x, degree), effective_df(S) and optimism_curve(x, y_train, y_test, sigma2, method, capacities) for 1-D inputs. For each capacity, fit fitted = S @ y_train and report the effective degrees of freedom, the train MSE, the test MSE (with y_test observed at the same x) and the Mallows' Cp estimate.

Example:

optimism_curve(x=[0, 1, 2, 3], y_train=[1, 2, 3, 6], y_test=[2, 2, 4, 4],
               sigma2=0.5, method="poly", capacities=[0])
# capacity=[0.], df=[1.], train_error=[3.5], test_error=[1.0], cp_estimate=[3.75]

knn_hat_matrix([0, 1, 2], 2)
# [[.5, .5, 0], [.5, .5, 0], [0, .5, .5]]   # row 1 tie: index 0 wins over 2

A degree-0 polynomial fits the mean 3 everywhere, so the train MSE is (4 + 1 + 0 + 9) / 4 = 3.5, the test MSE is 1, and Cp adds 2 · 1 · 0.5 / 4 = 0.25. In the KNN example, row 1 has two candidates at distance 1, and the lower index wins.

Constraints & Assumptions

  • KNN: S[i, j] = 1/k for the k nearest points by |x - x[i]| , the point itself included, with ties going to the lower index. k outside [1, n] raises ValueError .
  • Polynomial: S = X @ pinv(X) with the design [1, x, ..., x^degree] . degree < 0 raises ValueError .
  • effective_df returns float(trace(S)) for any square matrix.
  • cp_estimate = train_error + 2 * df * sigma2 / n . A method outside {"knn", "poly"} raises ValueError .
  • Return a dict with keys capacity , df , train_error , cp_estimate and test_error , each a float ndarray aligned with capacities .

What a Strong Answer Covers Guidance

  • Both hat matrices built so that fitted = S @ y_train , with the KNN self-inclusion and lower-index tie rule implemented exactly.
  • Effective degrees of freedom as trace(S) , and what that trace equals for KNN and for the polynomial projection.
  • Why 2 * df * sigma2 / n is the expected gap between test and train error for a linear smoother when the test targets sit at the same x .
  • Validation of k , degree and method , and the cost per capacity.

Follow-up Questions Guidance

  • Why does the KNN df equal n/k , and when would it not?
  • How would you estimate sigma2 when it is unknown?
  • Why is the raw-power Vandermonde design risky at high degree?