1

I want to try KNN algorithm on a dataset using R.I was able to perform KNN , but I want to check the accuracy of the model. I tried to do the same with the help of confusionMatrix function,but it shows the following error.

Error in confusionMatrix.default(k, knn_test$driver_tset): 
  the data cannot have more levels than the reference

The code is given below.

knn_data <- read.csv("Path/Data_without_Missing_values.csv")
knn_test<-read.csv("Path/Test.csv")
cl <- factor(knn_data[,4])
library('class') # required for knn()
k <- knn(knn_data[,c(1,2,3)], knn_test[,c(1,2,3)], cl)
library('caret') # required for confusionMatrix()
confusionMatrix(k,knn_test$driver_tset)

driver_tset is the column which I have to test. When I checked the levels of k and knn_test$driver_tset,it displays the following:

levels(k)
# [1] "7"  "8"  "9"  "10" "11" "12" "13" "14" "17"

levels(knn_test$driver_tset)
# NULL`

So its clear that levels are different, but I'm not getting the significance of levels here. Also,how do I fix this?

C8H10N4O2
  • 18,312
  • 8
  • 98
  • 134
Nithin Das
  • 364
  • 1
  • 5
  • 14
  • are you using `caret`? – C8H10N4O2 Nov 19 '15 at 13:54
  • 1
    Your example is not reproducible, but in general: the arguments to `caret::confusionMatrix()` are the predicted classes and the reference (actual) classes. Your syntax is incorrect with respect to the first argument. – C8H10N4O2 Nov 19 '15 at 13:59
  • @C8H10N4O2: Yes I'm using the `caret` package.Even i have used the same argument here for `confusionMatrix`. `k` has the predicted values and `knn_test$driver_tset` has reference values – Nithin Das Nov 20 '15 at 12:09
  • You are going to confuse everyone if you use `k` for predicted values instead of the algorithm constant for `knn()`. – C8H10N4O2 Nov 20 '15 at 13:12
  • Also, it appears that `knn_test$driver_tset` is **not a factor**, which is probably why your `confusionMatrix` isn't working. But we can't help you because you haven't provided a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – C8H10N4O2 Nov 20 '15 at 13:21

0 Answers0