<p><a href="https://twitter.com/drsimonj">@drsimonj</a> here to show you how to use pipelearner to easily grid-search hyperparameters for a model.</p>
<p>pipelearner is a package for making machine learning piplines and is currently available to install from GitHub by running the following:</p>
<pre><code># install.packages(&quot;devtools&quot;)  # Run this if devtools isn't installed
devtools::install_github(&quot;drsimonj/pipelearner&quot;)
library(pipelearner)
</code></pre>
<p>In this post we’ll grid search hyperparameters of a decision tree (using the rpart package) predicting cars’ transmission type (automatic or manual) using the mtcars data set. Let’s load rpart along with tidyverse, which pipelearner is intended to work with:</p>
<pre><code>library(tidyverse)
library(rpart)
</code></pre>
<h3><a href="https://drsimonj.svbtle.com/#the-data_3"> </a>The data</h3>
<p>Quickly convert our outcome variable to a factor with proper labels:</p>
<pre><code>d &lt;- mtcars %>% 
  mutate(am = factor(am, labels = c(&quot;automatic&quot;, &quot;manual&quot;)))
head(d)
#>    mpg cyl disp  hp drat    wt  qsec vs        am gear carb
#> 1 21.0   6  160 110 3.90 2.620 16.46  0    manual    4    4
#> 2 21.0   6  160 110 3.90 2.875 17.02  0    manual    4    4
#> 3 22.8   4  108  93 3.85 2.320 18.61  1    manual    4    1
#> 4 21.4   6  258 110 3.08 3.215 19.44  1 automatic    3    1
#> 5 18.7   8  360 175 3.15 3.440 17.02  0 automatic    3    2
#> 6 18.1   6  225 105 2.76 3.460 20.22  1 automatic    3    1
</code></pre>
<h2><a href="https://drsimonj.svbtle.com/#default-hyperparameters_2"> </a>Default hyperparameters</h2>
<p>We’ll first create a pipelearner object that uses the default hyperparameters of the decision tree.</p>
<pre><code>pl &lt;- d %>% pipelearner(rpart, am ~ .)
pl
#> $data
#> # A tibble: 32 × 11
#>      mpg   cyl  disp    hp  drat    wt  qsec    vs        am  gear  carb
#>    &lt;dbl> &lt;dbl> &lt;dbl> &lt;dbl> &lt;dbl> &lt;dbl> &lt;dbl> &lt;dbl>    &lt;fctr> &lt;dbl> &lt;dbl>
#> 1   21.0     6 160.0   110  3.90 2.620 16.46     0    manual     4     4
#> 2   21.0     6 160.0   110  3.90 2.875 17.02     0    manual     4     4
#> 3   22.8     4 108.0    93  3.85 2.320 18.61     1    manual     4     1
#> 4   21.4     6 258.0   110  3.08 3.215 19.44     1 automatic     3     1
#> 5   18.7     8 360.0   175  3.15 3.440 17.02     0 automatic     3     2
#> 6   18.1     6 225.0   105  2.76 3.460 20.22     1 automatic     3     1
#> 7   14.3     8 360.0   245  3.21 3.570 15.84     0 automatic     3     4
#> 8   24.4     4 146.7    62  3.69 3.190 20.00     1 automatic     4     2
#> 9   22.8     4 140.8    95  3.92 3.150 22.90     1 automatic     4     2
#> 10  19.2     6 167.6   123  3.92 3.440 18.30     1 automatic     4     4
#> # ... with 22 more rows
#> 
#> $cv_pairs
#> # A tibble: 1 × 3
#>            train           test   .id
#>           &lt;list>         &lt;list> &lt;chr>
#> 1 &lt;S3: resample> &lt;S3: resample>     1
#> 
#> $train_ps
#> [1] 1
#> 
#> $models
#> # A tibble: 1 × 5
#>   target model     params     .f   .id
#>    &lt;chr> &lt;chr>     &lt;list> &lt;list> &lt;chr>
#> 1     am rpart &lt;list [1]>  &lt;fun>     1
#> 
#> attr(,&quot;class&quot;)
#> [1] &quot;pipelearner&quot;
</code></pre>
<p>Fit the model with <code>learn()</code>:</p>
<pre><code>results &lt;- pl %>% learn()
results
#> # A tibble: 1 × 9
#>   models.id cv_pairs.id train_p         fit target model     params
#>       &lt;chr>       &lt;chr>   &lt;dbl>      &lt;list>  &lt;chr> &lt;chr>     &lt;list>
#> 1         1           1       1 &lt;S3: rpart>     am rpart &lt;list [1]>
#> # ... with 2 more variables: train &lt;list>, test &lt;list>
</code></pre>
<p>The fitted results include our single model. Let’s assess the model’s performance on the training and test sets:</p>
<pre><code># Function to compute accuracy
accuracy &lt;- function(fit, data, target_var) {
  # Coerce `data` to data.frame (needed for resample objects)
  data &lt;- as.data.frame(data)
  # Obtain predicted class
  predicted &lt;- predict(fit, data, type = &quot;class&quot;)
  # Return accuracy
  mean(predicted == data[[target_var]])
}

