问题
My question is quite the same with this thread, however, since that seems not to have an satisfying answer yet, I think it is still appropriate to ask again along with reproducible codes.
training <- read.csv("https://d396qusza40orc.cloudfront.net/predmachlearn/pml-training.csv")[,-1]
testing <- read.csv("https://d396qusza40orc.cloudfront.net/predmachlearn/pml-testing.csv")[,-1]
# Importing data
library(e1071)
# Load the required package for SVM
svm_model <- svm(classe ~ pitch_arm + pitch_forearm + pitch_dumbbell + pitch_belt +
roll_arm + roll_forearm + roll_dumbbell + roll_belt +
yaw_arm + yaw_forearm + yaw_dumbbell + yaw_belt,
data = training, scale = FALSE, cross = 10)
# Perform SVM analysis with default gamma and cost, and do 10-fold cross validation
predict(svm_model, testing)
# R returns factor(0) here
I have checked that testing data frame has all columns needed, and no NA exists in those required columns. Please give me some ideas to carry on. Thanks!
回答1:
This seems to be the result of a quirk in the e1071 predict.svm function. While your test data has no missing values for the variables in your model. Every point has missing values.
complete.cases(testing)
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[14] FALSE FALSE FALSE FALSE FALSE FALSE FALSE
You can work around this problem by eliminating the unneeded variables.
ModelVars = which(names(training) %in%
c("pitch_arm", "pitch_forearm", "pitch_dumbbell", "pitch_belt",
"roll_arm", "roll_forearm", "roll_dumbbell", "roll_belt",
"yaw_arm", "yaw_forearm", "yaw_dumbbell", "yaw_belt"))
test2 = testing[, ModelVars]
predict(svm_model, test2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
A A B A A A D B A A A C A A A A A A A A
Levels: A B C D E
来源:https://stackoverflow.com/questions/44003391/r-returns-factor0-when-predicting-with-a-svm-model