workflow_set,带有 dplyr 风格的选择器来选择结果和预测变量 R

问题描述 投票:0回答:1

我希望使用工作流程集来迭代模型创建中的不同变量。

https://www.tmwr.org/workflow-sets 中指出

有三种可能的预处理器:

  • 标准R公式
  • 菜谱对象(在估计/准备之前)
  • 用于选择结果和预测变量的 dplyr 风格选择器

但它仅提供了标准 R 公式的示例。 我更喜欢以 Dplyr 风格工作,因此如果我制作自己的函数,我可以在将来轻松地指定结果和预测变量。 我环顾四周,找不到任何 Dplyr 风格的例子。

但我发现 recipie%>%updateroal%>%updateroal 有效,但它很冗长。 (示例2)

不幸的是,我的第三种方法 add_variable 不起作用。

有谁知道如何以比我发现的更好的方式为workflow_set编写dplyr样式?

示例 1 R 公式样式

 set.seed(123)
  data <- data.frame(
    x1 = rnorm(100),
    x2 = rnorm(100),
    x3 = rnorm(100),
    x4 = rnorm(100),
    y = rnorm(100)
  )
  
  variables<-list(
    first = y ~ x1,
    second = y ~ x2,
    third = y ~ x1+x2,
    fourth = y ~ x3+x4
  )
  
  
  lm_model <- 
    linear_reg() %>% 
    set_engine("lm")
  
  location_models <- workflow_set(preproc = variables, models = list(lm = lm_model))
  location_models
  location_models$fit[[4]]
  extract_workflow(location_models, id = "third_lm")
  
  location_models <-
    location_models %>%
  mutate(fit = map(info, \(x) fit(x$workflow[[1]], data)))
  location_models$fit[[4]]

示例2更新角色

variables<-list(
    fist = recipe(data)%>%update_role( y, new_role = "outcome")%>%update_role( x1, new_role = "predictor"),
    second = recipe(data)%>%update_role( y, new_role = "outcome")%>%update_role( x2, new_role = "predictor"),
    third = recipe(data)%>%update_role( y, new_role = "outcome")%>%update_role( c(x1,x2), new_role = "predictor"),
    forth = recipe(data)%>%update_role( y, new_role = "outcome")%>%update_role( c(x3,x4), new_role = "predictor")
  )

示例 3 添加变量(不起作用)

variables<-list(
  fist = add_variables(outcomes = y, predictors = x1),
  second = add_variables(outcomes = y, predictors = x2),
  third = add_variables(outcomes = y, predictors = c(x1,x2)),
  forth = add_variables(outcomes = y, predictors = c(x3,x4))
  )
r tidymodels
1个回答
0
投票

?workflow_sets
的帮助页面有答案。预处理器列表可以包含:

  • 传统的 R 公式。
  • 通过
    recipes::recipe()
    的食谱定义(未准备)。
  • workflows::workflow_variables()
    创建的选择器对象。

你可以使用

variables <- list(
  fist   = workflow_variables(outcomes = y, predictors = x1),
  second = workflow_variables(outcomes = y, predictors = x2),
  third  = workflow_variables(outcomes = y, predictors = c(x1, x2)),
  forth  = workflow_variables(outcomes = y, predictors = c(x3, x4))
)
© www.soinside.com 2019 - 2024. All rights reserved.