Foundations to Frontier
Tests
D. Classical Machine Learning › D4 Instance-Based Methods

k-Nearest Neighbors Regression

k-NN regression predicts a numeric target as the average of the targets of the k most similar training examples, optionally weighting closer ones more. It assumes only that nearby inputs have similar outputs, so it can fit any smooth relationship given enough data, but it cannot extrapolate beyond the data and suffers in high dimensions. This page covers the estimator, distance weighting, the bias–variance trade-off controlled by k (variance σ²/k, bias growing with the neighbourhood size), leave-one-out selection of k, convergence rates, and its relation to kernel smoothers. In the exercises you implement k-NN regression with leave-one-out tuning and measure its bias and variance; then you estimate a battery's state of charge from voltage and temperature and compare k-NN with physics-shaped parametric models inside and outside the training conditions.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Estimate by averaging similar cases

To estimate how full a battery is from its voltage and temperature, look up the logged cases with the most similar voltage and temperature and average their known charge levels. That is k-NN regression. It makes no assumption about the shape of the relationship, which is its strength. Its blind spot is conditions it has never seen: it can only repeat what nearby examples said.

k-NN regression: average your neighbours' answers
mean squared error against the true curve (inside the data range): 0.0173
Dashed: the truth; orange: the k-NN prediction. Shaded edges are outside the training range: there the prediction is frozen at the average of the edge points, while the true curve keeps changing. Small k chases noise; large k smooths away the waves; distance weighting makes the curve pass close to each point.
Why engineers care

Lookup-and-average is how many engineering tables work: performance maps, calibration tables, look-up-based estimators. k-NN regression formalises it, adapts automatically as logged data grow, and shows exactly when a data-driven estimator must not be trusted: outside the envelope of the data.

📝 Quick check (Level 0)
0/3 answered
  1. 1. k-NN regression predicts…
  2. 2. Beyond the training range, k-NN regression…
  3. 3. In the demo, small k gives a curve that is…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

The training data are x = 0, 1, 2, 3, 10 with y = 0, 1, 4, 9, 100.

  • Query 1.4, k = 2: the nearest points are x = 1 and x = 2, so the prediction is (1 + 4)/2 = 2.5.
  • Query 1.25, distance-weighted, k = 2: the distances are 0.25 and 0.75, so the weights 1/d are 4 and 1.33. The prediction is (4·1 + 1.33·4)/5.33 = 1.75, closer to the nearer point’s value.
  • Query 20, k = 1: the nearest point is x = 10, so the prediction is 100. If the true trend were y = x², it would be 400. k-NN cannot extrapolate.

Bias and variance. Averaging k noisy targets divides the noise variance by k (σ²/k). But the k neighbours spread over a wider region, where the true function differs from its value at the query, which is bias. In exercise 1, at x = 0.25 on a sine curve:

  • k = 1 has bias² 0.0001 and variance 0.082;
  • k = 50 has bias² 0.011 and variance 0.0024.

The steps in plain English:

  1. Standardise the inputs.
  2. For a query, find the k nearest training points.
  3. Average their targets, or weight them by 1/distance.
  4. Choose k by leave-one-out or cross-validated error.
  5. Flag queries far from all training points: their predictions are guesses.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Prediction at 1.4 with k = 2?
  2. 2. Variance of a k-NN average of independent targets with noise σ²?
  3. 3. Distance weighting gives more influence to…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 30 minUndergraduate students and practising engineers.

The estimator

Plain k-NN: f̂(x) = (1/k) Σ over the k neighbours of yᵢ.

Weighted: f̂(x) = Σ wᵢyᵢ/Σ wᵢ with wᵢ = 1/d(x, xᵢ) (or a kernel). It equals yᵢ exactly at a training point, so it interpolates.

Linear smoother. f̂ = Ly, where each row of L has k entries equal to 1/k. The degrees of freedom are tr(L) = n/k (if each point counts itself). Leave-one-out excludes the point from its own neighbourhood, which is cheap to compute for k-NN.

Bias and variance at x:

  • Var ≈ σ²/k;
  • Bias ≈ ½ f″(x)·E[(neighbour offset)²] in the interior. It grows like (k/n)^(2/p), because the neighbourhood radius scales as (k/n)^(1/p).
  • Optimal k ∝ n^(4/(p+4)), giving MSE ~ n^(−4/(p+4)).

Boundaries and extrapolation. Neighbourhoods near the edge are one-sided, which biases the estimate (as for LOESS degree 0, D1.19). Beyond the data the prediction is constant.

from sklearn.neighbors import KNeighborsRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
model = make_pipeline(StandardScaler(), KNeighborsRegressor(n_neighbors=10, weights="distance")).fit(X, y)

Use it when there are few inputs, dense data covering the operating envelope, and an unknown non-linear relationship. Prefer parametric or physics-informed models when data are sparse, when you must extrapolate, or when there are many inputs.

