<p><a href="https://twitter.com/drsimonj">@drsimonj</a> here to share a tidyverse method of grid search for optimizing a model’s hyperparameters.</p>
<h2><a href="https://drsimonj.svbtle.com/#grid-search_2"> </a>Grid Search</h2>
<p>For anyone who’s unfamiliar with the term, grid search involves running a model many times with combinations of various hyperparameters. The point is to identify which hyperparameters are likely to work best. A more technical definition from <a href="https://en.wikipedia.org/wiki/Hyperparameter_optimization">Wikipedia</a>, grid search is:</p>
<blockquote><p>an exhaustive searching through a manually specified subset of the hyperparameter space of a learning algorithm</p>
</blockquote><h2><a href="https://drsimonj.svbtle.com/#what-this-post-isn39t-about_2"> </a>What this post isn’t about</h2>
<p>To keep the focus on grid search, this post does <strong>NOT</strong> cover…</p>
<ul><li> k-fold cross-validation. Although a practically essential addition to grid search, I’ll save the combination of these techniques for a future post. If you can’t wait, check out my <a href="https://drsimonj.svbtle.com/k-fold-cross-validation-with-modelr-and-broom">last post</a> for some inspiration.</li>
<li> Complex learning models. We’ll stick to a simple decision tree.</li>
<li> Getting a great model fit. I’ve deliberately chosen input variables and hyperparameters that highlight the approach.</li>
</ul><h2><a href="https://drsimonj.svbtle.com/#decision-tree-example_2"> </a>Decision tree example</h2>
<p>Say we want to run a simple decision tree to predict cars’ transmission type (<code>am</code>) based on their miles per gallon (<code>mpg</code>) and horsepower (<code>hp</code>) using the <code>mtcars</code> data set. Let’s prep the data:</p>
<pre><code>library(tidyverse)

d &lt;- mtcars %>% 
       # Convert `am` to factor and select relevant variables
       mutate(am = factor(am, labels = c(&quot;Automatic&quot;, &quot;Manual&quot;))) %>% 
       select(am, mpg, hp)

ggplot(d, aes(mpg, hp, color = am)) +
  geom_point()
</code></pre>
<p><a href="https://svbtleusercontent.com/afba3qginknbq.png"></a></p>
<p>For a decision tree, it looks like a step-wise function until <code>mpg > 25</code>, at which point it’s all Manual cars. Let’s grow a full decision tree on this data:</p>
<pre><code>library(rpart)
library(rpart.plot)

# Set minsplit = 2 to fit every data point
full_fit &lt;- rpart(am ~ mpg + hp, data = d, minsplit = 2)
prp(full_fit)
</code></pre>
<p><a href="https://svbtleusercontent.com/x0cgd5zrhwxlyq.png"></a></p>
<p>We don’t want a model like this, as it almost certainly has overfitting problems. So the question becomes, which hyperparameter specifications would work best for our model to generalize?</p>
<h2><a href="https://drsimonj.svbtle.com/#trainingtest-split_2"> </a>Training-Test Split</h2>
<p>To help validate our hyperparameter combinations, we’ll split our data into training and test sets (in an 80/20 split):</p>
<pre><code>set.seed(245)
n &lt;- nrow(d)
train_rows &lt;- sample(seq(n), size = .8 * n)
train &lt;- d[ train_rows, ]
test  &lt;- d[-train_rows, ]
</code></pre>
<h2><a href="https://drsimonj.svbtle.com/#create-the-grid_2"> </a>Create the Grid</h2>
<p>Step one for grid search is to define our hyperparameter combinations. Say we want to test a few values for <code>minsplit</code> and <code>maxdepth</code>. I like to setup the grid of their combinations in a tidy data frame with a <code>list</code> and <code>cross_d</code> as follows:</p>
<pre><code># Define a named list of parameter values
gs &lt;- list(minsplit = c(2, 5, 10),
           maxdepth = c(1, 3, 8)) %>% 
  cross_d() # Convert to data frame grid

