Re: [R] knn - 10 fold cross validation

From: Liaw, Andy <>
Date: Wed 07 Jun 2006 - 11:52:18 EST

You might want to check out the function tune.knn() in the e1071 package.  


From: on behalf of Tim Smith Sent: Tue 6/6/2006 8:29 PM
Subject: [R] knn - 10 fold cross validation [Broadcast]


  I was trying to get the optimal 'k' for the knn. To do this I was using the following function :       

knn.cvk <- function(datmat, cl, k = 2:9) {

    datmatT <- (datmat)
  cv.err <- cl.pred <- c()   

  for (i in k) {
    newpre <- as.vector(, cl, k = i))     cl.pred <- cbind(cl.pred, newpre)
    cv.err <- c(cv.err, sum(cl != newpre))     

  k0 <- k[which.min(cv.err)]

  However, the function does a 'leave one out' cross validation. I checked the documentation to see if I could change this, but it appears that I cannot. Since I have large datasets, I would like to do 10 fold cross validation, instead of the 'leave one out'.    

  Is there some other function that I can use that will give me a 10 fold cross validation for KNN ?    

  many thanks.

        [[alternative HTML version deleted]] mailing list
PLEASE do read the posting guide!
<> mailing list PLEASE do read the posting guide! Received on Wed Jun 07 12:01:37 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Wed 07 Jun 2006 - 18:10:45 EST.

Mailing list information is available at Please read the posting guide before posting to the list.