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.
What runs in CodeSplash
- k-nearest neighbors Verified in Python and R
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
No training at all
Readk-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 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.
How simple is too simple?
PredictPredict 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?
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.
Change k
ExploreFor this model, Flexibility is . 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 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?
Data
Model
k for neighbors, depth for trees, γ × 2 for the kernel, hidden units for the network.
Commit your prediction above to see the result
Make your prediction to see the result.
At , each row is its own nearest neighbor, so training accuracy is perfect and tells you nothing.
Distance is the whole model
ReadEverything 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.
Weights and ties
ReadNeighbor weights can count close neighbors more than distant ones. On Pima with distance weights and , 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.
Check your understanding
CheckpointCheck yourself
Which has the highest variance?
Show the answer
Answer: a
With , each prediction copies one row, noise included. Larger 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.
Try it
In the appIn 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.
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))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)Recap
Recap- Neighbors predict from the most similar rows, and 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