Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KNN in R: 'train and class have different lengths'?

Tags:

r

Here is my code:

train_points <- read.table("kaggle_train_points.txt", sep="\t")
train_labels <- read.table("kaggle_train_labels.txt", sep="\t")
test_points <- read.table("kaggle_test_points.txt", sep="\t")

#uses package 'class'
library(class)
knn(train_points, test_points, train_labels, k = 5);

dim(train_points) is 42000 x 784
dim(train_labels) is 42000 x 1

I don't see the issue, but I'm getting the error :

Error in knn(train_points, test_points, train_labels, k = 5) :
'train' and 'class' have different lengths.

What's the problem?

like image 784
Jon Avatar asked Apr 29 '13 10:04

Jon


4 Answers

I have recently encountered a very similar issue. I wanted to give only a single column as a predictor. In such cases, selecting a column, you have to remember about drop argument and set it to FALSE. The knn() function accepts only matrices or data frames as train and test arguments. Not vectors.

knn(train = trainSet[, 2, drop = FALSE], test = testSet[, 2, drop = FALSE], cl = trainSet$Direction, k = 5)

like image 38
crocodile Avatar answered Nov 06 '22 16:11

crocodile


Without access to the data, it's really hard to help. However, I suspect that train_labels should be a vector. So try

cl = train_labels[,1]
knn(train_points, test_points, cl, k = 5)

Also double check:

dim(train_points)
dim(test_points)
length(cl)
like image 197
csgillespie Avatar answered Nov 06 '22 17:11

csgillespie


I had the same issue in trying to apply knn on breast cancer diagnosis from wisconsin dataset I found that the issue was linked to the fact that cl argument need to be a vector factor (my mistake was to write cl=labels , I thought this was the vector to be predicted it was in fact a data frame of one column ) so the solution was to use the following syntax : knn (train, test,cl=labels$diagnosis,k=21) diagnosis was the header of the one column data frame labels and it worked well Hope this help !

like image 4
Axel Ullern Avatar answered Nov 06 '22 16:11

Axel Ullern


Try converting the data into a dataframe using as.dataframe(). I was having the same problem & afterwards it worked fine:

train_pointsdf <- as.data.frame(train_points)
train_labelsdf <- as.data.frame(train_labels)
test_pointsdf <- as.data.frame(test_points)
like image 3
T.j. Gray Avatar answered Nov 06 '22 17:11

T.j. Gray