我想使用OneR包中的breastcancer数据集创建一个正则化的逻辑回归模型来预测Class。我希望将这一切整合到tidymodels框架下的一个整洁的工作流程中。
library(tidymodels)library(OneR)#指定模型bc.lr = logistic_reg( mode="classification", penalty = tune(), mixture=1) %>% set_engine("glmnet")#使用4折交叉验证调整惩罚项cv_splits<-vfold_cv(breastcancer,v=4,strata="Class")#简单配方,用于缩放所有预测变量并删除包含NA的观测值bc.recipe <- recipe (Class ~., data = breastcancer) %>% step_normalize(all_predictors()) %>% step_naomit(all_predictors(), all_outcomes()) %>% prep()#设置调参网格tuning_grid = grid_regular(penalty(range = c(0, 0.5)), levels = 10, original = F)#将所有内容整合到一个工作流程中bc.wkfl <- workflow() %>% add_recipe(bc.recipe) %>% add_model(bc.lr)#模型拟合tune = tune_grid(bc.wkfl, resample = cv_splits, grid = tuning_grid, metrics = metric_set(accuracy), control = control_grid(save_pred = T))
当我尝试调用tune_grid时,得到一个奇怪的错误。
Fold1: model 1/1 (predictions): Error: Column `.row` must be length ....
回答:
这里的问题在于配方步骤对NA
值的处理。这是一个你需要仔细考虑“skipping”的步骤。来自那篇文章的引用:
在进行重抽样或训练/测试分割时,某些操作对于用于建模的数据是有意义的,但对于新样本或测试集来说可能存在问题。
library(tidymodels)#> ── Attaching packages ────────────────────────────────────────── tidymodels 0.1.0 ──#> ✓ broom 0.5.6 ✓ recipes 0.1.12#> ✓ dials 0.0.6 ✓ rsample 0.0.6 #> ✓ dplyr 0.8.5 ✓ tibble 3.0.1 #> ✓ ggplot2 3.3.0 ✓ tune 0.1.0 #> ✓ infer 0.5.1 ✓ workflows 0.1.1 #> ✓ parsnip 0.1.1 ✓ yardstick 0.0.6 #> ✓ purrr 0.3.4#> ── Conflicts ───────────────────────────────────────────── tidymodels_conflicts() ──#> x purrr::discard() masks scales::discard()#> x dplyr::filter() masks stats::filter()#> x dplyr::lag() masks stats::lag()#> x ggplot2::margin() masks dials::margin()#> x recipes::step() masks stats::step()library(OneR)lasso_spec <- logistic_reg(penalty = tune(), mixture = 1) %>% set_engine("glmnet")## 交叉验证分割cancer_splits <- vfold_cv(breastcancer, v = 4, strata = Class)## 预处理配方(注意设置skip = TRUE)cancer_rec <- recipe(Class ~ ., data = breastcancer) %>% step_naomit(all_predictors(), skip = TRUE) %>% step_normalize(all_predictors())## 调参网格tuning_grid <- grid_regular(penalty(), levels = 10)## 将所有内容整合到一个工作流程中cancer_wf <- workflow() %>% add_recipe(cancer_rec) %>% add_model(lasso_spec)## 拟合cancer_res <- tune_grid( cancer_wf, resamples = cancer_splits, grid = tuning_grid, control = control_grid(save_pred = TRUE))cancer_res#> # 4-fold cross-validation using stratification #> # A tibble: 4 x 5#> splits id .metrics .notes .predictions #> <list> <chr> <list> <list> <list> #> 1 <split [523/176]> Fold1 <tibble [20 × 4]> <tibble [0 × 1]> <tibble [1,760 × 6…#> 2 <split [524/175]> Fold2 <tibble [20 × 4]> <tibble [0 × 1]> <tibble [1,750 × 6…#> 3 <split [525/174]> Fold3 <tibble [20 × 4]> <tibble [0 × 1]> <tibble [1,740 × 6…#> 4 <split [525/174]> Fold4 <tibble [20 × 4]> <tibble [0 × 1]> <tibble [1,740 × 6…
Created on 2020-05-14 by the reprex package (v0.3.0)
请注意,设置skip = TRUE
允许你以适当的方式处理新数据中的NA
值。