# Training accuracy
accuracy(results$fit[[1]], results$train[[1]], results$target[[1]])
#> [1] 0.92

# Test accuracy
accuracy(results$fit[[1]], results$test[[1]], results$target[[1]])
#> [1] 0.8571429
</code></pre>
<p>Looks like we’ve achieved 92% accuracy on the training data and 86% accuracy on the test data. Perhaps we can improve on this by tweaking the model’s hyperparameters.</p>
<h2><a href="https://drsimonj.svbtle.com/#adding-hyperparameters_2"> </a>Adding hyperparameters</h2>
<p>When using pipelearner, you can add any arguments that the learning function will accept after we provide a formula. For example, run <code>?rpart</code> and you’ll see that control options can be added. To see these options, run <code>?rpart.control</code>.</p>
<p>An obvious choice for decision trees in <code>minsplit</code>, which determines “the minimum number of observations that must exist in a node in order for a split to be attempted.” By default it’s set to 20. Given that we have such a small data set, this seems like a poor choice. We can adjust it as follows:</p>
<pre><code>pl &lt;- d %>% pipelearner(rpart, am ~ ., minsplit = 5)
results &lt;- pl %>% learn()

# Training accuracy
accuracy(results$fit[[1]], results$train[[1]], results$target[[1]])
#> [1] 0.92

# Test accuracy
accuracy(results$fit[[1]], results$test[[1]], results$target[[1]])
#> [1] 0.8571429
</code></pre>
<p>Reducing <code>minsplit</code> will generally increase your training accuracy. Too small, however, and you’ll overfit the training data resulting in poorer test accuracy.</p>
<h2><a href="https://drsimonj.svbtle.com/#using-vectors_2"> </a>Using vectors</h2>
<p>All the model arguments you provide to <code>pipelearner()</code> can be vectors. pipelearner will then automatically expand those vectors into a grid and test all combinations. For example, let’s try out many values for <code>minsplit</code>:</p>
<pre><code>pl &lt;- d %>% pipelearner(rpart, am ~ ., minsplit = c(2, 4, 6, 8, 10))
results &lt;- pl %>% learn()
results
#> # A tibble: 5 × 9
#>   models.id cv_pairs.id train_p         fit target model     params
#>       &lt;chr>       &lt;chr>   &lt;dbl>      &lt;list>  &lt;chr> &lt;chr>     &lt;list>
#> 1         1           1       1 &lt;S3: rpart>     am rpart &lt;list [2]>
#> 2         2           1       1 &lt;S3: rpart>     am rpart &lt;list [2]>
#> 3         3           1       1 &lt;S3: rpart>     am rpart &lt;list [2]>
#> 4         4           1       1 &lt;S3: rpart>     am rpart &lt;list [2]>
#> 5         5           1       1 &lt;S3: rpart>     am rpart &lt;list [2]>
#> # ... with 2 more variables: train &lt;list>, test &lt;list>
</code></pre>
<p>Combining <code>mutate</code> from dplyr and <code>map</code> functions from the purrr package (all loaded with tidyverse), we can extract the relevant information for each value of <code>minsplit</code>:</p>
<pre><code>results &lt;- results %>% 
  mutate(
    minsplit = map_dbl(params, &quot;minsplit&quot;),
    accuracy_train = pmap_dbl(list(fit, train, target), accuracy),
    accuracy_test  = pmap_dbl(list(fit, test,  target), accuracy)
  )

