Xgboost:使用单次测试观察?

Xgboost: using single test observation?

我想使用 R 的 xgboost 拟合时间序列模型,我只想使用最后一次观察来测试模型(在滚动 window 预测中,总共会有更多)。但是当我在测试数据中只包含一个值时,我得到了错误:Error in xgb.DMatrix(data = X[n, ], label = y[n]) : xgb.DMatrix does not support construction from double。是否可以这样做,或者我至少需要 2 个测试点?

可重现的例子:

library(xgboost)
n = 1000
X = cbind(runif(n,0,20), runif(n,0,20))
y = X %*% c(2,3) + rnorm(n,0,0.1)

train = xgb.DMatrix(data  = X[-n,],
                    label = y[-n])

test = xgb.DMatrix(data   = X[n,],
                    label = y[n]) # error here, y[.] has 1 value

test2 = xgb.DMatrix(data   = X[(n-1):n,],
                    label = y[(n-1):n]) # works here, y[.] has 2 values

还有另一个 post here 解决了类似的问题,但它指的是 predict() 函数,而我指的是 test 数据进入 xgboost 的 watchlist 参数并使用例如提前停止。

这里的问题是 matrix 的子集操作与单个索引有关。看,

class(X[n, ])
# [1] "numeric"

class(X[n,, drop = FALSE])
#[1] "matrix" "array" 

使用X[n,, drop = FALSE]获取测试样本。

test = xgb.DMatrix(data   = X[n,, drop = FALSE], label = y[n])

xgb.model <- xgboost(data = train, nrounds = 15)
predict(xgb.model, test)
# [1] 62.28553