具有多个特征的 XGBoost predict() 错误

XGBoost predict() error with multiple features

我看不出 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,]))

转置我的测试集不会 return 错误,但是这是错误地使用了预测变量,因为

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

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

所以我的问题是,如何使用与构建模型相同的特征使用 XGBoost 进行预测?在此示例中,我构建了一个具有三个特征(lag1、lag2 和 lag3)的模型来预测响应 return。但是当尝试使用 predict 进行预测时,该函数的行为就好像它只会使用一个特征,如果它使用多个值,就像我转置测试集时一样,它是如何利用这些值的是未知的.

你真的很亲密...留在我身边...

> 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 :)

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