results %>% select(minsplit, contains(&quot;accuracy&quot;))
#> # A tibble: 5 × 3
#>   minsplit accuracy_train accuracy_test
#>      &lt;dbl>          &lt;dbl>         &lt;dbl>
#> 1        2              1     0.5714286
#> 2        4              1     0.5714286
#> 3        6              1     0.5714286
#> 4        8              1     0.5714286
#> 5       10              1     0.5714286
</code></pre>
<p>This applies to as many hyperparameters as you care to add. For example, let’s grid search combinations of values for <code>minsplit</code>, <code>maxdepth</code>, and <code>xval</code>:</p>
<pre><code>pl &lt;- d %>% pipelearner(rpart, am ~ .,
                        minsplit = c(2, 20),
                        maxdepth = c(2, 5),
                        xval     = c(5, 10))
pl %>%
  learn()%>% 
  mutate(
    minsplit = map_dbl(params, &quot;minsplit&quot;),
    maxdepth = map_dbl(params, &quot;maxdepth&quot;),
    xval     = map_dbl(params, &quot;xval&quot;),
    accuracy_train = pmap_dbl(list(fit, train, target), accuracy),
    accuracy_test  = pmap_dbl(list(fit, test,  target), accuracy)
  ) %>%
  select(minsplit, maxdepth, xval, contains(&quot;accuracy&quot;))
#> # A tibble: 8 × 5
#>   minsplit maxdepth  xval accuracy_train accuracy_test
#>      &lt;dbl>    &lt;dbl> &lt;dbl>          &lt;dbl>         &lt;dbl>
#> 1        2        2     5           1.00     0.8571429
#> 2       20        2     5           0.92     0.8571429
#> 3        2        5     5           1.00     0.8571429
#> 4       20        5     5           0.92     0.8571429
#> 5        2        2    10           1.00     0.8571429
#> 6       20        2    10           0.92     0.8571429
#> 7        2        5    10           1.00     0.8571429
#> 8       20        5    10           0.92     0.8571429
</code></pre>
<p>Not much variance in the accuracy, but it demonstrates how you can use this in your own work.</p>
<h2><a href="https://drsimonj.svbtle.com/#using-trainmodels_2"> </a>Using train_models()</h2>
<p>A bonus tip for those of you how are comfortable so far: you can use <code>learn_models()</code> to isolate multiple grid searches. For example:</p>
<pre><code>pl &lt;- d %>%
  pipelearner() %>% 
  learn_models(rpart, am ~ ., minsplit = c(1, 2), maxdepth = c(4, 5)) %>% 
  learn_models(rpart, am ~ ., minsplit = c(6, 7), maxdepth = c(1, 2))

pl %>%
  learn()%>% 
  mutate(
    minsplit = map_dbl(params, &quot;minsplit&quot;),
    maxdepth = map_dbl(params, &quot;maxdepth&quot;),
    accuracy_train = pmap_dbl(list(fit, train, target), accuracy),
    accuracy_test  = pmap_dbl(list(fit, test,  target), accuracy)
  ) %>%
  select(minsplit, maxdepth, contains(&quot;accuracy&quot;))
#> # A tibble: 8 × 4
#>   minsplit maxdepth accuracy_train accuracy_test
#>      &lt;dbl>    &lt;dbl>          &lt;dbl>         &lt;dbl>
#> 1        1        4           1.00     1.0000000
#> 2        2        4           1.00     1.0000000
#> 3        1        5           1.00     1.0000000
#> 4        2        5           1.00     1.0000000
#> 5        6        1           0.88     0.8571429
#> 6        7        1           0.88     0.8571429
#> 7        6        2           0.96     0.8571429
#> 8        7        2           0.96     0.8571429
</code></pre>
<p>Notice the separate grid searches for <code>minsplit = c(1, 2), maxdepth = c(4, 5)</code> and <code>minsplit = c(6, 7), maxdepth = c(1, 2)</code>.</p>
<p>This is because grid search is applied separately for each model defined by a <code>learn_models()</code> call. This means you can separate various hyperparameters combinations if you want to.</p>
<h2><a href="https://drsimonj.svbtle.com/#sign-off_2"> </a>Sign off</h2>
<p>Thanks for reading and I hope this was useful for you.</p>
<p>For updates of recent blog posts, follow <a href="https://twitter.com/drsimonj">@drsimonj</a> on Twitter, or email me at <a href="mailto:drsimonjackson@gmail.com">drsimonjackson@gmail.com</a> to get in touch.</p>
<p>If you’d like the code that produced this blog, check out the <a href="https://github.com/drsimonj/blogR">blogR GitHub repository</a>.</p>