1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| library(class)
# tune parameter using cross-validation (CV)
k<-seq(1,15,1) # different k
cv.err<-NULL # cv error
for (ki in k){
knn.pred.cv<-knn.cv(admission[,1:2],admission[,3],k=ki)
cv.err<-c(cv.err, mean(knn.pred.cv!=admission[,3]))
}
plot(k,cv.err, main="CV error vs k")
# using the optimal parameter
knn.pred<-knn(admission[,1:2],admission[,1:2], admission[,3],k=k[which.min(cv.err)])
# plot
# different symbols represents true classifications
# different colors are predicted classifications
plot(admission[,1:2],col=knn.pred, pch=as.numeric(admission$CLASS),
xlab="GPA",ylab="GMAT",main="KNN")
|