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

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

Here is my code:

train_points 

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?

回答1:

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) 


回答2:

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)



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!