regr-tree02

statlearning
trees
tidymodels
mtcars
string
Published

May 17, 2023

library(tidymodels)

Aufgabe

Berechnen Sie einfaches Prognosemodell auf Basis eines Entscheidungsbaums!

Modellformel: am ~ . (Datensatz mtcars)

Berichten Sie die Modellgüte (ROC-AUC).

Hinweise:

  • Tunen Sie alle Parameter (die der Engine anbietet).
  • Führen Sie eine \(v=2\)-fache Kreuzvalidierung durch (weil die Stichprobe so klein ist).
  • Beachten Sie die üblichen Hinweise.











Lösung

Setup

library(tidymodels)
data(mtcars)
library(tictoc)  # Zeitmessung

Für Klassifikation verlangt Tidymodels eine nominale AV, keine numerische:

mtcars <-
  mtcars %>% 
  mutate(am = factor(am))

Daten teilen

d_split <- initial_split(mtcars)
d_train <- training(d_split)
d_test <- testing(d_split)

Modell(e)

mod_tree <-
  decision_tree(mode = "classification",
                cost_complexity = tune(),
                tree_depth = tune(),
                min_n = tune())

Rezept(e)

rec1 <- 
  recipe(am ~ ., data = d_train)

Resampling

rsmpl <- vfold_cv(d_train, v = 2)

Workflow

wf1 <-
  workflow() %>%  
  add_recipe(rec1) %>% 
  add_model(mod_tree)

Tuning/Fitting

fit1 <-
  tune_grid(object = wf1,
            metrics = metric_set(roc_auc),
            resamples = rsmpl)

Bester Kandidat

autoplot(fit1)

show_best(fit1)
# A tibble: 5 × 9
  cost_complexity tree_depth min_n .metric .estimator  mean     n std_err
            <dbl>      <int> <int> <chr>   <chr>      <dbl> <int>   <dbl>
1        1.07e- 8          4     2 roc_auc binary     0.764     2  0.0139
2        9.57e- 4         10    10 roc_auc binary     0.764     2  0.0139
3        1.25e-10         14    20 roc_auc binary     0.764     2  0.0139
4        6.83e- 2         11    17 roc_auc binary     0.764     2  0.0139
5        3.01e- 5          3     7 roc_auc binary     0.764     2  0.0139
# ℹ 1 more variable: .config <chr>

Finalisieren

wf1_finalized <-
  wf1 %>% 
  finalize_workflow(select_best(fit1))

Last Fit

final_fit <- 
  last_fit(object = wf1_finalized, d_split)

collect_metrics(final_fit)
# A tibble: 3 × 4
  .metric     .estimator .estimate .config             
  <chr>       <chr>          <dbl> <chr>               
1 accuracy    binary          0.75 Preprocessor1_Model1
2 roc_auc     binary          0.75 Preprocessor1_Model1
3 brier_class binary          0.25 Preprocessor1_Model1

Categories:

  • statlearning
  • trees
  • tidymodels
  • string