可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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)