【问题标题】:Subsetting A Sparse Matrix in R在 R 中对稀疏矩阵进行子集化
【发布时间】:2018-06-15 20:13:50
【问题描述】:

我正在尝试将 dgCMatrix 类的稀疏矩阵子集化为训练和测试集,然后将这些矩阵转换为 xgb.DMatrix 对象以运行 eXtremeGradientBoosting。我运行以下代码(可重现):

a<-data.frame(replicate(3,sample(1:1000,1000,rep=TRUE)))
b <- cast_sparse(a,X1,X2,X3)
c<-data.frame(replicate(3,sample(1:1000,1000,rep=FALSE)))

sample <- sample.int(n = nrow(c), size = floor(.75*nrow(c)), replace = F)
y.train <- c$X1[sample]
y.test  <- c$X1[-sample]
x.train <- as.matrix(as.data.frame(as.matrix(b))[sample,])
x.test <- b[-sample,]
train.xgb <- xgb.DMatrix(x.train, label = y.train)
test.xgb <- xgb.DMatrix(x.test, label = y.test)

当我运行最后一行时,出现以下错误:

Error in setinfo.xgb.DMatrix(dmat, names(p), p[[1]]) : 
  The length of labels must equal to the number of rows in the input data

无论出于何种原因,x.test 矩阵的维度仅为2,而标签的长度为250。我无法弄清楚为什么会发生这种情况——有什么建议或想法可以解决这个问题吗?

【问题讨论】:

    标签: r


    【解决方案1】:

    鉴于拆分的目的是为了 xgboost,您可以做的不是拆分 dgCMatrix 而是使用 slice 函数拆分 xgb.DMatrix

    total = xgb.DMatrix(as.matrix(b), label = c$X1)
    train.xgb = xgboost::slice(total,sample)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-25
      • 2018-08-07
      • 2012-01-10
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多