Skip to main content

k-Nearest Neighbors Regression: What Is This House Worth? Ask the Neighbors

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.

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?

Code
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:

Code
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)
[1] 21613
Code
range(house$date)
[1] "2014-05-02" "2015-05-27"
Code
quantile(house$price, c(0.01, 0.25, 0.5, 0.75, 0.99))
       1%       25%       50%       75%       99% 
 153500.4  321950.0  450000.0  645000.0 1964400.0 

There are 21,613 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:

Code
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))
     train validation       test 
     15611       3125       2877 

2. Look at the data

Code
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()

Plot: 2. Look at the data

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:

Code
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])
)
      distance   km  price built grade size
16518     0.90 0.78 304000  1972     7  900
6006      0.94 0.67 300000  1982     7  970
16644     0.97 0.31 335000  1967     7 1060
6767      1.03 0.67 350000  1967     7 1010
17242     1.04 0.93 300000  1971     7  910
Code
c(predicted = 10^mean(train$logp[near]), sold_for = new$price)
predicted  sold_for 
 317136.2  180000.0 

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:

Code
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
                              k       rmse                         what
all predictors, raw units     5 0.10989469    all predictors, raw units
all predictors, standardised 12 0.09012174 all predictors, standardised
place only                    8 0.12973096                   place only
Code
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")

K chart – 4. What is similar? Scaling

  • The classic U-shape: too few neighbors are noisy, too many are not similar.
  • With place only, 0.130 at best.
  • With all the predictors in raw units, 0.110. The year of construction runs over a hundred units and the waterfront over one, so the years decide who is a neighbor.
  • Standardized, 0.090. 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:

Code
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
 east north lsize grade built  llot  view water 
 8.00  4.00  2.00  1.00  0.25  1.00  0.25  1.00 
Code
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)
standardised     weighted            k 
  0.09012174   0.08359334   8.00000000 

The search gives the most weight to east, north, lsize, and the error falls to 0.084. 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.

Code
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
)
          what   price sqft grade built  km
1 to be valued 230,000 1250     7  1969 0.0
2  neighbour 1 236,000 1300     7  1967 0.2
3  neighbour 2 169,575 1300     7  1968 0.2
4  neighbour 3 216,000 1280     7  1956 0.8
5  neighbour 4 170,000 1300     7  1961 1.4
6  neighbour 5 190,000 1090     7  1967 0.2
7  neighbour 6 235,500 1380     7  1971 1.6
8  neighbour 7 215,000 1130     7  1969 1.3
9  neighbour 8 225,000 1460     7  1968 1.4
Code
c(predicted = 10^mean(comp$logp), sold_for = test$price[one])
predicted  sold_for 
 205502.8  230000.0 

A person who doubts the value of 205,503 dollars can look at the 8 houses and say which of them is not comparable.


6. Against other methods

Code
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
)
                             model   rmse median_error
                    GAM with a map 0.0813        0.109
                     kNN, weighted 0.0857        0.112
                     Random forest 0.0858        0.106
         Regression + postal codes 0.0894        0.118
                 kNN, standardised 0.0903        0.115
 Regression + kNN of its residuals 0.0922        0.125
                 Linear regression 0.1195        0.168
Code
get <- function(m, col = "rmse") results[results$model == m, col]
Code
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")

Compare chart – 6. Against other methods

  • Plain linear regression misses half of the houses by more than 17%; the weighted kNN by more than 11%. Knowing the neighbors is worth a lot.
  • A regression with postal codes comes close to kNN (RMSE 0.089 against 0.086). 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 0.120 to 0.092. 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, 0.081, and the random forest has 0.086.

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:

Code
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))
                    [,1]   [,2]   [,3]   [,4]   [,5]    [,6]
noise_predictors  0.0000 1.0000 2.0000 4.0000 8.0000 16.0000
kNN               0.0902 0.0959 0.0995 0.1047 0.1150  0.1288
linear_regression 0.1195 0.1195 0.1195 0.1195 0.1196  0.1196
Code
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"))
 2 dimensions  8 dimensions 24 dimensions 
         0.02          0.21          0.35 

With 16 useless predictors the error of kNN goes from 0.090 to 0.129. Linear regression hardly notices (0.120 and 0.120): 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 2% of the distance of the farthest in 2 dimensions, and at 35% 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.

Code
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))
half_width_log10           factor coverage_in_test 
       0.1338998        1.3611305        0.8953771 
Code
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)
      cheapest quarter                      2                      3 most expensive quarter 
                 0.863                  0.910                  0.928                  0.882 

The 90% interval goes from the prediction divided by 1.36 to the prediction times 1.36. In the test 89.5% of the houses were inside. The coverage is right on average, and not in every group: it ranges from 86% to 93% 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, 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:

Code
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 2,877 houses sold in King County, Washington, in April and May 2015 from 18,736 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 4.6.2; R Core Team, 2026) with the package FNN.

Results:

With k = 8 and weighted predictors, half of the predictions were within 11.2% of the price (RMSE of log10 price = 0.086), compared with 16.8% for linear regression (Table 1). A linear regression corrected by the mean residual of the 15 nearest houses had a median error of 12.5%. The 90% conformal intervals (predicted price divided or multiplied by 1.36) contained 89.5% of the prices.

Table 1

Prediction of House Prices in April and May 2015

Model RMSE (log10 price) Median error
GAM with a map 0.081 10.9%
kNN, weighted 0.086 11.2%
Random forest 0.086 10.6%
Regression + postal codes 0.089 11.8%
kNN, standardised 0.090 11.5%
Regression + kNN of its residuals 0.092 12.5%
Linear regression 0.120 16.8%

Note. N = 2,877. 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, random forest, support vector regression

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