逻辑回归错误:测试数据

时间:2018-06-09 01:13:09

标签: r error-handling logistic-regression prediction categorical-data

当我试图使用R中的Logistic回归模型进行预测时,我遇到以下错误:

  

错误

Error:

  

pred< - predict(model,newdata = test)
  model.frame.default中的错误(Terms,newdata,na.action = na.action,xlev = object $ xlevels):     factor admission_type_id有新的等级8

根据我的理解,该列的测试数据" admission_type_id"比较训练数据有新的水平。 我尝试查看唯一值,我看到Train数据具有测试数据的所有值。

  

独特(火车$ admission_type_id)
  1 1 3 2 6 5 8 4
  级别:1 2 3 4 5 6 7 8

     

独特(测试$ admission_type_id)
  1 6 1 2 3 5 8
  级别:1 2 3 4 5 6 7 8

如果有人可以帮助我理解这个问题,那将会很有帮助。 谢谢。

1 个答案:

答案 0 :(得分:0)

问题在于您为一个/多个预测变量设定了不同的因子水平:

例如,我使用的是mtcars数据。它也应该出现在你的会话中。(阅读我在代码之间的评论)

mtcars_train <- mtcars[mtcars$cyl %in% c(4,6),] #Consider this as train data
mtcars_train$cyl <- as.factor(mtcars_train$cyl) #Changing cyl to factor, here cyl values are 4 and 6 only, notice there is no 8

mtcars_orig <- mtcars #Taking the entire data which contain cyl values as 4,6 and 8
mtcars_orig$cyl <- as.factor(mtcars_orig$cyl) #Converting to factors, here again we can see that levels(mtcars_orign$cyl) is 4,6 and 8

lm1 <- lm(am ~ mpg + cyl + hp , data=mtcars_train) # Building the model
predict(lm1, newdata=mtcars_orig) #Now if you try to predict you will receive the error of having missing classes

lm1$xlevels[["cyl"]] <- union(lm1$xlevels[["cyl"]], levels(mtcars_orig$cyl)) #You can fix this here by running this code, it will append the levels to your original lm1 model here

如果运行预测,在运行最后一步后,您将获得结果。

predict(lm1, newdata=mtcars_orig)

我的建议是,乘坐一个火车样本,这是一个非常好的代表你的整个数据集,你的火车和测试应该匹配,如果因素水平不匹配,这个错误总会来。

相关问题