O'Reilly logo

R Data Analysis Cookbook - Second Edition by Kuntal Ganguly

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using a convenience function to run KNN

We would normally run knn and compute the RMS error. The following convenience function can help:

rdacb.knn.reg <- function (trg_predictors, val_predictors,  trg_target, val_target, k) { 
  library(FNN) 
  res <- knn.reg(trg_predictors, val_predictors, trg_target,      k, algorithm = "brute") 
  errors <- res$pred - val_target 
  rmse <- sqrt(sum(errors * errors)/nrow(val_predictors)) 
  cat(paste("RMSE for k=", toString(k), ":", sep = ""), rmse,      "\n") 
  rmse 
} 

With the preceding function, we can execute the following after reading the data, creating dummies, rescaling the predictors, and partitioning, that is, executing steps 1 through 4 of the main recipe:

> set.seed(1000) > t.idx <- createDataPartition(educ$expense, p ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required