r语言 - Xgboost:使用单次测试观察?



我想使用xgboost对R拟合一个时间序列模型,并且我只想使用最后的观测值来测试模型(在滚动窗口预测中,总共会有更多的观测值)。但是当我在测试数据中只包含一个值时,我得到了错误: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

这里有另一篇文章解决了类似的问题,但是它指的是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

最新更新