R:缺少数据会导致 XGBoost / sparse.model.matrix 出错

R: Missing data causes error with XGBoost / sparse.model.matrix

据我了解,XGB 应该有处理缺失数据的好处,但是,每当我测试添加了一些 NA 的波士顿住房集时,我得到错误:

The length of labels must equal to the number of rows in the input data

我运行的密码是

trainm <- sparse.model.matrix(class ~ ., data = train)
train_label <- train[,"class"]
train_matrix <- xgb.DMatrix(data = as.matrix(trainm) label=train_label)

当我不添加 NA 时一切正常。我很确定问题是 NA 从稀疏矩阵中删除导致混淆,但我不确定如何解决它。

我的密码是here.

任何对我有帮助的反馈都将不胜感激。

您需要在构建稀疏模型矩阵时对处理 NA 采取纠正措施。休息,你的 code/data 没有问题。这是修改后的代码:

options(na.action='na.pass')
trainm <- sparse.model.matrix(class ~ ., data = train)
train_label <- train$class
train_matrix <- xgb.DMatrix(data = trainm, label=train$class)