Skip to content
E
Educatum

How does KNN regression work?

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

k-Nearest Neighbors (k-NN) regression is a non-parametric, lazy algorithm that predicts a continuous value by averaging the target values of the k closest training samples in feature space. Predictions can use uniform averages or inverse-distance weighting, producing flexible piecewise-constant approximations that cannot extrapolate beyond the training target range.

Study Card: How K-Nearest Neighbors (KNN) Regression Works

Direct Answer

K-Nearest Neighbors (KNN) regression predicts a continuous target y^(x)\hat{y}(x) by locating the kk closest training observations Nk(x)N_k(x) under a distance metric (typically Euclidean distance on scaled features) and aggregating their target values. In standard uniform KNN regression, the prediction is the unweighted arithmetic mean; in distance-weighted KNN regression, closer neighbors receive higher weights:

y^(x)=1k∑i∈Nk(x)yiory^(x)=∑i∈Nk(x)wiyi∑i∈Nk(x)wi,wi=1d(x,xi)+ϵ\hat{y}(x) = \frac{1}{k}\sum_{i \in N_k(x)} y_i \qquad\text{or}\qquad \hat{y}(x) = \frac{\sum_{i \in N_k(x)} w_i y_i}{\sum_{i \in N_k(x)} w_i}, \quad w_i = \frac{1}{d(x, x_i) + \epsilon}

Because it is a non-parametric lazy learner, KNN makes no global functional form assumption (unlike linear regression), naturally fitting non-linear curves. However, its prediction surface is piecewise-constant (stepped), inference scales with training set size (O(Nd)O(Nd) brute force), and—crucially—it cannot extrapolate outside the minimum and maximum target values [min⁡yi,max⁡yi][\min y_i, \max y_i] observed in training data.

Key Terms

  • k-Nearest Neighbors (Nk(x)N_k(x)): The kk training points closest to query xx according to the chosen distance metric.
  • Distance Metric: Measures similarity between feature vectors (e.g., Euclidean, Manhattan, Minkowski).
  • Non-Parametric Model: Does not fix a finite parametric equation like y=w⊤x+by = w^\top x + b; effective capacity adapts locally with training data.
  • Lazy Learning: Stores training observations rather than optimizing weights upfront, shifting compute to inference time.

Example

Suppose we predict home prices from standardized square footage and bedroom count using k=3k = 3. If the three nearest comparable homes in the training set sold for 300,000 dollars, 350,000 dollars, and 400,000 dollars, uniform KNN predicts 300,000+350,000+400,0003=350,000\frac{300{,}000 + 350{,}000 + 400{,}000}{3} = 350{,}000 dollars. Decreasing kk (e.g., k=1k = 1) tracks local variations tightly but amplifies sensitivity to noisy comps (high variance); increasing kk smooths predictions at the expense of local detail (high bias). Note also that even if a test mansion has double the square footage of any training home, KNN can never predict above the highest training target average.

Code Implementation

import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsRegressor

# Generate synthetic 1D non-linear data with noise
np.random.seed(0)
X = np.sort(5 * np.random.rand(100, 1), axis=0)
y = np.sin(X).ravel()
y[::5] += 1.0 * (0.5 - np.random.rand(20))

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=42
)

# Train uniform and distance-weighted KNN Regressors (k=5)
k = 5
knn_uniform = KNeighborsRegressor(n_neighbors=k, weights='uniform').fit(X_train, y_train)
knn_dist = KNeighborsRegressor(n_neighbors=k, weights='distance').fit(X_train, y_train)

print(f"Uniform KNN Test MSE:  {mean_squared_error(y_test, knn_uniform.predict(X_test)):.4f}")
print(f"Weighted KNN Test MSE: {mean_squared_error(y_test, knn_dist.predict(X_test)):.4f}")

# Visualize the piecewise-constant prediction curve
T = np.linspace(0, 5, 500)[:, np.newaxis]
plt.scatter(X_train, y_train, color='darkorange', label='Training data')
plt.plot(T, knn_uniform.predict(T), color='navy', label='Uniform prediction')
plt.plot(T, knn_dist.predict(T), color='teal', linestyle='--', label='Distance-weighted')
plt.xlabel('Feature Value (X)')
plt.ylabel('Target Variable (y)')
plt.title(f'KNN Regression (k = {k})')
plt.legend()
plt.show()
  • KNN Classification vs. Regression: Classification takes majority or weighted class votes; regression takes unweighted or weighted target averages (hence cannot extrapolate beyond training target bounds).
  • Feature Scaling: Essential whenever features have different units or variances, preventing large-scale features from dominating Euclidean distances.
  • Curse of Dimensionality: High-dimensional feature spaces become sparse, pushing nearest neighbors far away and degrading regression accuracy.
  • Bias-Variance Tradeoff (kk): Small kk yields low bias and high variance; larger kk yields smoother estimates with variance scaling roughly as σ2/k\sigma^2 / k and higher bias.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.