Investigation: The beauty of kNN

Investigation: The beauty of kNN#

Nearest-neighbor methods turn a representation and a distance into a prediction. Scaling, irrelevant features, class imbalance, and the choice of k affect what nearby means. The representation must preserve distinctions relevant to the question.

Question. Tune k on training-side folds of Iris, fitting scaling within each fold, then evaluate the chosen rule on held-out flowers.

Before running: write the result you expect and what would challenge it. Data are simulated unless explicitly identified otherwise.

# Open this notebook from book/notebooks (or book/exercises).
course_path <- if (file.exists("../R/course.R")) "../R/course.R" else "book/R/course.R"
stopifnot(file.exists(course_path))
source(course_path)
set.seed(432)
d <- iris
s <- split_groups(seq_len(nrow(d)),seed=432)
train <- d[s$train,]; test <- d[s$test,]
features <- c("Sepal.Length","Sepal.Width","Petal.Length","Petal.Width")
fold <- group_folds(seq_len(nrow(train)),k=5)
candidates <- c(1,3,5,9,15)
cv_error <- sapply(candidates,function(k) {
  errors <- rep(NA_real_,nrow(train))
  for(f in unique(fold)) {
    a <- which(fold!=f); v <- which(fold==f)
    scaler <- fit_scaler(train[a,features])
    pred <- class::knn(apply_scaler(train[a,features],scaler),apply_scaler(train[v,features],scaler),train$Species[a],k=k)
    errors[v] <- as.numeric(pred!=train$Species[v])
  }
  mean(errors)
})
data.frame(k=candidates,validation_error=cv_error)
best_k <- candidates[which.min(cv_error)]
A data.frame: 5 × 2
kvalidation_error
<dbl><dbl>
10.02500000
30.02500000
50.03333333
90.02500000
150.04166667
scaler <- fit_scaler(train[features])
pred <- class::knn(apply_scaler(train[features],scaler),apply_scaler(test[features],scaler),train$Species,k=best_k)
table(predicted=pred,observed=test$Species)
c(selected_k=best_k,test_error=mean(pred!=test$Species))
stopifnot(length(intersect(s$train,s$test))==0)
            observed
predicted    setosa versicolor virginica
  setosa         10          0         0
  versicolor      0         10         1
  virginica       0          2         7
selected_k
3
test_error
0.1

Representation and retrieval#

Changing measurement units changes unscaled distances. Scaling should be fitted on analysis rows and reused on assessment rows. In a text-retrieval extension, use documented frozen embeddings and an independently judged set of relevant documents. Compare nearest neighbors with a keyword baseline; record the embedding model/version and do not assume geometric proximity establishes scientific relevance. No live API is required for the core lab.

Interpret and verify#

Compare scaled and unscaled distances using training-side evidence. Explain how a semantically similar text can still be irrelevant to a retrieval question.

Failure to consider: Scaling the entire dataset before splitting leaks evaluation information. Repeatedly selecting k on the test set turns that set into validation data.

Report the target, the numerical result with its units, the relevant uncertainty, and one limitation. Distinguish what is established by the simulation from what would require real data.

AI audit: critique the saved faulty claim in the companion exercise before using any live assistant. If you use AI, record the relevant suggestion, your independent check, and the final decision.

Use classifier metrics from the preceding lessons; the next chapter formalizes the complete resampling procedure.

sessionInfo()
R version 4.2.1 (2022-06-23)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS 15.7.7

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRlapack.dylib

locale:
[1] C.UTF-8/C.UTF-8/C.UTF-8/C/C.UTF-8/C.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
 [1] class_7.3-20        fansi_1.0.3         crayon_1.5.1       
 [4] digest_0.6.29       utf8_1.2.2          IRdisplay_1.1      
 [7] repr_1.1.4          lifecycle_1.0.1     jsonlite_1.8.0     
[10] evaluate_0.15       pillar_1.8.0        rlang_1.0.6        
[13] cli_3.3.0           uuid_1.1-0          vctrs_0.4.1        
[16] IRkernel_1.3.0.9000 tools_4.2.1         glue_1.6.2         
[19] fastmap_1.1.0       compiler_4.2.1      base64enc_0.1-3    
[22] pbdZMQ_0.3-7        htmltools_0.5.3    

Attribution#

Notebook authored by Patience Stevens and edited by Amy Sentis and Fiona Horner.

Revised investigation: 2026 course revision. Original authorship is retained; examples and explanatory text have been updated.