gs
#> # A tibble: 9 × 2
#>   minsplit maxdepth
#>      &lt;dbl>    &lt;dbl>
#> 1        2        1
#> 2        5        1
#> 3       10        1
#> 4        2        3
#> 5        5        3
#> 6       10        3
#> 7        2        8
#> 8        5        8
#> 9       10        8
</code></pre>
<p>Note that the <strong>list names are the names of the hyperparameters</strong> that we want to adjust in our model function.</p>
<h2><a href="https://drsimonj.svbtle.com/#create-a-model-function_2"> </a>Create a model function</h2>
<p>We’ll be iterating down the <code>gs</code> data frame to use the hyperparameter values in a <code>rpart</code> model. The easiest way to handle this is to define a function that accepts a row of our data frame values and passes them correctly to our model. Here’s what I’ll use:</p>
<pre><code>mod &lt;- function(...) {
  rpart(am ~ hp + mpg, data = train, control = rpart.control(...))
}
</code></pre>
<p>Notice the argument <code>...</code> is being passed to <code>control</code> in <code>rpart</code>, which is where these hyperparameters can be used.</p>
<h2><a href="https://drsimonj.svbtle.com/#fit-the-models_2"> </a>Fit the models</h2>
<p>Now, to fit our models, use <code>pmap</code> to iterate down the values. The following is iterating through each row of our <code>gs</code> data frame, plugging the hyperparameter values for that row into our model.</p>
<pre><code>gs &lt;- gs %>% mutate(fit = pmap(gs, mod))
gs
#> # A tibble: 9 × 3
#>   minsplit maxdepth         fit
#>      &lt;dbl>    &lt;dbl>      &lt;list>
#> 1        2        1 &lt;S3: rpart>
#> 2        5        1 &lt;S3: rpart>
#> 3       10        1 &lt;S3: rpart>
#> 4        2        3 &lt;S3: rpart>
#> 5        5        3 &lt;S3: rpart>
#> 6       10        3 &lt;S3: rpart>
#> 7        2        8 &lt;S3: rpart>
#> 8        5        8 &lt;S3: rpart>
#> 9       10        8 &lt;S3: rpart>
</code></pre>
<h2><a href="https://drsimonj.svbtle.com/#obtain-accuracy_2"> </a>Obtain accuracy</h2>
<p>Next, let’s assess the performance of each fit on our test data. To handle this efficiently, let’s write another small function:</p>
<pre><code>compute_accuracy &lt;- function(fit, test_features, test_labels) {
  predicted &lt;- predict(fit, test_features, type = &quot;class&quot;)
  mean(predicted == test_labels)
}
</code></pre>
<p>Now apply this to each fit:</p>
<pre><code>test_features &lt;- test %>% select(-am)
test_labels   &lt;- test$am

gs &lt;- gs %>%
  mutate(test_accuracy = map_dbl(fit, compute_accuracy,
                                 test_features, test_labels))
gs
#> # A tibble: 9 × 4
#>   minsplit maxdepth         fit test_accuracy
#>      &lt;dbl>    &lt;dbl>      &lt;list>         &lt;dbl>
#> 1        2        1 &lt;S3: rpart>     0.7142857
#> 2        5        1 &lt;S3: rpart>     0.7142857
#> 3       10        1 &lt;S3: rpart>     0.7142857
#> 4        2        3 &lt;S3: rpart>     0.8571429
#> 5        5        3 &lt;S3: rpart>     0.8571429
#> 6       10        3 &lt;S3: rpart>     0.7142857
#> 7        2        8 &lt;S3: rpart>     0.8571429
#> 8        5        8 &lt;S3: rpart>     0.8571429
#> 9       10        8 &lt;S3: rpart>     0.7142857
</code></pre>
<h2><a href="https://drsimonj.svbtle.com/#arrange-results_2"> </a>Arrange results</h2>
<p>To find the best model, we <code>arrange</code> the data based on <code>desc(test_accuracy)</code>. The best fitting model will then be in the first row. You might see above that we have many models with the same fit. This is unusual, and likley due to the example I’ve chosen. Still, to handle this, I’ll break ties in accuracy with <code>desc(minsplit)</code> and <code>maxdepth</code> to find the model that is most accurate and also simplest.</p>
<pre><code>gs &lt;- gs %>% arrange(desc(test_accuracy), desc(minsplit), maxdepth)
gs
#> # A tibble: 9 × 4
#>   minsplit maxdepth         fit test_accuracy
#>      &lt;dbl>    &lt;dbl>      &lt;list>         &lt;dbl>
#> 1        5        3 &lt;S3: rpart>     0.8571429
#> 2        5        8 &lt;S3: rpart>     0.8571429
#> 3        2        3 &lt;S3: rpart>     0.8571429
#> 4        2        8 &lt;S3: rpart>     0.8571429
#> 5       10        1 &lt;S3: rpart>     0.7142857
#> 6       10        3 &lt;S3: rpart>     0.7142857
#> 7       10        8 &lt;S3: rpart>     0.7142857
#> 8        5        1 &lt;S3: rpart>     0.7142857
#> 9        2        1 &lt;S3: rpart>     0.7142857
</code></pre>
<p>It looks like a <code>minsplit</code> of 5 and <code>maxdepth</code> of 3 is the way to go!</p>
<p>To compare to our fully fit tree, here’s a plot of this top-performing model. Remember, it’s in the first row so we can reference <code>[[1]]</code>.</p>
<pre><code>prp(gs$fit[[1]])
</code></pre>
<p><a href="https://svbtleusercontent.com/8v4tygcg2vfbtg.png"></a></p>
<h2><a href="https://drsimonj.svbtle.com/#food-for-thought_2"> </a>Food for thought</h2>
<p>Having the results in a tidy data frame lets us do a lot more than just pick the optimal hyperparameters. It lets us quickly wrangle with and visualize the results of the various combinations. Here are some ideas:</p>
<ul><li> Search among the top performers for the simplest model.</li>
<li> Plot performance across the hyperparameter combinations.</li>
<li> Save time by restricting the hypotheses before model fitting. For example, in a large data set, it’s practically pointless to try a small <code>minsplit</code> and small <code>maxdepth</code>. In this case, before fitting the models, we can <code>filter</code> the <code>gs</code> data frame to exclude certain combinations.</li>
</ul><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>