Skip to contents

Create a tuneable glmnet worfklow for regression and classification

Usage

workflow_elasticnet(rec, engine = "glmnet", ...)

Arguments

rec

prerocessing recipe to build the workflow

engine

glmnet, spark, brulee (glmnet by default)

...

Optional engine arguments

Examples

library(tidymodels)
library(glmnet)
#> Loading required package: Matrix
#> 
#> Attaching package: ‘Matrix’
#> The following objects are masked from ‘package:tidyr’:
#> 
#>     expand, pack, unpack
#> Loaded glmnet 4.1-9
library(modeldata)
library(future)
data(cells)
split <- cells |>
  mutate(across(where(is.character), as.factor)) |>
  sample_n(500) |>
  initial_split(strata = class)
train <- training(split)
folds <- vfold_cv(train, v = 2, strata = class)
wf <- train |>
  recipe(case ~ .) |>
  step_integer(all_nominal_predictors()) |>
  workflow_elasticnet()
#> [1] "logistic_reg binary classification"
doFuture::registerDoFuture()
plan(sequential)
res <- wf |>
  tune::tune_grid(
    folds,
    grid = 2,
    metrics = metric_set(roc_auc),
    control = tune::control_grid(save_workflow = TRUE, verbose = FALSE)
  )
res |> collect_metrics()
#> # A tibble: 2 × 8
#>        penalty mixture .metric .estimator  mean     n std_err .config           
#>          <dbl>   <dbl> <chr>   <chr>      <dbl> <int>   <dbl> <chr>             
#> 1 1               0.05 roc_auc binary     0.557     2 0.00612 Preprocessor1_Mod…
#> 2 0.0000000001    1    roc_auc binary     0.552     2 0.0186  Preprocessor1_Mod…
res |> last_fit_metrics(split, "roc_auc")
#> # A tibble: 3 × 4
#>   .metric     .estimator .estimate .config             
#>   <chr>       <chr>          <dbl> <chr>               
#> 1 accuracy    binary         0.492 Preprocessor1_Model1
#> 2 roc_auc     binary         0.440 Preprocessor1_Model1
#> 3 brier_class binary         0.251 Preprocessor1_Model1
best <- res |> fit_best()
best |>
  augment(testing(split)) |>
  roc_auc(case, .pred_Test) |>
  pull(.estimate)
#> [1] 0.4395161