来自数据帧的 XGB 稀疏矩阵

XGB sparse matrix from a dataframe

正在阅读XGB vignette

We are using the train data. As explained above, both data and label are stored in a list.

In a sparse matrix, cells containing 0 are not stored in memory. Therefore, in a dataset mainly made of 0, memory size is reduced. It is very usual to have such dataset.

之后的小插图也会告诉您如何使用密集矩阵。

我有一个从文本数据派生的数据框,因此它非常稀疏,因为大多数值为零。我一直在将数据帧传递给 XGB,并且 运行 需要很长时间,但也许这是预期的。我正在对 1M 观察值、92 个变量进行训练,并使用带有 15 个处理器的托管 RStudio 64gb(当我在终端中监控时,我看到 XGB 也在使用所有可用的处理器)。

我的问题是,我是否必须对我的数据框进行某种转换以使其成为稀疏矩阵?

library(tidyverse)
library(caret)
library(xgboost)

## xgboost
# set up parameter search
xgb_grid = expand.grid(  #  stopped using differing permutations of parameters because training was taking so long
  nrounds = 150,
  eta = 0.3, # default 0.3; previously verified 0.3 was best model with 100k sample
  max_depth = 6, # default 6; previously verified 6 was best model with 100k sample
  gamma = 0, #default = 0
  colsample_bytree = 1, # default = 1
  min_child_weight = 1, # default = 1
  subsample = 1 # default = 1
)

# fit a xgboost model
print("begin xgb")
mod_xgb <- train(
  cluster ~.,
  data = select(training_data, -id),
  method = "xgbTree",
  trControl = train_control,
  na.action = na.pass,
  tuneGrid = xgb_grid,
  metric = "Kappa"
)

> str(training_data)
'data.frame':   1000000 obs. of  92 variables:
 $ violat          : num  0 0 0 0 0 0 0 0 0 0 ...
 $ found           : num  0 0 0 0 0 0 0 0 0 0 ...
 $ person          : num  0 0 0 0 0 0 0 0 0 0 ...
 $ theft           : num  0 0 0 1 0 0 0 0 0 0 ...
 $ theft_from      : num  0 0 0 0 0 0 0 0 0 0 ...

我问是因为我想知道我是否以某种方式将我的数据框 training_data 更改为 XGB 的稀疏矩阵,也许模型会训练得更快?会吗?

如何制作 training_data 稀疏矩阵以传递给 XGBoost?

Matrix 包具有以下创建稀疏矩阵的函数 sparse.model.matrix()。如果您在创建稀疏矩阵之前从数据中删除 NA 以确保在输入 xgboost 函数时因变量 y 与稀疏矩阵的长度相同,这可能会有所帮助。

我还倾向于记录我的训练数据中的因子水平,以便在对未见过的测试数据集进行预测时,我可以确保测试数据与训练数据具有相同的因子水平。这可确保测试数据矩阵与训练矩阵具有相同的维度。

来自 mtcars 的示例:

f<-mpg~hp+as.factor(cyl)
trainMatrix<-sparse.model.matrix(f,mtcars)