在KNN算法中传导时的异常"(list) object cannot be coerced to type 'double'"错误



我正在R上进行KNN算法。我有三个数据集。我一直在研究我的代码,这是我所拥有的:

library(stats)
library(class)
#load up train and testing files
train1<-read.table("train1.txt",header=FALSE) 
test1<-read.table("test1.txt",header=FALSE)
#convert inputs into matrix
train = matrix(train1, byrow = T, ncol=3)
test = matrix(test1, byrow = T, ncol=3)
#load the classes in the training data
cl1a<-read.table("classes1.txt",header = FALSE)
clas=matrix(cl1a,byrow=T,ncol=1)
#set k 
kk = 2
#run knn
kn1 = knn(train, test, clas, k=kk, prob=TRUE)

运行最后一行后,我收到错误消息:

knn(train, test, clas, k = kk, prob = TRUE) 中的错误: (列表)对象不能强制键入"double"

我在其他地方读到这可以通过将表转换为矩阵来修复,但我在我的代码中修复了这一点,如您所见。

任何帮助不胜感激!

您需要按照我在上面的评论中的建议使用as.matrix。原因如下:

str(matrix(iris,byrow=T,ncol=5))

如您所见,这将生成一个列表。

List of 5
 $ : num [1:150] 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ : num [1:150] 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ : num [1:150] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ : num [1:150] 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
 - attr(*, "dim")= int [1:2] 1 5

另一方面,as.matrix产生矩阵。现在为什么会出错呢??knn我们可以看到它接受矩阵或数据帧:

火车
训练集事例的矩阵或数据帧。 测试
测试集用例的矩阵或数据框。 向量将被解释为单个案例的行向量

这就解释了为什么会出现错误:

knn(train, test, clas, k = kk, prob = TRUE) 中的错误:(列表)对象不能强制键入"double"

安全的做法是使用as.data.frameas.matrix

相关内容

最新更新