如何解决在 R tidymodels 中尝试的 LASSO 模型中出现一致的“错误:为该步骤选择的所有列都应为数字”
尝试运行我的第一个 LASSO 模型并遇到了一些问题。我有一个医学数据集,我试图从大约 60 个预测变量中预测二分结果(疾病)。尽管在配方阶段已经将它们全部转换为虚拟变量,但我在收到错误“为该步骤选择的所有列都应该是数字”之前调整了网格。我减少了预测变量的数量,看看是否会改变任何东西,但它似乎没有解决问题。结果并不常见,在大约 3% 的情况下会出现,所以我不知道这是否会影响任何事情。 代码如下
拆分为测试和训练数据并按疾病分层
set.seed(123)
df_split <- initial_split(df,strata = disease)
df_train <- training(df_split)
df_test <- testing(df_split)
创建验证集
set.seed(234)
validation_set <- validation_split(df_train,strata = dfPyVAN,prop = 0.8)
构建模型
df_model <-
logistic_reg(penalty = tune(),mixture = 1) %>%
set_engine("glmnet")
创建配方
df_recipe <-
recipe(dfPyVAN ~ .,data = df_train) %>%
step_medianimpute(all_predictors()) %>%
step_dummy(all_nominal(),-all_outcomes()) %>%
step_zv(all_predictors()) %>%
step_normalize(all_predictors())
创建工作流程
df_workflow <-
workflow() %>%
add_model(df_model) %>%
add_recipe(df_recipe)
要调整的惩罚值网格
df_reg_grid <- tibble(penalty = 10^seq(-4,-1,length.out = 30))
训练和调整模型 - 这是它崩溃的步骤,我得到了不断的错误
df_res <-
df_workflow %>%
tune_grid(validation_set,grid = df_reg_grid,control = control_grid(save_pred = TRUE),metrics = metric_set(roc_auc))
我尝试了多种变体,但结果相同 - 如果有人能提供任何帮助,我将不胜感激,
非常感谢
解决方法
您收到的错误来自 step_medianimpute()
。 step_medianimpute()
要求所有变量都是数字,但它通过 all_predictors()
传递因子变量。
解决此问题的一种方法是在估算之前重新排列您的配方以创建虚拟变量。
library(recipes)
library(modeldata)
data(ames)
df_recipe <-
recipe(Central_Air ~ .,data = ames) %>%
step_medianimpute(all_predictors()) %>%
step_dummy(all_nominal(),-all_outcomes()) %>%
step_zv(all_predictors()) %>%
step_normalize(all_predictors())
prep(df_recipe)
#> Error: All columns selected for the step should be numeric
df_recipe <-
recipe(Central_Air ~ .,data = ames) %>%
step_dummy(all_nominal(),-all_outcomes()) %>%
step_medianimpute(all_predictors()) %>%
step_zv(all_predictors()) %>%
step_normalize(all_predictors())
prep(df_recipe)
#> Data Recipe
#>
#> Inputs:
#>
#> role #variables
#> outcome 1
#> predictor 73
#>
#> Training data contained 2930 data points and no missing data.
#>
#> Operations:
#>
#> Dummy variables from MS_SubClass,MS_Zoning,Street,Alley,... [trained]
#> Median Imputation for Lot_Frontage,Lot_Area,... [trained]
#> Zero variance filter removed 2 items [trained]
#> Centering and scaling for Lot_Frontage,... [trained]
由 reprex package (v1.0.0) 于 2021 年 4 月 27 日创建
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。