当使用SVM模型进行预测时,R返回因子(0)

时间:2017-05-16 13:50:44

标签: r machine-learning svm predict

我的问题与this thread完全相同,但是,由于这似乎还没有令人满意的答案,我认为再次提出可重复的代码仍然是合适的。

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

我已检查过测试数据框是否包含所有列,并且这些必需列中不存在NA。请给我一些想法继续下去。谢谢!

1 个答案:

答案 0 :(得分:0)

这似乎是e1071 predict.svm函数中的一个怪癖的结果。虽然您的测试数据没有模型中变量的缺失值。每个点都缺少值。

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

您可以通过消除不需要的变量来解决此问题。

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