【问题标题】:predict() error: what can I do if one variable exists in training data but not in prediction data?predict() 错误:如果一个变量存在于训练数据中但不存在于预测数据中,我该怎么办?
【发布时间】:2016-10-04 17:02:32
【问题描述】:

我有一个包含以下变量的训练数据集

str(PairsTrain)

'data.frame':   1495698 obs. of  4 variables:  
            $ itemID_1        : int  1 4 8 12 15 19 20 20 22 26 ...  
            $ itemID_2        : int  4112648 1223296 2161930 5637025  113701         
            $ isDuplicate     : int  1 0 1 0 0 0 0 0 1 0 ...  
            $ generationMethod: int  1 1 1 1 1 1 1 1 1 1 ... 

我使用逻辑回归glm()函数从这个数据集中学习

mod1 <- glm(isDuplicate ~., data = PairsTrain, family = binomial)

下面是我的测试数据集的结构:

str(Test)

'data.frame':   1044196 obs. of  3 variables:  
         $ id      : int  0 1 2 3 4 5 6 7 8 9 ...  
         $ itemID_1: int  5 5 6 11 23 23 30 31 36 47 ...  
         $ itemID_2: int  4670875 787210 1705280 3020777 5316130 3394969 2922567 

我正在尝试对我的测试数据集进行预测,如下所示

PredTest <- predict(mod1, newdata = Test, type = "response")

eval(expr, envir, enclos) 中的错误:找不到对象“generationMethod”

我收到上述错误。我在想我得到错误的原因是我的测试数据集中的特征数量与训练数据集不匹配。

我不确定我是否正确,我被困在这里,不知道如何处理这种情况。

【问题讨论】:

  • 您好哲元我在测试数据集中没有generationMethod。 “id”、“itemID_1”、“itemID_2”是测试数据集中仅有的特征。

标签: r regression glm lm predict


【解决方案1】:

好的,这就是你所需要的:

test$generationMethod <- 0

您的test 中必须有变量generationMethod!它已用于构建模型,因此在您进行预测时predict 需要它。如您所说,test 中没有此变量,请使用上述方法在test 中创建此类变量。这对进行预测没有影响,因为该列全为 0;但是,它将帮助您通过predict 的变量检查。

或者,您可以考虑从模型开发中删除变量 generationMethod。试试:

mod2 <- glm(isDuplicate ~ itemID_1 + itemID_2, data = PairsTrain,
            family = binomial)

【讨论】:

  • 我尝试在我的测试数据集中将 0 分配给 genrationMethod 和 isDuplicate 并运行预测函数,它没有抛出任何错误,我还尝试使用您提到的 mod2 模型进行预测,它也有效。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2013-01-05
  • 2021-02-28
  • 1970-01-01
  • 2017-08-29
  • 2019-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多