user2991421
user2991421

Reputation: 417

Error in 1:nrow(newdata) : argument of length 0 while using SVM predict

I'm trying to predict A values based upon model trained by svm. This is how my train and test data looks like:

A     B    C     D
r00  r01  r02   r03
...  ...  ...   ...

Code Snippet is given below:

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,]])
}

I'm getting the following error for the svm.predict line and am not really sure why?

Error in 1:nrow(newdata) : argument of length 0

Structure for train data:

structure(list(A = structure(6L, .Label = c("'1'", 
"'2'", "'3'" ), class = "factor"), B =  structure(15L, .Label = c(...)...)

Structure for test data:

structure(list(A = structure(2L, .Label = c("'1'", 
"'2'", "'3'" ), class = "factor"), B =  structure(17L, .Label = c(...)...)

Upvotes: 0

Views: 14649

Answers (1)

Aur&#232;le
Aur&#232;le

Reputation: 12819

I suspect featvecs has only one column, so featvecs[f,] is of length 1.

Then test[,featvecs[f,]] outputs a vector instead of the expected data.frame (See the difference between mtcars[, "mpg"] and mtcars[, "mpg", drop = FALSE]), and nrow() applied to a vector outputs NULL: 1:nrow(newdata) in the source code of svm.predict() gives 1:NULL that causes your error.

Try adding drop = FALSE to test[,featvecs[f,], drop = FALSE] so that you get a data.frame.

Upvotes: 1

Related Questions