代码之家  ›  专栏  ›  技术社区  ›  Santhosh Kothapally

predict()error:如果训练数据中存在一个变量,而预测数据中不存在,我该怎么办?

  •  -2
  • Santhosh Kothapally  · 技术社区  · 9 年前

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

    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”

    我得到了上面的错误。我想我得到错误的原因是我的测试数据集中的功能数量与训练数据集不匹配。

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

    1 回复  |  直到 9 年前
        1
  •  1
  •   Zheyuan Li    9 年前

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

    test$generationMethod <- 0
    

    您必须有变量 generationMethod 在您的 test ! 它已用于构建模型,因此需要 predict 当你做出预测时。正如你所说,你没有这个变量 测验 ,使用上面的命令在 测验 .由于此列均为0,因此对预测没有影响;但是,它将帮助您通过 预测 .

    或者,您可以考虑删除变量 生成方法 从您的模型开发中。尝试:

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