🐍 Exercise 1: k-NN regression, its tuning and its bias–variance
Implement k-NN regression (plain and distance-weighted), leave-one-out MSE for choosing k, and a Monte-Carlo bias–variance estimate; check the hand example including flat extrapolation, find the LOO-optimal k on a noisy sine, and show that larger k trades variance for bias.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Degrees of freedom of plain k-NN regression are about…
  2. 2. Distance-weighted k-NN at a training point returns…
  3. 3. KNeighborsRegressor(weights='distance') uses…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Consistency. Like classification, k-NN regression is universally consistent if k → ∞ and k/n → 0 (Stone, 1977). It converges to E[y | x] for any distribution with finite variance.

Minimax rates. For twice-differentiable f in p dimensions, the best rate is n^(−4/(p+4)), and k-NN attains it with tuned k, as do kernel and local-linear smoothers (Györfi et al., 2002). The exponent shows the curse of dimensionality directly: with p = 2 the rate is n^(−2/3), with p = 20 it is n^(−1/6).

k-NN versus kernels. k-NN is a kernel smoother with an adaptive bandwidth: the radius that contains k points. It is wide where data are sparse and narrow where dense. Local-linear versions remove boundary bias.

Uncertainty. The spread of the neighbours’ targets gives a rough local predictive interval. Conformal methods give calibrated intervals.

Interview questions.

  • Why can’t k-NN extrapolate? Its predictions are averages of observed targets, so they always lie within the range of training targets.
  • How do you choose k fast? Leave-one-out costs no more than one neighbour search with k + 1 neighbours.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Optimal k-NN MSE rate in p dimensions (smooth f)?
  2. 2. k-NN is like a kernel smoother with…
  3. 3. k-NN predictions always lie…

Level 4: Expert

★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.

Estimating battery state of charge

History.

  • Nearest-neighbour regression and kernel regression (Nadaraya, 1964; Watson, 1964) developed together.
  • Stone (1977) proved universal consistency.
  • Györfi, Kohler, Krzyżak and Walk (2002) gave the definitive theory of rates.
  • In battery management, look-up tables of open-circuit voltage against SOC and temperature remain standard, and data-driven k-NN or kernel estimators refine them as fleets log data.

Exercise 1. The hand example gives 2.5 at x = 1.4, and a flat 100 beyond the data. On a noisy sine with n = 300, the leave-one-out MSE by k is 0.167 (k = 1), 0.101 (5), 0.094 (15), 0.099 (50) and 0.180 (150). At x = 0.25, going from k = 1 to k = 50 cuts the variance 34-fold and raises bias² 100-fold.

Exercise 2: SOC from voltage and temperature. Setup: a non-linear OCV curve with a temperature shift; training at 0–30 °C; test inside (0–30 °C) and in a cold soak (−20 to −5 °C); 8 repetitions. The table shows the SOC RMSE inside / outside the training range.

Training samples k-NN (LOO k) Linear Cubic in V + temperature
100 0.046 / 0.122 0.064 / 0.068 0.024 / 0.051
1000 0.012 / 0.061 0.059 / 0.059 0.021 / 0.043
  • With plenty of data and inside the envelope, k-NN is the most accurate: it captures the steep ends of the OCV curve, which a cubic cannot.
  • With 100 samples the physics-shaped cubic wins: its few parameters are estimated well, while k-NN’s local averages are noisy.
  • In the cold soak, k-NN is worst at both sizes: its error grows 2.7–5 times, because it can only reuse the 0 °C neighbours.
  • For battery management, use the data-driven estimator inside its envelope and fall back to (or blend with) a physical model outside it.
🐍 Exercise 2 (research): state of charge inside and outside the envelope
Simulate battery voltage from SOC and temperature with a non-linear OCV curve; train on 0–30 °C and compare k-NN regression (k by leave-one-out), linear regression and a cubic-in-voltage model by SOC RMSE inside the training range and in a −20 to −5 °C cold soak, for 100 and 1000 samples.

k-NN regression in AI, robotics and aerospace

  • Battery and component state estimation from logged operating data.
  • Performance maps: engine, thruster and actuator look-up tables refined from test data.
  • Robot learning from demonstration: retrieve and average actions from similar past states.
  • Surrogate models: quick interpolators for expensive simulations within a sampled design space.

References

  1. C. J. Stone (1977). “Consistent nonparametric regression.” Annals of Statistics 5(4).
  2. L. Györfi, M. Kohler, A. Krzyżak, H. Walk (2002). A Distribution-Free Theory of Nonparametric Regression. Springer.
  3. E. A. Nadaraya (1964). “On estimating regression.” Theory of Probability and Its Applications 9(1).
  4. N. S. Altman (1992). “An introduction to kernel and nearest-neighbor nonparametric regression.” The American Statistician 46(3).
  5. G. L. Plett (2015). Battery Management Systems, Volume I: Battery Modeling. Artech House.