You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中用mlr3hyperband对train.csv做XGBoost超参数优化

如何在mlr3hyperband中使用自定义数据集进行XGBoost调参?

你已经通过以下代码读取并处理了自定义数据集:

train = na.omit(read_csv('train.csv'))

但在使用mlr3hyperband调参时,无法直接将数据框传入tune()的task参数,也不能用tsk(train)加载自定义数据——这是因为mlr3要求task必须是mlr3标准的Task对象,而tsk()函数仅用于加载内置数据集。

解决步骤

  • 明确任务类型:确定你的任务是分类(预测离散标签)还是回归(预测连续值)。
  • 转换数据为Task对象:使用as_task_classif()(分类任务)或as_task_regr()(回归任务)将数据框转换为Task,必须指定目标列(即你要预测的列名)。

完整代码示例

假设你的任务是分类,目标列名为target,完整代码如下:

library(mlr3hyperband)
library(mlr3learners)
library(readr)

# 读取并处理数据
train = na.omit(read_csv('train.csv'))

# 将数据框转换为分类Task对象,替换target为你的实际目标列名
task = as_task_classif(train, target = "target", id = "my_custom_task")

# 定义带调参的XGBoost学习器
learner = lrn("classif.xgboost",
  nrounds           = to_tune(p_int(27, 243, tags = "budget")),
  eta               = to_tune(1e-4, 1, logscale = TRUE),
  max_depth         = to_tune(1, 20),
  colsample_bytree  = to_tune(1e-1, 1),
  colsample_bylevel = to_tune(1e-1, 1),
  lambda            = to_tune(1e-3, 1e3, logscale = TRUE),
  alpha             = to_tune(1e-3, 1e3, logscale = TRUE),
  subsample         = to_tune(1e-1, 1)
)

# 执行Hyperband调参
instance = tune(
  tnr("hyperband", eta = 3),
  task = task, # 使用自定义的Task对象
  learner = learner,
  resampling = rsmp("cv", folds = 3),
  measures = msr("classif.ce")
)

# 查看调参结果
instance$result

注意事项

  • 如果是回归任务,将as_task_classif()替换为as_task_regr(),同时将lrn("classif.xgboost")改为lrn("regr.xgboost"),msr("classif.ce")改为回归对应的指标(比如msr("regr.mse"))。
  • 确保目标列的类型符合任务要求:分类任务的目标列应为因子或字符型,回归任务应为数值型。

内容的提问来源于stack exchange,提问作者Abubakar Popoola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 01:42:12