【问题标题】:Logistic regression error: New levels in categorical column in Test data逻辑回归错误:测试数据中分类列中的新级别
【发布时间】:2018-11-19 01:42:50
【问题描述】:

当我尝试在 R 中使用逻辑回归模型进行预测时,出现以下错误:

错误

pred model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) 中的错误: 因子 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

独特(test$admission_type_id)
1 6 1 2 3 5 8
等级:1 2 3 4 5 6 7 8

如果有人能帮助我理解这个问题,那将是非常有帮助的。 谢谢。

【问题讨论】:

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


    【解决方案1】:

    问题是一个/多个预测变量的因子水平不同:

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

    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 运行最后一步,你就会得到你的结果。

    predict(lm1, newdata=mtcars_orig)
    

    我的建议是,获取一个可以很好地代表整个数据集的训练样本,并且你的训练和测试应该匹配,如果因子水平不匹配,这个错误总是会出现。

    【讨论】:

    • 感谢您的回复伙伴。当我使用 unique() 时,我在训练和测试中看到相同的级别。那么为什么会出现这个问题呢?提前致谢。
    • @Hitin,请在您的问题中使用dput(head(dataframe,20)) 粘贴您的两个数据样本,如果没有看到您的数据,很难确定原因。
    • @Hitin,我可以看到差异,您在训练中缺少 7 分,在测试中缺少 4 分。似乎您在拆分之前已经创建了因子(因此即使您没有实际值也可以看到级别,因子很有趣,除非您重新编码它们,否则旧级别存在),这还不错想法,但似乎您的样本不好,或者此类/细分中的记录很少。
    猜你喜欢
    • 2021-09-28
    • 2019-03-05
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 2020-10-16
    相关资源
    最近更新 更多