---
title: "k-Nearest Neighbors Regression: What Is This House Worth? Ask the Neighbors"
description: "k-nearest neighbors regression in R, by hand and with FNN, on 21,600 house sales around Seattle: distances, scaling and weighting the predictors, choosing k by validation on later sales, the bias-variance trade-off, comparable houses for one sale, the curse of dimensionality with noise predictors, kNN against regression, GAM and random forest, a local correction of a regression, prediction intervals by conformal prediction, and APA reporting."
author: ""
---
```{r options, echo=FALSE, warning=FALSE, message=FALSE}
directory<-if (rstudioapi::isAvailable()) paste0(dirname(rstudioapi::getActiveDocumentContext()$path),"/") else ""
source(paste0(directory, "R/code_options.R"))
# no knitr cache: the page downloads its data each time it runs (in a few seconds),
# and a cached chunk would quietly keep an old download
knitr::opts_chunk$set(fig.height = 4.5, cache = FALSE)
```
## The question: what an estate agent does
How do you find out what a house is worth? You look at what **similar houses nearby** were sold for, and take something like the average. Estate agents call these houses *comparables*. No formula, no coefficients.
**k-nearest neighbors** (kNN) is this, done by a computer. To predict a case, find the $k$ most similar cases in the data and average their outcomes. It is the simplest method of machine learning, more than 70 years old (Fix and Hodges described it in 1951; Cover & Hart, 1967, worked out how good it can be), and it has no training at all. The whole model is the data.
All the difficulty is in two words: how many (**k**), and what is **similar**. Is a house of the same size at a distance of 3 km more similar than a house twice as large next door?
```{r packages}
library(FNN) # knn.reg(), get.knnx(): fast neighbors
library(mgcv) # bam(), for comparison (comes with R)
library(ranger) # random forest, for comparison
library(ggplot2)
# number formats for the text
f0 <- function(x) formatC(x, format = "f", digits = 0, big.mark = ",")
f1 <- function(x) formatC(x, format = "f", digits = 1, big.mark = ",")
f2 <- function(x) formatC(x, format = "f", digits = 2, big.mark = ",")
f3 <- function(x) formatC(x, format = "f", digits = 3, big.mark = ",")
num <- function(x) trimws(format(x, big.mark = ","))
pct <- function(x, d = 0) paste0(formatC(100 * x, format = "f", digits = d), "%")
rmse <- function(a, b) sqrt(mean((a - b)^2))
```
---
## 1. The data
The county around Seattle (King County, Washington) publishes every sale of a house. This file has the sales from May 2014 to May 2015, and OpenML (2019) serves it as CSV:
```{r download}
raw <- read.csv("https://www.openml.org/data/get_csv/21578898/house_sales.arff")
house <- with(
raw,
data.frame(
price = price,
logp = log10(price),
date = as.Date(substr(date, 1, 8), "%Y%m%d"),
east = (long + 122.2) * 111.32 * cos(47.56 * pi / 180),
north = (lat - 47.56) * 111.32, # kilometers from a point in the middle
lsize = log2(sqft_living),
grade,
built = yr_built,
llot = log2(sqft_lot),
view,
water = as.integer(waterfront),
zip = factor(zipcode)
)
)
nrow(house)
range(house$date)
quantile(house$price, c(0.01, 0.25, 0.5, 0.75, 0.99))
```
There are `r num(nrow(house))` sales. `east` and `north` are the position in kilometers, `lsize` the living space (log base 2, so one unit is a doubling), `grade` the county's grade of the building (1 to 13), `built` the year, `llot` the land (log), `view` (0 to 4) and `water` (on the waterfront). Prices are skewed, so we predict $\log_{10}$ of the price; an error of 0.04 is about 10%.
The use of such a model is to value houses that are sold **later**. So we learn from the sales until January 2015, choose the settings with those of February and March, and test with April and May:
```{r split}
train <- subset(house, date < as.Date("2015-02-01"))
valid <- subset(house, date >= as.Date("2015-02-01") & date < as.Date("2015-04-01"))
test <- subset(house, date >= as.Date("2015-04-01"))
c(train = nrow(train), validation = nrow(valid), test = nrow(test))
```
---
## 2. Look at the data
```{r look, fig.height = 6}
ggplot(train, aes(east, north, colour = logp)) +
geom_point(size = 0.5, alpha = 0.7) +
coord_fixed() +
scale_colour_viridis_c(
option = "C",
name = "price",
breaks = log10(c(1e5, 2.5e5, 5e5, 1e6, 2.5e6)),
labels = c("100k", "250k", "500k", "1M", "2.5M"),
limits = log10(c(1.5e5, 2.5e6)),
oob = scales::squish
) +
labs(title = "House prices around Seattle", x = "km east", y = "km north") +
theme_bw()
```
Place matters, and not in a way that a straight line could follow: there are expensive shores, cheap corridors and sharp borders.
---
## 3. The method step by step, with formulas
### Step 1: a distance
The usual one is Euclidean. With the predictors $x_1, \dots, x_p$,
$$d(x, x') = \sqrt{\sum_{j=1}^{p} w_j^2\, (x_j - x'_j)^2}$$
The **weights** $w_j$ are part of the method, whether one chooses them or not. If a predictor is measured in other units, its weight changes.
### Step 2: the neighbors, and their mean
Let $N_k(x)$ be the $k$ training cases with the smallest distance to $x$. The prediction is
$$\hat f(x) = \frac{1}{k}\sum_{i \in N_k(x)} y_i$$
By hand, for the first house of the validation set, with place and size only:
```{r by_hand}
new <- valid[1, ]
d <- sqrt(
(train$east - new$east)^2 + (train$north - new$north)^2 + (2 * (train$lsize - new$lsize))^2
) # a doubling of the size counts as 2 km
near <- order(d)[1:5]
cbind(
distance = round(d[near], 2),
km = round(sqrt((train$east[near] - new$east)^2 + (train$north[near] - new$north)^2), 2),
train[near, c("price", "built", "grade")],
size = round(2^train$lsize[near])
)
c(predicted = 10^mean(train$logp[near]), sold_for = new$price)
```
### Step 3: the choice of $k$
With $k = 1$ the prediction jumps from house to house and copies every accident of a single sale: no bias, much variance. With $k = n$ it is the mean of all houses: no variance, much bias. In between is the best value, and it must be found by trying.
### Step 4: no training, slow prediction
There is nothing to estimate. But for each new case all the distances must be computed. Programs use search trees (`FNN` does) that avoid most of the work in few dimensions.
---
## 4. What is similar? Scaling
Try three definitions, each with several $k$, on the validation sales:
```{r scaling}
vars <- c("east", "north", "lsize", "grade", "built", "llot", "view", "water")
centre <- colMeans(train[, vars]); spread <- apply(train[, vars], 2, sd)
Z <- function(d, w = rep(1, length(vars))) {
sweep(sweep(sweep(as.matrix(d[, vars]), 2, centre), 2, spread, "/"), 2, w, "*")
} # standardize with the training data, then weight
knn <- function(Ztr, Zte, k, y = train$logp) knn.reg(Ztr, Zte, y, k = k)$pred
ks <- c(1, 2, 3, 5, 8, 12, 20, 35, 60, 100)
place <- c("east", "north")
curves <- rbind(
data.frame(
k = ks,
rmse = sapply(ks, function(k) rmse(knn(train[, place], valid[, place], k), valid$logp)),
what = "place only"
),
data.frame(
k = ks,
rmse = sapply(ks, function(k) rmse(knn(train[, vars], valid[, vars], k), valid$logp)),
what = "all predictors, raw units"
),
data.frame(
k = ks,
rmse = sapply(ks, function(k) rmse(knn(Z(train), Z(valid), k), valid$logp)),
what = "all predictors, standardised"
)
)
best <- do.call(rbind, lapply(split(curves, curves$what), function(d) d[which.min(d$rmse), ]))
best
```
```{r k_chart}
ggplot(curves, aes(k, rmse, colour = what)) +
geom_line(linewidth = 0.9) +
geom_point(size = 2) +
scale_x_log10(breaks = ks) +
scale_colour_manual(values = c("#eda100", "#2a78d6", "#eb6834"), name = NULL) +
labs(
title = "Error on later sales, by the number of neighbours",
x = "k (log scale)",
y = "RMSE of log10(price)"
) +
theme_bw() +
theme(legend.position = "bottom")
```
- The classic **U-shape**: too few neighbors are noisy, too many are not similar.
- With **place only**, `r f3(best["place only", "rmse"])` at best.
- With all the predictors in **raw units**, `r f3(best["all predictors, raw units", "rmse"])`. The year of construction runs over a hundred units and the waterfront over one, so the years decide who is a neighbor.
- **Standardized**, `r f3(best["all predictors, standardised", "rmse"])`. Each predictor has the same weight now.
### Weights for the predictors
But why the **same** weight? Place matters more than the size of the garden. We can search for better weights on the validation set, one predictor at a time, doubling or halving its weight as long as it helps:
```{r weights}
w <- setNames(rep(1, length(vars)), vars)
score <- function(w, k = 8) rmse(knn(Z(train, w), Z(valid, w), k), valid$logp)
current <- score(w); history <- data.frame(step = 0, changed = "start", rmse = current)
for (round in 1:4) {
for (v in vars) {
for (f in c(2, 0.5)) {
repeat {
trial <- w
trial[v] <- trial[v] * f
s <- score(trial)
if (s < current - 1e-5) {
w <- trial
current <- s
history <- rbind(history, data.frame(step = nrow(history), changed = v, rmse = s))
} else {
break
}
}
}
}
}
w
k_w <- ks[which.min(sapply(ks, function(k) score(w, k)))]
c(standardised = best["all predictors, standardised", "rmse"], weighted = score(w, k_w), k = k_w)
```
The search gives the most weight to `r paste(names(sort(w, decreasing = TRUE))[1:3], collapse = ", ")`, and the error falls to `r f3(score(w, k_w))`. **The weights are the model.** They were tuned on the validation sales, so that error is too good; the test set will tell. (Weighting the neighbors themselves by their distance is another refinement, which helps a little.)
---
## 5. The comparables of one house
An advantage that few other methods of machine learning have: the prediction can be **shown**.
```{r comparables}
Zt <- Z(train, w); Zn <- Z(test, w)
one <- 3
nn <- get.knnx(Zt, Zn[one, , drop = FALSE], k = k_w)
comp <- train[nn$nn.index[1, ], ]
show <- rbind(
cbind(what = "to be valued", test[one, ]),
cbind(what = paste("neighbour", seq_len(k_w)), comp)
)
data.frame(
what = show$what,
price = f0(show$price),
sqft = round(2^show$lsize),
grade = show$grade,
built = show$built,
km = round(sqrt((show$east - test$east[one])^2 + (show$north - test$north[one])^2), 1),
row.names = NULL
)
c(predicted = 10^mean(comp$logp), sold_for = test$price[one])
```
A person who doubts the value of `r f0(10^mean(comp$logp))` dollars can look at the `r k_w` houses and say which of them is not comparable.
---
## 6. Against other methods
```{r compare}
learn <- rbind(train, valid) # the test may use everything before April
Zl <- sweep(sweep(sweep(as.matrix(learn[, vars]), 2, centre), 2, spread, "/"), 2, w, "*")
knn_pred <- knn.reg(Zl, Zn, learn$logp, k = k_w)$pred
lin <- lm(logp ~ east + north + lsize + grade + built + llot + view + water, data = learn)
# each postal code its own level
linz <- lm(logp ~ zip + lsize + grade + built + llot + view + water, data = learn)
gm <- bam(
logp ~ s(east, north, k = 150) +
s(lsize, k = 6) +
s(grade, k = 6) +
s(built, k = 8) +
s(llot, k = 6) +
view +
water,
data = learn
)
set.seed(161)
rf <- ranger(
logp ~ east + north + lsize + grade + built + llot + view + water,
data = learn,
num.trees = 500
)
# a regression for the house, and kNN for the place: the mean residual of the nearest houses
res_learn <- resid(lin)
local <- knn.reg(learn[, place], test[, place], res_learn, k = 15)$pred
preds <- list(
`Linear regression` = predict(lin, test),
`Regression + postal codes` = predict(linz, test),
`kNN, standardised` = knn.reg(
Z(learn),
Z(test),
learn$logp,
k = best["all predictors, standardised", "k"]
)$pred,
`kNN, weighted` = knn_pred,
`GAM with a map` = as.numeric(predict(gm, test)),
`Random forest` = predict(rf, test)$predictions,
`Regression + kNN of its residuals` = predict(lin, test) + local
)
results <- data.frame(
model = names(preds),
rmse = sapply(preds, rmse, b = test$logp),
median_error = sapply(preds, function(p) median(abs(10^(p - test$logp) - 1))),
row.names = NULL
)
results <- results[order(results$rmse), ]
print(
transform(results, rmse = round(rmse, 4), median_error = round(median_error, 3)),
row.names = FALSE
)
get <- function(m, col = "rmse") results[results$model == m, col]
```
```{r compare_chart}
results$model <- factor(results$model, levels = rev(results$model))
ggplot(results, aes(median_error, model)) +
geom_segment(aes(x = 0, xend = median_error, yend = model), colour = "grey75") +
geom_point(size = 3, colour = "#2a78d6") +
scale_x_continuous(labels = function(v) paste0(100 * v, "%"), limits = c(0, NA)) +
labs(
title = "Median error on the sales of April and May 2015",
x = "half of the predictions are closer than this",
y = NULL
) +
theme_bw() +
theme(plot.title.position = "plot")
```
- Plain **linear regression** misses half of the houses by more than `r pct(get("Linear regression", "median_error"))`; the weighted **kNN** by more than `r pct(get("kNN, weighted", "median_error"))`. Knowing the neighbors is worth a lot.
- A regression with **postal codes** comes close to kNN (RMSE `r f3(get("Regression + postal codes"))` against `r f3(get("kNN, weighted"))`). It uses a simple formula for what is simple (size, grade, age), and the neighborhood for the rest.
- The same idea without postal codes: a **regression for the house and kNN for the place**, that is, the linear regression plus the average residual of the 15 nearest houses. A few lines of code take the RMSE of the regression from `r f3(get("Linear regression"))` to `r f3(get("Regression + kNN of its residuals"))`. It does not reach the weighted kNN, because the formula of the regression is too simple for the rest, too.
- The **GAM** with a smooth map and smooth curves has the smallest error, `r f3(get("GAM with a map"))`, and the **random forest** has `r f3(get("Random forest"))`.
Where kNN loses, it is because it cannot learn that a doubling of the size adds a certain share of the price **everywhere**. It must find, for every place and grade, houses of the right size. The GAM adds up one map and one curve per predictor, and learns each of them from all the sales.
---
## 7. The curse of dimensionality
In many dimensions nothing is near. Add predictors that mean nothing (random numbers), and watch:
```{r curse}
set.seed(162)
extra <- c(0, 1, 2, 4, 8, 16)
noise <- matrix(
rnorm((nrow(learn) + nrow(test)) * max(extra)),
ncol = max(extra),
dimnames = list(NULL, paste0("noise", seq_len(max(extra))))
)
in_learn <- seq_len(nrow(learn)); in_test <- nrow(learn) + seq_len(nrow(test))
curse <- sapply(extra, function(m) {
A <- cbind(Z(learn), noise[in_learn, seq_len(m), drop = FALSE])
B <- cbind(Z(test), noise[in_test, seq_len(m), drop = FALSE])
rmse(knn.reg(A, B, learn$logp, k = 8)$pred, test$logp)
})
lm_noise <- sapply(extra, function(m) {
L <- cbind(learn[, c("logp", vars)], noise[in_learn, seq_len(m), drop = FALSE])
Te <- cbind(test[, vars], noise[in_test, seq_len(m), drop = FALSE])
rmse(predict(lm(logp ~ ., data = L), Te), test$logp)
})
rbind(noise_predictors = extra, kNN = round(curse, 4), linear_regression = round(lm_noise, 4))
dist_ratio <- sapply(c(2, 8, 24), function(p) {
set.seed(163)
u <- matrix(runif(2000 * p), ncol = p)
d <- sqrt(colSums((t(u[-1, ]) - u[1, ])^2))
min(d) / max(d)
})
setNames(round(dist_ratio, 2), paste(c(2, 8, 24), "dimensions"))
```
With 16 useless predictors the error of kNN goes from `r f3(curse[1])` to `r f3(curse[6])`. Linear regression hardly notices (`r f3(lm_noise[1])` and `r f3(lm_noise[6])`): it gives them coefficients near zero. kNN cannot ignore a predictor; each one has its weight in the distance. The second output shows the geometry: among 2,000 random points, the nearest is at `r pct(dist_ratio[1])` of the distance of the farthest in 2 dimensions, and at `r pct(dist_ratio[3])` in 24. "Nearest" loses its meaning (Beyer et al., 1999).
---
## 8. How sure is the prediction? Conformal intervals
kNN has no standard errors. **Conformal prediction** gives intervals for any method, with one simple idea: look at the errors on sales that were not used, and take their 90% quantile (Lei et al., 2018). Here: predict the validation sales from the training sales, and use those errors for the test.
```{r conformal}
err <- abs(knn(Z(train, w), Z(valid, w), k_w) - valid$logp)
q90 <- sort(err)[ceiling(0.9 * (length(err) + 1))]
inside <- abs(knn_pred - test$logp) <= q90
c(half_width_log10 = q90, factor = 10^q90, coverage_in_test = mean(inside))
cheap <- cut(
knn_pred,
quantile(knn_pred, 0:4 / 4),
include.lowest = TRUE,
labels = c("cheapest quarter", "2", "3", "most expensive quarter")
)
round(tapply(inside, cheap, mean), 3)
```
The 90% interval goes from the prediction divided by `r f2(10^q90)` to the prediction times `r f2(10^q90)`. In the test `r pct(mean(inside), 1)` of the houses were inside. The coverage is right **on average**, and not in every group: it ranges from `r pct(min(tapply(inside, cheap, mean)))` to `r pct(max(tapply(inside, cheap, mean)))` across the quarters of the predicted price, because the interval has the same width everywhere.
---
## 9. Things to keep in mind
- **Scale, then weight.** Both decide the result. Use the training data for the center and the spread.
- **Choose $k$ by validation**, on cases that resemble the future. An odd $k$ has no meaning in regression.
- **At the edges** kNN is biased: the neighbors of the largest house are all smaller. The prediction can never leave the range of the data.
- **Few, strong predictors.** With many weak ones use other methods, or reduce them first.
- **Categories** need a distance of their own (0 if equal, 1 if not, times a weight).
- **Dependence**: the same house sold twice, flats of the same building. Keep them on the same side of the split.
- **Distance in space is not distance in life.** Two houses on the opposite shores of a lake are near on the map.
- **It is a smoother.** kNN with one predictor is a rough cousin of [LOESS](EXAMPLE_LOESS.Rmd), which fits a line instead of a mean and has less bias at the ends.
---
## 10. Reporting the results in APA style
A report (APA 7th edition) needs the predictors and their scaling, the distance and the weights, $k$ and how it was chosen, the split, the errors in understandable units, and simpler alternatives. The numbers come from the R objects:
```{r apa_numbers}
r <- results[order(results$rmse), ]
apa_table <- data.frame(
Model = as.character(r$model),
rmse = f3(r$rmse),
med = pct(r$median_error, 1)
)
```
**Method** (data analysis):
> We predicted the log price of `r num(nrow(test))` houses sold in King County, Washington, in April and May 2015 from `r num(nrow(learn))` earlier sales (May 2014–March 2015) with k-nearest neighbors regression. Predictors were the position (km), log living space, grade, year of construction, log lot size, view and waterfront, standardized with the training data. The number of neighbors and the weights of the predictors in the Euclidean distance were chosen with the sales of February and March 2015. Linear regression with and without postal codes, a generalized additive model with a smooth of the position, a random forest, and a regression corrected by the residuals of neighboring houses served for comparison. Prediction intervals are split-conformal (Lei et al., 2018). Analyses were conducted in R (Version `r paste(R.version$major, R.version$minor, sep = ".")`; R Core Team, `r R.version$year`) with the package FNN.
**Results:**
> With *k* = `r k_w` and weighted predictors, half of the predictions were within `r pct(get("kNN, weighted", "median_error"), 1)` of the price (RMSE of log~10~ price = `r f3(get("kNN, weighted"))`), compared with `r pct(get("Linear regression", "median_error"), 1)` for linear regression (Table 1). A linear regression corrected by the mean residual of the 15 nearest houses had a median error of `r pct(get("Regression + kNN of its residuals", "median_error"), 1)`. The 90% conformal intervals (predicted price divided or multiplied by `r f2(10^q90)`) contained `r pct(mean(inside), 1)` of the prices.
**Table 1**
*Prediction of House Prices in April and May 2015*
```{r apa_table, echo=FALSE}
knitr::kable(apa_table, col.names = c("Model", "RMSE (log~10~ price)", "Median error"), align = "lrr", format = "pipe", row.names = FALSE)
```
*Note.* *N* = `r num(nrow(test))`. Median error: the median of the absolute relative error of the price.
**Points to remember:**
- Report the scaling and the weights: they are the model.
- Say how $k$ was chosen.
- Test on later cases if the use is prediction.
- Give errors in percent, not only in logs.
---
## 11. Summary
| | |
|---|---|
| **When** | Prediction with few, strong predictors and much data, especially positions |
| **The method** | The mean outcome of the $k$ nearest cases |
| **How (R)** | `FNN::knn.reg(train, test, y, k)`; neighbors: `get.knnx()` |
| **Choices** | Predictors, scaling, weights, $k$ |
| **$k$** | Small: noisy. Large: biased. Choose by validation |
| **Strength** | No assumptions, and every prediction can be shown |
| **Weakness** | Many predictors, edges, sparse regions |
| **A useful mixture** | Correct a regression by the mean residual of the nearest cases |
| **Related pages** | [LOESS](EXAMPLE_LOESS.Rmd), [random forest](EXAMPLE_RANDOM_FOREST.Rmd), [support vector regression](EXAMPLE_SUPPORT_VECTOR_REGRESSION.Rmd) |
---
## References
Beyer, K., Goldstein, J., Ramakrishnan, R., & Shaft, U. (1999). When is "nearest neighbor" meaningful? In *Database theory – ICDT'99* (pp. 217–235). Springer. https://doi.org/10.1007/3-540-49257-7_15
Cover, T., & Hart, P. (1967). Nearest neighbor pattern classification. *IEEE Transactions on Information Theory*, *13*(1), 21–27. https://doi.org/10.1109/TIT.1967.1053964
Fix, E., & Hodges, J. L. (1951). *Discriminatory analysis: Nonparametric discrimination: Consistency properties* (Report No. 4). USAF School of Aviation Medicine. https://doi.org/10.1037/e471672008-001
Lei, J., G'Sell, M., Rinaldo, A., Tibshirani, R. J., & Wasserman, L. (2018). Distribution-free predictive inference for regression. *Journal of the American Statistical Association*, *113*(523), 1094–1111. https://doi.org/10.1080/01621459.2017.1307116
OpenML. (2019). *House sales in King County, USA* (data set 42092) [Data set]. https://www.openml.org/d/42092