使用parsnip::set_engine("xgboost")传参触发警告,如何消除?
问题背景
使用R语言的parsnip包训练xgboost模型时,尝试通过parsnip::set_engine()传递额外参数(eval_metric、seed),先后尝试两种方式均触发警告:
尝试的两种传参方式
方式一:
model_list$xgboost <- parsnip::boost_tree( trees = 1000, tree_depth = hardhat::tune(), learn_rate = hardhat::tune(), loss_reduction = hardhat::tune(), sample_size = hardhat::tune(), mtry = hardhat::tune() ) %>% parsnip::set_engine("xgboost", eval_metric = "rmse", seed = 55 ) %>% parsnip::set_mode("regression")
方式二:
model_list$xgboost <- parsnip::boost_tree( trees = 1000, tree_depth = hardhat::tune(), learn_rate = hardhat::tune(), loss_reduction = hardhat::tune(), sample_size = hardhat::tune(), mtry = hardhat::tune() ) %>% parsnip::set_engine("xgboost", params = list(eval_metric = "rmse", seed = 55) ) %>% parsnip::set_mode("regression")
触发的警告信息
warning: Passed invalid argument 'info' - entries on it should be passed as direct arguments. This warning will become an error in a future version., Passed invalid function arguments: eval_metric, seed, nthread. These should be passed as a list to argument 'params'. Conversion from argument to 'params' entry will be done automatically, but this behavior will become an error in a future version., Parameter 'watchlist' has been renamed to 'evals'. This warning will become an error in a future version., Argument 'objective' is only for custom objectives. For built-in objectives, pass the objective under 'params'. This warning will become an error in a future version.
当前环境:R 4.3.3、parsnip 1.3.2、xgboost 3.0.2.1
解决方法
结合xgboost 3.x版本的API变化以及parsnip的封装规则,调整参数传递方式即可消除警告:
修改后的代码
model_list$xgboost <- parsnip::boost_tree( trees = 1000, tree_depth = hardhat::tune(), learn_rate = hardhat::tune(), loss_reduction = hardhat::tune(), sample_size = hardhat::tune(), mtry = hardhat::tune() ) %>% parsnip::set_engine( "xgboost", params = list( eval_metric = "rmse", seed = 55, # 回归任务明确指定内置目标函数,避免额外警告 objective = "reg:squarederror" ) ) %>% parsnip::set_mode("regression")
关键注意事项
- 参数分类传递:
boost_tree()中已经封装的参数(如trees、tree_depth)直接在该函数中设置,xgboost原生参数(eval_metric、seed、内置objective)必须放入params列表中传递给set_engine()。 - 适配xgboost 3.x API:
- 原
watchlist参数需替换为evals,同样放入params列表。 - 内置目标函数不能单独作为
set_engine()的参数,必须放在params里,否则会触发objective相关警告。
- 原
- 提前适配未来版本:警告提示当前的兼容转换会在未来版本移除,因此按要求使用
params列表传递参数是长期可行的方案。
内容的提问来源于stack exchange,提问作者SiriO

