【问题标题】:step_mutate() couldn't find the function str_remove()step_mutate() 找不到函数 str_remove()
【发布时间】:2021-10-20 01:23:26
【问题描述】:

我有一个中间有 step_mutate() 函数的配方,在 stringr 包的支持下对 Titanic 数据集执行文本数据转换。

library(tidyverse)
library(tidymodels)

extract_title <- function(x) stringr::str_remove(str_extract(x, "Mr\\.? |Mrs\\.?|Miss\\.?|Master\\.?"), "\\.")

rf_recipe <- 
  recipe(Survived ~ ., data = titanic_train) %>% 
  step_impute_mode(Embarked) %>% 
  step_mutate(Cabin = if_else(is.na(Cabin), "Yes", "No"),
              Title = if_else(is.na(extract_title(Name)), "Other", extract_title(Name))) %>% 
  step_impute_knn(Age, impute_with = c("Title", "Sex", "SibSp", "Parch")) %>% 
  update_role(PassengerId, Name, new_role = "id")

这组转换与rf_recipe %&gt;% prep() %&gt;% bake(new_data = NULL) 完美配合。

当我尝试在工作流中使用超参数调整和 10 倍交叉验证来拟合随机森林模型时,所有模型都失败了。 .notes 列的输出明确指出mutate()Title 存在问题:找不到函数str_remove()

doParallel::registerDoParallel()
rf_res <- 
  tune_grid(
    rf_wf,
    resamples = titanic_folds,
    grid = rf_grid,
    control = control_resamples(save_pred = TRUE)
  )

正如this post suggests 我已经明确告诉R str_remove 应该在stringr 包中找到。为什么这不起作用,可能是什么原因造成的?

【问题讨论】:

  • extract_title 函数分解为两个单独的变异步骤是否有效?
  • 它没有。也许它与 step_mutate 中的自定义函数有关。
  • 尝试的一个想法是在pkgs 中包含control argument for tuning 中的stringr。

标签: r dplyr tidymodels r-recipes


【解决方案1】:

我不认为这会修复错误,但是以防万一str_extract函数没有写stringr :: str_extract,你加载包了吗?

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

出现错误是因为step_knn_impute() 以及随后的gower::gower_topn 函数将所有字符转换为因子。为了解决这个问题,我必须应用 prep()bake() 函数,而无需在工作流中包含配方。

prep_recipe <- prep(rf_recipe)  
train_processed <- bake(prep_recipe, new_data = NULL)
test_processed <- bake(prep_recipe, new_data = titanic_test %>%
                         mutate(across(where(is.character), as.factor)))

现在模型收敛了。

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 2022-10-05
    • 2019-09-09
    • 2012-01-07
    • 2019-05-19
    • 2020-10-02
    • 2015-11-26
    • 2017-04-25
    • 2013-10-28
    相关资源
    最近更新 更多