Skip to content

Instantly share code, notes, and snippets.

@xccds
Created May 6, 2012 09:52
Show Gist options
  • Save xccds/2621347 to your computer and use it in GitHub Desktop.
Save xccds/2621347 to your computer and use it in GitHub Desktop.
library(class)
vknn = function(v,data,cl,k){
# 分割原始数据
grps = cut(1:nrow(data),v,labels=FALSE)[sample(1:nrow(data))]
# 对每份数据分别运行KNN函数
pred = lapply(1:v,function(i,data,cl,k){
omit = which(grps == i)
pcl = knn(data[-omit,],data[omit,],cl[-omit],k=k)
},data,cl,k)
# 整合预测结果
wh = unlist(pred)
table(wh,cl[order(grps)])
}
vknn(5,iris[1:4],iris$Species,5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment