Skip to content

k-nearest neighbors

Predict from the most similar rows. Simple and surprisingly strong in low dimensions, it falls apart when scale, irrelevant columns or many features distort what "near" means.

Applied ~9 min8 steps

What runs in CodeSplash

You will be able to

  • Explain how k trades bias for variance
  • Say why scaling and irrelevant features break distance
  • Weigh neighbors' speed at training against their cost when predicting

Read first

01

No training at all

Read

k-nearest neighborsk-nearest neighborsPredicts from the k most similar training rows. It has no fitting step, and every prediction scans the data. stores the training rows. To predict, it finds the kk closest rows in the standardized design, then averages their targets or takes a vote.

There's no fitting step, so there's nothing to overfit in the usual sense. The price arrives at prediction time: every prediction scans the data.

02

How simple is too simple?

Predict

Predict first

Ozone from solar radiation, wind and temperature. A linear model on the same data plus month has a cross-validated RMSE of 22.9. What about averaging the 7 most similar days?

Worse than linearAbout the sameBetter than linear
Reveal

Better: RMSE 18.7. Three scaled numeric features are the setting where neighbors shine, and hot, still days do have similar ozone. It finds local shape without being told about it.

03

Change k

Explore

For this model, Flexibility is kk. Start at 1, then raise it. Watch the boundary smooth out, and compare Training accuracy with New-data accuracy. Press memorize the noise to see k=1k = 1 on noisy data.

DExplorable · Decision boundary zoo

What shapes of boundary can each kind of model draw?

Which model will score highest on new data from this shape?

How sure?

Data

Model

1

k for neighbors, depth for trees, γ × 2 for the kernel, hidden units for the network.

0.20
150
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

At k=1k = 1, each row is its own nearest neighbor, so training accuracy is perfect and tells you nothing.

04

Distance is the whole model

Read

Everything rests on what "near" means.

  • Scale: unscaled, the column with the largest numbers decides. The card says standardizes inputs for this reason.
  • Irrelevant columns: they add distance without information.
  • Many columns: in high dimensions, nearly all rows are about equally far from each other, so "nearest" stops meaning much.

Categories count as 0/1 distances, which is a blunt measure next to scaled numbers. On penguins with island, sex and bill length, log loss is 0.152, some way behind models that use more measurements.

05

Weights and ties

Read

Neighbor weights can count close neighbors more than distant ones. On Pima with distance weights and k=15k = 15, AUC is 0.838, and with two features and balanced class votes it's 0.792.

Distances, neighbor order on ties and weights are computed the same way in Python and R, so predictions are identical in both.

06

Check your understanding

Checkpoint

Check yourself

Which kk has the highest variance?

Show the answer

Answer: a

With k=1k = 1, each prediction copies one row, noise included. Larger kk averages noise away, at the cost of blurring local detail.

Check yourself

Which change would hurt k-nearest neighbors the most?

Show the answer

Answer: b

Standardizing makes units harmless. Noise columns dilute distance itself, and scaling can't remove them. Prune features first, or use a learner that ignores them.

Check yourself

Where does k-nearest neighbors spend its time?

Show the answer

Answer: b

That's why its gallery card rates it mid-range on speed. It also has to keep the training rows with the model.

07

Try it

In the app

In the Learners step, select k-nearest neighbors and open Hyperparameters. Neighbors (k) and Neighbor weights can both be tuned. On a large table, try it on a sample first.

Python
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

df = pd.read_csv("airquality.csv").dropna(subset=["Ozone"])
X, y = df[["Solar.R", "Wind", "Temp"]], df["Ozone"]
for k in [1, 3, 7, 15, 40]:
    m = make_pipeline(SimpleImputer(strategy="median"), StandardScaler(), KNeighborsRegressor(k))
    print(k, -cross_val_score(m, X, y, cv=5, scoring="neg_root_mean_squared_error").mean().round(2))
R
df <- airquality[!is.na(airquality$Ozone), ]
x <- as.matrix(df[, c("Solar.R", "Wind", "Temp")])
set.seed(1)
fold <- sample(rep(1:5, length.out = nrow(x)))
knn_rmse <- function(k) mean(sapply(1:5, function(f) {
  tr <- x[fold != f, ]; te <- x[fold == f, ]
  med <- apply(tr, 2, median, na.rm = TRUE)
  for (j in colnames(x)) { tr[is.na(tr[, j]), j] <- med[j]; te[is.na(te[, j]), j] <- med[j] }
  m <- colMeans(tr); s <- apply(tr, 2, sd)
  p <- FNN::knn.reg(scale(tr, m, s), scale(te, m, s), df$Ozone[fold != f], k = k)$pred
  sqrt(mean((df$Ozone[fold == f] - p)^2))
}))
sapply(c(1, 3, 7, 15, 40), knn_rmse)
08

Recap

Recap
  • Neighbors predict from the most similar rows, and kk sets the bias–variance trade.
  • Scale matters, irrelevant columns hurt, and many columns dissolve the idea of "near".
  • It's cheap to train and costly to predict.

Concepts in this lesson