SVM predict on dataframe with different factor levels

懵懂的女人 提交于 2019-12-02 16:29:26

问题


I have a dataframe I want to make predictions on from an SVM, but the dataframe doesn't have all of the levels that the original training dataframe did. Is there an easy way around this?

Here's a quick example

library(e1071)
df = data.frame(y = c(rep(1:3, each = 3)), x = rep(c("A", "B", "C"), each = 3))

m1 = svm(y ~ x, df)
df2 = data.frame(x = "B")

predict(m1, df2)
Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : 
  contrasts can be applied only to factors with 2 or more levels

回答1:


Just be sure to specify the levels in df2

library(e1071)
df = data.frame(y = c(rep(1:3, each = 3)), x = rep(c("A", "B", "C"), each = 3))

m1 = svm(y ~ x, df)
df2 = data.frame(x = factor("B",levels = c("A","B","C")))

predict(m1, df2)


来源:https://stackoverflow.com/questions/46991570/svm-predict-on-dataframe-with-different-factor-levels

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!