R tidymodels:如何使用workflow_map()传递initial参数?
解决方案
报错的核心原因是workflow_map("tune_grid")返回的是workflow set对象(带result列的tibble),而tune_bayes()的initial参数需要的是单个模型的tune_grid()输出结果,而非整个集合。要实现对应模型的网格调参结果传递给贝叶斯调参,需要为每个workflow单独匹配对应的initial参数,具体方法如下:
方法1:使用workflow_map的.options参数传递对应结果
利用purrr::map将tune_grid结果列中的每个元素包装为tune_bayes所需的参数列表,通过.options传递给每个workflow:
library(tidymodels) library(purrr) # (前面的数据、配方、模型、交叉验证设置不变) # 先完成网格调参得到workflow set tune_grid <- workflow_set( preproc = list(recipe), models = list(lasso = lasso_model, rf = rf_model)) %>% workflow_map("tune_grid", resamples = cross_val, grid = 25) # 为每个workflow生成对应的initial参数列表 bayes_options <- map(tune_grid$result, ~ list(initial = .x)) # 执行贝叶斯调参,传递对应initial参数 tune_bayes <- workflow_set( preproc = list(recipe), models = list(lasso = lasso_model, rf = rf_model) ) %>% workflow_map( "tune_bayes", resamples = cross_val, .options = bayes_options, iter = 10 # 根据需求调整贝叶斯迭代次数 ) # 查看结果 tune_bayes$result[[1]]
方法2:用mutate结合map2手动映射
通过mutate新增列,用map2遍历workflow_id和对应的网格调参结果,逐个调用tune_bayes:
# 基于已有的tune_grid workflow set,生成贝叶斯调参结果 tune_bayes_results <- tune_grid %>% mutate( bayes_result = map2( wflow_id, result, function(wf_id, grid_res) { # 提取对应workflow wf <- extract_workflow(tune_grid, wf_id) # 调用tune_bayes,传入对应initial结果 tune_bayes( object = wf, resamples = cross_val, initial = grid_res, iter = 10 ) } ) ) # 查看lasso模型的贝叶斯调参结果 tune_bayes_results$bayes_result[[1]]
关键说明
- 两种方法都保证了每个模型的网格调参结果对应传递给自身的贝叶斯调参,避免了传入整个workflow set导致的类型错误。
- 确保
workflow_set的模型顺序和tune_grid的顺序一致(这里因为使用相同的preproc和models列表,顺序天然匹配)。
内容的提问来源于stack exchange,提问作者Matifou
相关产品推荐
相关产品推荐

