我正在尝试基于通过SVM训练的模型来预测A值。这是我的训练和测试数据的外观:
A B C Dr00 r01 r02 r03... ... ... ...
代码片段如下:
featvecs = [“B”]
for (f in 1:nrow(featvecs)) { tuned <- svm(A ~., data = train[,c("A",featvecs[f,])], gamma = 0.01, cost = 10, kernel= "radial") svm.predict <- predict(tuned, test[,featvecs[f,]])}
我在svm.predict这一行得到了以下错误,但我不太确定为什么?
Error in 1:nrow(newdata) : argument of length 0
训练数据的结构:
structure(list(A = structure(6L, .Label = c("'1'", "'2'", "'3'" ), class = "factor"), B = structure(15L, .Label = c(...)...)
测试数据的结构:
structure(list(A = structure(2L, .Label = c("'1'", "'2'", "'3'" ), class = "factor"), B = structure(17L, .Label = c(...)...)
回答:
我怀疑featvecs
只有一个列,所以featvecs[f,]
的长度为1
。
然后test[,featvecs[f,]]
输出的是一个向量而不是预期的数据框(参见mtcars[, "mpg"]
和mtcars[, "mpg", drop = FALSE]
之间的区别),而nrow()
应用于向量时输出NULL
:1:nrow(newdata)
在svm.predict()
的源代码中会得到1:NULL
,这导致了你的错误。
尝试在test[,featvecs[f,], drop = FALSE]
中添加drop = FALSE
,这样你就能得到一个数据框。