【问题标题】:Get data into a format for xgboost in R?将数据转换为 R 中 xgboost 的格式?
【发布时间】:2017-04-15 08:27:16
【问题描述】:

有人有一个很好解释的例子,将数据转换成 R 中 xgboost 可以使用的格式吗?

get started doc 对我没有帮助。数据(agaricus.trainagaricus.test)已经采用特殊格式(dgCMatrix):

> str(agaricus.train)
List of 2
 $ data :Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
  .. ..@ i       : int [1:143286] 2 6 8 11 18 20 21 24 28 32 ...
  .. ..@ p       : int [1:127] 0 369 372 3306 5845 6489 6513 8380 8384 10991 ...
  .. ..@ Dim     : int [1:2] 6513 126
  .. ..@ Dimnames:List of 2
  .. .. ..$ : NULL
  .. .. ..$ : chr [1:126] "cap-shape=bell" "cap-shape=conical" "cap-shape=convex" "cap-shape=flat" ...
  .. ..@ x       : num [1:143286] 1 1 1 1 1 1 1 1 1 1 ...
  .. ..@ factors : list()
 $ label: num [1:6513] 1 0 0 1 0 0 0 1 0 0 ...

我看到 this example code 使用 sparse.model.matrix,但我仍然很难将相当简单的数据组合成 xgboost 需要的格式。

例如,假设我有两个数据框:wordslabels

words 数据框有sentence_idword_id,每个句子有一个或多个单词。

data_label 数据框有一个 sentence_id 和标签(例如,0 或 1 用于二进制分类任务)。

如何将这些数据转换为一种格式来预测句子的标签?

我可以拆分训练和测试。

编辑:words和data_label的最简单版本:

words <- data.frame(sentence_id=c(1, 1, 2, 2, 2),
                    word_id=c(1, 2, 1, 3, 4))
data_label <- data.frame(sentence_id=c(1, 2), label=c(0, 1))

【问题讨论】:

  • 需要minimal reproducible example 才能开始编码。
  • 我猜你知道如何将你的数据框转换为对 xgboost 至关重要的矩阵格式,并且你所有的数据都是数字格式。您能否发布一小部分数据和您正在使用的代码,否则不清楚可能是什么问题。
  • @cousin_pete 我在上面放了 word 和 data_label 的代码。
  • @42- 我在上面放了 word 和 data_label 的代码。
  • @cousin_pete 我们不要假设我知道如何转换为矩阵格式。有几种不同的转换函数,不知道xgboost要哪个。

标签: r xgboost


【解决方案1】:

xgb.DMatrix 的输入可以是密集的matrix,也可以是稀疏的dgCMatrix,或者以 LibSVM 格式存储在文件中的稀疏数据。由于您正在处理文本数据,因此稀疏表示将是最合适的。 下面是如何将示例数据转换为 dgCMatrix 的示例。 在这里,我假设一个完美的情况,从 1 开始的连续整数句 ID 集在两个表中都是相同的。如果在实践中并非如此,则需要您自己处理更多数据。

library(Matrix)

words <- data.frame(sentence_id=c(1, 1, 2, 2, 2),
                    word_id=c(1, 2, 1, 3, 4))
data_label <- data.frame(sentence_id=c(1, 2), label=c(0, 1))

# quick check of assumptions about sentence_id
stopifnot(min(words$sentence_id) == 1 &&
          max(words$sentence_id) == length(unique(words$sentence_id)))

# sparse matrix construction from "triplet" data
# (rows are sentences, columns are words, and the value is always 1)
smat <- sparseMatrix(i = words$sentence_id, j = words$word_id, x = 1)

# make sure sentence_id are in proper order in data_label:
data_label <- data_label[order(data_label$sentence_id)]
stopifnot(all.equal(data_label$sentence_id, 1:nrow(smat)))

xmat <- xgb.DMatrix(smat, label = data_label$label)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 2017-12-27
    • 2021-11-16
    • 2013-10-22
    • 1970-01-01
    • 2021-09-28
    • 2019-04-13
    相关资源
    最近更新 更多