checkKNN <- function()
{
set.seed(9999)
exampleDF <-
data.frame(x=matrix(runif(14),ncol=2),y=c('a','a','b','b','b','b','b'))
exampleDF$y <- as.factor(exampleDF$y)
exampleDF
# x.1 x.2 y
# 1 0.8608396 0.81819992 a
# 2 0.6602416 0.99815678 a
# 3 0.8004162 0.74069639 b
# 4 0.2076460 0.81829430 b
# 5 0.6894843 0.02551977 b
# 6 0.8448705 0.16775453 b
# 7 0.2197564 0.76513326 b
w <- pdist(exampleDF[,1:2],exampleDF[,1:2])
matrix(w@dist,ncol=7)
sqrt(sum((exampleDF[1,1:2]-exampleDF[2,1:2])^2))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] 0.0000000 0.2694885 0.0982740 0.65319359 0.8109898 0.6506414 0.64327574
# [2,] 0.2694885 0.0000000 0.2931464 0.48702493 0.9730765 0.8506796 0.49832430
# [3,] 0.0982740 0.2931464 0.0000000 0.59782773 0.7237288 0.5746639 0.58117378
# [4,] 0.6531936 0.4870249 0.5978277 0.00000000 0.9277174 0.9106356 0.05452301
# [5,] 0.8109898 0.9730765 0.7237288 0.92771739 0.0000000 0.2106552 0.87616915
# [6,] 0.6506414 0.8506796 0.5746639 0.91063559 0.2106552 0.0000000 0.86465538
# [7,] 0.6432757 0.4983243 0.5811738 0.05452301 0.8761691 0.8646554 0.00000000
# [1] 0.2694885
knnOut <- qeKNN(exampleDF,'y',k=2,holdout=NULL,scaleX=FALSE)
knnOut$whichClosest
# [,1] [,2]
# [1,] 1 3
# [2,] 2 1
# [3,] 3 1
# [4,] 4 7
# [5,] 5 6
# [6,] 6 5
# [7,] 7 4
knnOut$regests
# [1] 0.5 1.0 0.5 0.0 0.0 0.0 0.0
predict(knnOut,exampleDF[,1:2])
# $predClasses
# [1] "b" "a" "b" "b" "b" "b" "b"
# $probs
# [1] 0.5 1.0 0.5 0.0 0.0 0.0 0.0
predict(knnOut,exampleDF[,1:2],newxK=2)
# $predClasses
# [1] "b" "a" "b" "b" "b" "b" "b"
# $probs
# [1] 0.50 0.75 0.50 0.00 0.00 0.00 0.00
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.