How does KNN regression work?
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 by locating the closest training observations 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:
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 ( brute force), and—crucially—it cannot extrapolate outside the minimum and maximum target values observed in training data.
Key Terms
- k-Nearest Neighbors (): The training points closest to query 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 ; 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 . 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 dollars. Decreasing (e.g., ) tracks local variations tightly but amplifies sensitivity to noisy comps (high variance); increasing 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()
Related Concepts
- 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 (): Small yields low bias and high variance; larger yields smoother estimates with variance scaling roughly as and higher bias.