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

使用tidymodels、parsnip、workflows复用Recipe处理试验结果的挑战

在tidymodels中复用Recipe适配多模型(针对浓缩计数数据)

目标

复用一个recipe对象,适配逻辑回归、随机森林等多种建模类型,处理浓缩后的调查计数数据。

数据变量

  • outcome_yes:事件发生的数值计数
  • outcome_no:事件未发生的数值计数
  • total_tested:测试总次数(等于outcome_yes与outcome_no之和)
  • cat_pred:二分类预测变量(取值为是/否)
  • num_pred:连续型预测变量(潜在结果障碍计数)

现有可行建模方法(基础glm实现)

以下两种glm()写法结果一致,且已在SAS中复现:

  1. 使用cbind()构建响应变量:
example_data |>
  glm(
    cbind(outcome_yes, outcome_no) ~ cat_pred + num_pred,
    family = binomial(),
    data = _
  )
  1. 事件/试验语法+权重:
example_data |>
  glm(
    outcome_yes / total_tested ~ cat_pred + num_pred,
    family = binomial(),
    weights = total_tested,
    data = _
  )

遇到的问题

在recipe()中使用上述任一写法时,直接报错:

Error in `inline_check()`:
! No in-line functions should be used here; use steps to define baking actions.
Backtrace:
 1. recipes::recipe(...)
 2. recipes:::recipe.formula(...)
 3. recipes:::form2args(formula, data, ...)
 4. recipes:::inline_check(formula)

尝试的解决方案及报错

尝试将因变量设为outcome_yes + outcome_no,但在fit()步骤失败:

代码示例

the_recipe <-
  recipe(
    outcome_yes + outcome_no ~ cat_pred + num_pred,
    family = binomial(),
    data = example_data
  ) |> 
  step_relevel(all_factor_predictors(), ref_level = 'No') |> 
  step_dummy(all_factor_predictors())

the_model <-
  logistic_reg() |> 
  set_engine('glm') |> 
  set_mode('classification')

the_workflow <-
  workflow() |> 
  add_recipe(the_recipe) |> 
  add_model(the_model)

the_workflow |> 
  fit(example_data)

报错信息

Error in `check_outcome()`:
! For a classification model, the outcome should be a `factor`, not a `tbl_df`.
Backtrace:
  1. generics::fit(the_workflow, example_data)
  2. workflows:::fit.workflow(the_workflow, example_data)
  3. workflows::.fit_model(workflow, control)
  5. workflows:::fit.action_model(...)
  6. workflows:::fit_from_xy(spec, mold, case_weights, control_parsnip)
  8. parsnip::fit_xy.model_spec(...)
  9. parsnip:::xy_form(...)
 10. parsnip:::check_outcome(env$y, object)

核心需求

创建可在workflow中使用、适配多种建模类型的recipe。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 23:33:11