简体   繁体   中英

Q: KNN in R — strange behavior

Does anyone know why the below KNN R code gives different predictions for different seeds? This is strange as K<-5, and thus the majority is well defined. In addition, the floating numbers are large -- so no precision of data problem arises (like in this post ).

library(class)

set.seed(642002713)
m = 20
n = 1000
from = -(2^30)
to = -(from)
train = matrix(runif(m*n, from, to), nrow=m, ncol=n)
trainLabels = sample.int(2, size = m, replace=T)-1
test = matrix(runif(n, from, to), nrow=1)

K <- 5

seed <- 544336746
set.seed(seed)
pred_1 <- knn(train=train, test=test, cl = trainLabels, k=K)
message("predicted: ", pred_1, ", seed: ", seed)
#predicted: 0, seed: 544336746

seed <- 621513172 
set.seed(seed)
pred_2 <- knn(train=train, test=test, cl = trainLabels, k=K)
message("predicted: ", pred_2, ", seed: ", seed)
#predicted: 1, seed: 621513172

A manual check:

euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))
result = vector(mode="numeric", length=nrow(train))
for(i in 1:nrow(train)) {
  result[i] <- euc.dist(train[i,], test)
}
a <- data.frame(result, trainLabels)
names(a) = c("RSSE", "labels")
b <- a[with(a, order(sums, decreasing =T)), ]
headK <- head(b, K)
message("Manual predicted K: ", paste(K," class:", names(which.max(table(headK[,2])))))
#Manual predicted K: 5  class: 1

would give the prediction 1, with the Top K(=5) RSSE:

RSSE             labels
28479706980      1
28472893026      0
28063242772      1
27966740954      1
27927401005      1

so, majority is well defined + no problem of small float difference in RSSE.

When I scale and center the data - including the test set! , then I get both predictions 0.

My preprocessing:

sc<-function(x){(x-mean(x))/sd(x)}
train<-apply(train,1,sc)
train<-t(train)
test<-apply(test,1,sc)
test<-t(test)

and obtain:

> seed <- 544336746
> pred_1 <- knn(train=train, test=test, cl = trainLabels, k=K)
> message("predicted: ", pred_1, ", seed: ", seed)
predicted: 0, seed: 544336746

> seed <- 621513172
> pred_2 <- knn(train=train, test=test, cl = trainLabels, k=K)
> message("predicted: ", pred_2, ", seed: ", seed)
predicted: 0, seed: 621513172

manual check that I edited to this form

a <- data.frame(result, trainLabels)
names(a) = c("RSSE", "labels")
b <- a[with(a, order(a$RSSE)), ]
headK <- head(b, K)
message("Manual predicted K: ", paste(K," class:", names(which.max(table(headK[,2])))))
Manual predicted K: 5  class: 0

and results:

       RSSE labels
3  43.48199      0
17 43.61283      1
7  43.63948      1
8  43.69730      0
19 43.78931      0    
6  43.88009      0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM