【问题标题】:XGBoost predict() error with multiple features具有多个特征的 XGBoost predict() 错误
【发布时间】:2016-09-12 10:39:05
【问题描述】:

我看不到 XGBoost 的预测方法如何使用多个特征进行预测。

library(xgboost)
library(MASS)

sp500=data.frame(SP500)
label=sp500[,1]
lag1=sp500[-1,]
lag2=lag1[-1]
lag3=lag2[-1]
train=cbind(lag1,lag2,lag3)

model=xgboost(data=train[50:1000,],label=label[50:1000],
objective="reg:linear",booster="gbtree",nround=50)

predict(model,train[1,]) #returns an error, because it will not accept multiple columns



predict(model,t(train[1,]))

转置我的测试集不会返回错误,但是这是错误地使用了预测器,因为

predict(model,t(train[1:5,]))

只预测三个值而不是预期的五个

所以我的问题是,如何使用 XGBoost 使用与构建模型相同的功能进行预测?在此示例中,我构建了一个具有三个特征的模型,即 lag1、lag2 和 lag3,以预测响应返回。但是,当尝试使用predict 进行预测时,该函数的行为就好像它只使用一个特性,并且如果它使用多个值,比如我转置测试集时,它是如何利用这些值的。

【问题讨论】:

    标签: r predict xgboost


    【解决方案1】:

    你真的很亲近……和我在一起……

    > dim(train)
    [1] 2779    3
    

    好的,你训练了三个特征......这并不奇怪

    当你这样做时

    > predict(model,train[1,])
    Error in xgb.DMatrix(newdata) : 
      xgb.DMatrix: does not support to construct from  double
    

    xboost 正在寻找一个矩阵,你给了它一个向量,继续……

    ##this works 
    
    > predict(model,t(train[1,]))
    [1] -0.09167647
    > dim(t(train[1,]))
    [1] 1 3
    

    因为你转置了一个向量,它形成了一个 1 * 3 的矩阵

    但这搞砸了

    > predict(model, t(train[1:5,]))
    [1] -0.09167647  0.31090808 -0.10482860
    > dim(t(train[1:5,]))
    [1] 3 5
    ### Xgboost used the 3 rows and the first three columns only to predict
    ## the transpose didn't do the same thing here
    

    错误是因为转置(列)向量和转置矩阵是不同的东西

    你真正想要的是这个

    > predict(model,train[1:5,]) 
    [1] -0.09167647  0.31090808 -0.10482860 -0.02773660  0.33554882
    > dim(train[1:5,]) ## five rows of three columns
    [1] 5 3
    

    你必须非常小心,因为如果你没有给它足够的列xgboost 会像这样回收这些列...

     predict(model,train[1:5,1:2])
    [1] -0.07803667 -0.25330877  0.10844088 -0.04510367 -0.27979547
     ## only gave it two columns and it made a prediction :)
    

    只要确保你给它一个列数相同的矩阵,否则所有的地狱都会崩溃:)

    【讨论】:

    • 谢谢。正是我需要的
    猜你喜欢
    • 2017-01-15
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 2021-03-01
    • 2021-12-17
    • 1970-01-01
    • 2020-07-16
    • 2019-06-13
    相关资源
    最近更新 更多