【问题标题】:Define mlr3 task using data from a database (different tables)?使用数据库中的数据(不同的表)定义 mlr3 任务?
【发布时间】:2021-02-13 08:33:55
【问题描述】:

这是一个新手问题。 如何定义使用来自(sqlite)数据库的数据的(分类)tskmlr3db example 似乎首先从内存中写入数据。就我而言,数据已经在数据库中。更大的问题可能是,目标数据和特征在不同的表中。

我尝试了什么:

con <- DBI::dbConnect(RSQLite::SQLite(), dbname = "my_data.db")
my_features <- dplyr::tbl(con, "my_features")
my_target <- dplyr::tbl(con, "my_targets")
task <- mlr3::TaskClassif$new("my_task", backend=my_features, target="???")

然后我不知道如何指定target 参数。

也许一个解决方案是在数据库中创建一个连接特征和目标的视图?

【问题讨论】:

  • 如果这里没有提供解决方案,请随时在mlr-org/mlr3db 提出问题。

标签: r mlr3


【解决方案1】:

可以将数据拆分为 (1) 多个表或 (2) 多个数据库。在您的情况下,看起来数据只是拆分为多个表,但您可以使用相同的 DBI 连接来访问它们。

您只需要一个键列来连接这两个表。在以下示例中,我使用一个简单的整数键列和一个 inner_join() 将两个表合并为一个新表,但这在某种程度上取决于您的数据库方案。

library(mlr3)
library(mlr3db)

# base data set
data = iris
data$row_id = 1:nrow(data)

# create data base with two tables, split data into features and target and
# keep key column `row_id` in both tables
path = tempfile()
con = DBI::dbConnect(RSQLite::SQLite(), dbname = path)
DBI::dbWriteTable(con, "features", subset(data, select = - Species))
DBI::dbWriteTable(con, "target", subset(data, select = c(row_id, Species)))
DBI::dbDisconnect(con)

# re-open table
con = DBI::dbConnect(RSQLite::SQLite(), dbname = path)

# access tables with dplyr
tbl_features = dplyr::tbl(con, "features")
tbl_target = dplyr::tbl(con, "target")

# join tables with an inner_join
tbl_joined = dplyr::inner_join(tbl_features, tbl_target, by = "row_id")

# convert to a backend and create the task
backend = as_data_backend(tbl_joined, primary_key = "row_id")
mlr3::TaskClassif$new("my_task", backend, target = "Species")

【讨论】:

    猜你喜欢
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 2018-08-21
    • 2015-11-17
    相关资源
    最近更新 更多