KNN with R gives wrong answer 100% of the time

Started by
1 comment, last by taby 2 years ago

I have an R code that uses a k-nearest neighbour algorithm to emulate the XOR operation. I have only one problem – it's wrong 100% of the time. LOL Any ideas?

library(class)

# XOR problem
xor_dataframe <- data.frame(c(), c())
xor_dataframe = rbind(xor_dataframe, c(0, 0))
xor_dataframe = rbind(xor_dataframe, c(1, 0))
xor_dataframe = rbind(xor_dataframe, c(0, 1))
xor_dataframe = rbind(xor_dataframe, c(1, 1))

train_labels <- c(0, 1, 1, 0)

test_dataframe <- data.frame(c(), c())
test_dataframe = rbind(test_dataframe, c(0, 0))
test_dataframe = rbind(test_dataframe, c(1, 0))
test_dataframe = rbind(test_dataframe, c(0, 1))
test_dataframe = rbind(test_dataframe, c(1, 1))

classifier_knn <- knn(train = xor_dataframe,
                      test = test_dataframe,
                      cl = train_labels,
                      k = 3)

# This prints 1 0 0 1, instead of 0 1 1 0???
classifier_knn

#attributes(.Last.value)

Advertisement

It works where k = 1. My bad.

This topic is closed to new replies.

Advertisement