<p><strong>Previously in this series:</strong></p>
<ul><li><a href="http://varianceexplained.org/statistics/beta_distribution_and_baseball/">Understanding the beta distribution</a></li>
<li><a href="http://varianceexplained.org/r/empirical_bayes_baseball/">Understanding empirical Bayes estimation</a></li>
<li><a href="http://varianceexplained.org/r/credible_intervals_baseball/">Understanding credible intervals</a></li>
<li><a href="http://varianceexplained.org/r/bayesian_fdr_baseball/">Understanding the Bayesian approach to false discovery rates</a></li>
<li><a href="http://varianceexplained.org/r/bayesian_ab_baseball/">Understanding Bayesian A/B testing</a></li>
<li><a href="http://varianceexplained.org/r/beta_binomial_baseball/">Understanding beta binomial regression</a></li>
<li><a href="http://varianceexplained.org/r/hierarchical_bayes_baseball/">Understanding empirical Bayesian hierarchical modeling</a></li>
</ul><p>In this series on empirical Bayesian methods on baseball data, we’ve been treating our overall distribution of batting averages as a beta distribution, which is a simple distribution between 0 and 1 that has a single peak. But what if that weren’t a good fit? For example, what if we had a <a href="https://en.wikipedia.org/wiki/Multimodal_distribution">multimodal</a> distribution, with multiple peaks?</p>
<p>In this post, we’re going to consider what to do when your binomial proportions are made up of multiple peaks, and when you don’t know which observation belongs to which clusters. For example, so far in our analysis we’ve been filtering out pitchers, who tend to have a much lower batting average than non-pitchers. If you include them, the data looks something like this:</p>
<p></p>
<p>These batting averages certainly don’t look like a single beta distribution- it’s more like two separate ones mixed together. Imagine that you didn’t know which players were pitchers, and you wanted to separate the data into two groups according to your best prediction. This is very common in practical machine learning applications, such as clustering and segmentation.</p>
<p>In this post we’ll examine <a href="https://en.wikipedia.org/wiki/Mixture_model">mixture models</a>, where we treat the distribution of batting averages as a <strong>mixture of two beta-binomial distributions</strong>, and need to guess which player belongs to which group. This will also introduce the concept of an <a href="https://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm">expectation-maximization algorithm</a>, which is important in both Bayesian and frequentist statistics. We’ll show how to calculate a posterior probability for the cluster each player belongs to, and see that mixture models are still a good fit for the empirical Bayes framework.</p>
<h3>Setup</h3>
<p>As usual, I’ll start with some code you can use to catch up if you want to follow along in R. If you want to understand what it does in more depth, check out the previous posts in this series. (As always, all the code in this post can be found <a href="https://github.com/dgrtwo/dgrtwo.github.com/blob/master/_R/2017-01-03-mixture_models_baseball.Rmd">here</a>).<a href="http://varianceexplained.org/#fn:subset">1</a></p>
<pre><code><span>library</span><span>(</span><span>dplyr</span><span>)</span><span>
</span><span>library</span><span>(</span><span>tidyr</span><span>)</span><span>
</span><span>library</span><span>(</span><span>Lahman</span><span>)</span><span>
</span><span>library</span><span>(</span><span>ggplot2</span><span>)</span><span>
</span><span>theme_set</span><span>(</span><span>theme_bw</span><span>())</span><span>
</span><span># Identify those who have pitched at least three games
</span><span>pitchers</span><span> </span><span>&lt;-</span><span> </span><span>Pitching</span><span> </span><span>%>%</span><span>
</span><span>group_by</span><span>(</span><span>playerID</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>summarize</span><span>(</span><span>gamesPitched</span><span> </span><span>=</span><span> </span><span>sum</span><span>(</span><span>G</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>filter</span><span>(</span><span>gamesPitched</span><span> </span><span>></span><span> </span><span>3</span><span>)</span><span>
</span><span># in this setup, we're keeping some extra information for later in the post:
# a &quot;bats&quot; column and a &quot;year&quot; column
</span><span>career</span><span> </span><span>&lt;-</span><span> </span><span>Batting</span><span> </span><span>%>%</span><span>
</span><span>filter</span><span>(</span><span>AB</span><span> </span><span>></span><span> </span><span>0</span><span>,</span><span> </span><span>lgID</span><span> </span><span>==</span><span> </span><span>&quot;NL&quot;</span><span>,</span><span> </span><span>yearID</span><span> </span><span>>=</span><span> </span><span>1980</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>group_by</span><span>(</span><span>playerID</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>summarize</span><span>(</span><span>H</span><span> </span><span>=</span><span> </span><span>sum</span><span>(</span><span>H</span><span>),</span><span> </span><span>AB</span><span> </span><span>=</span><span> </span><span>sum</span><span>(</span><span>AB</span><span>),</span><span> </span><span>year</span><span> </span><span>=</span><span> </span><span>mean</span><span>(</span><span>yearID</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>average</span><span> </span><span>=</span><span> </span><span>H</span><span> </span><span>/</span><span> </span><span>AB</span><span>,</span><span>
</span><span>isPitcher</span><span> </span><span>=</span><span> </span><span>playerID</span><span> </span><span>%in%</span><span> </span><span>pitchers</span><span>$</span><span>playerID</span><span>)</span><span>
</span><span># Add player names
</span><span>career</span><span> </span><span>&lt;-</span><span> </span><span>Master</span><span> </span><span>%>%</span><span>
</span><span>tbl_df</span><span>()</span><span> </span><span>%>%</span><span>
</span><span>dplyr</span><span>::</span><span>select</span><span>(</span><span>playerID</span><span>,</span><span> </span><span>nameFirst</span><span>,</span><span> </span><span>nameLast</span><span>,</span><span> </span><span>bats</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>unite</span><span>(</span><span>name</span><span>,</span><span> </span><span>nameFirst</span><span>,</span><span> </span><span>nameLast</span><span>,</span><span> </span><span>sep</span><span> </span><span>=</span><span> </span><span>&quot; &quot;</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>inner_join</span><span>(</span><span>career</span><span>,</span><span> </span><span>by</span><span> </span><span>=</span><span> </span><span>&quot;playerID&quot;</span><span>)</span></code></pre><p>We’ve been filtering out pitchers in the previous posts, which make batting averages look roughly like a beta distribution. But when we leave them in, as I showed above, the data looks a lot less like a beta:</p>
<p></p>
<p>The dashed density curve represents the beta distribution we would naively fit to this data. We can see that unlike our earlier analysis, where we’d filtered out pitchers, the beta is not a good fit- but that it’s plausible that we could fit the data using two beta distributions, one for pitchers and one for non-pitchers.</p>
<p>In this example, we know which players are pitchers and which aren’t. But if we didn’t, we would need to assign each player to a distribution, or “cluster”, before performing shrinkage on it. In a real analysis it’s not realistic that we wouldn’t know which players are pitchers, but it’s an excellent illustrative example of a mixture model and of expectation-maximization algorithms.</p>
<h3>Expectation-maximization</h3>
<p>The challenge of mixture models is that at the start, we don’t know which observations belong to which cluster, nor what the parameters of each distribution is. It’s difficult to solve these problems at the same time- so an expectation-maximization (EM) algorithm takes the jump of estimating them one at a time, and <strong>alternating</strong> between them.</p>
<p>The first thing to do in an EM clustering algorithm is to assign our clusters <strong>randomly</strong>:</p>
<pre><code><span>set.seed</span><span>(</span><span>2016</span><span>)</span><span>
</span><span># We'll fit the clusters only with players that have had at least 20 at-bats
</span><span>starting_data</span><span> </span><span>&lt;-</span><span> </span><span>career</span><span> </span><span>%>%</span><span>
</span><span>filter</span><span>(</span><span>AB</span><span> </span><span>>=</span><span> </span><span>20</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>select</span><span>(</span><span>-</span><span>year</span><span>,</span><span> </span><span>-</span><span>bats</span><span>,</span><span> </span><span>-</span><span>isPitcher</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>cluster</span><span> </span><span>=</span><span> </span><span>factor</span><span>(</span><span>sample</span><span>(</span><span>c</span><span>(</span><span>&quot;A&quot;</span><span>,</span><span> </span><span>&quot;B&quot;</span><span>),</span><span> </span><span>n</span><span>(),</span><span> </span><span>replace</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>)))</span></code></pre><h4>Maximization</h4>
<p>Now that we’ve got cluster assignments, what do the densities of each cluster look like?</p>
<pre><code><span>starting_data</span><span> </span><span>%>%</span><span>
</span><span>ggplot</span><span>(</span><span>aes</span><span>(</span><span>average</span><span>,</span><span> </span><span>color</span><span> </span><span>=</span><span> </span><span>cluster</span><span>))</span><span> </span><span>+</span><span>
</span><span>geom_density</span><span>()</span></code></pre><p></p>
<p>Well, that doesn’t look like much of a division- they have basically the same density! That’s OK: one of the nice features of expectation-maximization is that we don’t actually have to start with good clusters to end up with a good result.</p>
<p>We’ll now write a function for fitting a beta-binomial distribution using maximum likelihood estimation (and the <code>dbetabinom.ab</code> function from the VGAM package). This is a process we’ve done in multiple posts before, including the <a href="http://varianceexplained.org/r/empirical_bayes_baseball/">appendix of one of the first ones</a>. We’re just encapsulating it into a function.</p>
<pre><code><span>library</span><span>(</span><span>VGAM</span><span>)</span><span>
</span><span>fit_bb_mle</span><span> </span><span>&lt;-</span><span> </span><span>function</span><span>(</span><span>x</span><span>,</span><span> </span><span>n</span><span>)</span><span> </span><span>{</span><span>
</span><span># dbetabinom.ab is the likelihood function for a beta-binomial
</span><span> </span><span># using n, alpha and beta as parameters
</span><span> </span><span>ll</span><span> </span><span>&lt;-</span><span> </span><span>function</span><span>(</span><span>alpha</span><span>,</span><span> </span><span>beta</span><span>)</span><span> </span><span>{</span><span>
</span><span>-</span><span>sum</span><span>(</span><span>dbetabinom.ab</span><span>(</span><span>x</span><span>,</span><span> </span><span>n</span><span>,</span><span> </span><span>alpha</span><span>,</span><span> </span><span>beta</span><span>,</span><span> </span><span>log</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>))</span><span>
</span><span>}</span><span>
</span><span>m</span><span> </span><span>&lt;-</span><span> </span><span>stats4</span><span>::</span><span>mle</span><span>(</span><span>ll</span><span>,</span><span> </span><span>start</span><span> </span><span>=</span><span> </span><span>list</span><span>(</span><span>alpha</span><span> </span><span>=</span><span> </span><span>3</span><span>,</span><span> </span><span>beta</span><span> </span><span>=</span><span> </span><span>10</span><span>),</span><span> </span><span>method</span><span> </span><span>=</span><span> </span><span>&quot;L-BFGS-B&quot;</span><span>,</span><span>
</span><span>lower</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>0.001</span><span>,</span><span> </span><span>.001</span><span>))</span><span>
</span><span>ab</span><span> </span><span>&lt;-</span><span> </span><span>stats4</span><span>::</span><span>coef</span><span>(</span><span>m</span><span>)</span><span>
</span><span>data_frame</span><span>(</span><span>alpha</span><span> </span><span>=</span><span> </span><span>ab</span><span>[</span><span>1</span><span>],</span><span> </span><span>beta</span><span> </span><span>=</span><span> </span><span>ab</span><span>[</span><span>2</span><span>],</span><span> </span><span>number</span><span> </span><span>=</span><span> </span><span>length</span><span>(</span><span>x</span><span>))</span><span>
</span><span>}</span></code></pre><p>(The <code>number</code> column I added will be useful in the next step). For example, here are the alpha and beta chosen for the entire data as a whole:</p>
<pre><code><span>fit_bb_mle</span><span>(</span><span>starting_data</span><span>$</span><span>H</span><span>,</span><span> </span><span>starting_data</span><span>$</span><span>AB</span><span>)</span></code></pre><pre><code>## # A tibble: 1 × 3
##   alpha  beta number
##   &lt;dbl> &lt;dbl>  &lt;int>
## 1  12.8  45.5   3209</code></pre><p>But now we’re working with a mixture model. This time, we’re going to fit the model within each of our (randomly assigned) clusters:</p>
<pre><code><span>fits</span><span> </span><span>&lt;-</span><span> </span><span>starting_data</span><span> </span><span>%>%</span><span>
</span><span>group_by</span><span>(</span><span>cluster</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>do</span><span>(</span><span>fit_bb_mle</span><span>(</span><span>.</span><span>$</span><span>H</span><span>,</span><span> </span><span>.</span><span>$</span><span>AB</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>ungroup</span><span>()</span><span>
</span><span>fits</span></code></pre><pre><code>## # A tibble: 2 × 4
##   cluster alpha  beta number
##    &lt;fctr> &lt;dbl> &lt;dbl>  &lt;int>
## 1       A  12.1  43.3   1559
## 2       B  13.6  47.9   1650</code></pre><p>Another component of this model is the prior probability that a player is in cluster A or cluster B, which we set to 50-50 when we were assigning random clusters. We can estimate our new iteration of this based on the total number of assignments in each group, which is why we included the <code>number</code> column:</p>
<pre><code><span>fits</span><span> </span><span>&lt;-</span><span> </span><span>fits</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>prior</span><span> </span><span>=</span><span> </span><span>number</span><span> </span><span>/</span><span> </span><span>sum</span><span>(</span><span>number</span><span>))</span><span>
</span><span>fits</span></code></pre><pre><code>## # A tibble: 2 × 5
##   cluster alpha  beta number prior
##    &lt;fctr> &lt;dbl> &lt;dbl>  &lt;int> &lt;dbl>
## 1       A  12.1  43.3   1559 0.486
## 2       B  13.6  47.9   1650 0.514</code></pre><p>Much as the within-cluster densities only changed a little, the priors only changed a little as well. This was the maximization step: find the maximum likelihood parameters (in this case, two alpha/beta values, and a per-cluster probability), pretending we knew the assignments.</p>
<h3>Expectation</h3>
<p>We now have a distribution for each cluster. It’s worth noting that these are pretty similar distributions, and that neither is a good fit to the data.</p>
<p></p>
<p>However, notice that due to a small random difference, cluster B is <strong>slightly</strong> more likely than cluster A for batting averages above about .2, and vice versa below .2.</p>
<p>Consider therefore that each player has a likelihood it would have been generated from cluster A, and a likelihood it would have been generated from cluster B (being sure to weight each by the prior probability of being in A or B):</p>
<pre><code><span>crosses</span><span> </span><span>&lt;-</span><span> </span><span>starting_data</span><span> </span><span>%>%</span><span>
</span><span>select</span><span>(</span><span>-</span><span>cluster</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>crossing</span><span>(</span><span>fits</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>likelihood</span><span> </span><span>=</span><span> </span><span>prior</span><span> </span><span>*</span><span> </span><span>VGAM</span><span>::</span><span>dbetabinom.ab</span><span>(</span><span>H</span><span>,</span><span> </span><span>AB</span><span>,</span><span> </span><span>alpha</span><span>,</span><span> </span><span>beta</span><span>))</span><span>
</span><span>crosses</span></code></pre><pre><code>## # A tibble: 6,418 × 11
##     playerID               name     H    AB average cluster alpha  beta
##        &lt;chr>              &lt;chr> &lt;int> &lt;int>   &lt;dbl>  &lt;fctr> &lt;dbl> &lt;dbl>
## 1  abbotje01        Jeff Abbott    11    42  0.2619       A  12.1  43.3
## 2  abbotje01        Jeff Abbott    11    42  0.2619       B  13.6  47.9
## 3  abbotji01         Jim Abbott     2    21  0.0952       A  12.1  43.3
## 4  abbotji01         Jim Abbott     2    21  0.0952       B  13.6  47.9
## 5  abbotku01        Kurt Abbott   475  1860  0.2554       A  12.1  43.3
## 6  abbotku01        Kurt Abbott   475  1860  0.2554       B  13.6  47.9
## 7  abbotky01        Kyle Abbott     3    31  0.0968       A  12.1  43.3
## 8  abbotky01        Kyle Abbott     3    31  0.0968       B  13.6  47.9
## 9  abercre01 Reggie Abercrombie    86   386  0.2228       A  12.1  43.3
## 10 abercre01 Reggie Abercrombie    86   386  0.2228       B  13.6  47.9
## # ... with 6,408 more rows, and 3 more variables: number &lt;int>,
## #   prior &lt;dbl>, likelihood &lt;dbl></code></pre><p>For example, consider Jeff Abbott, who got 11 hits out of 42 at-bats. He had a 4.35% chance of getting that if he were in cluster A, but a 4.76% chance if he were in cluster B. For that reason (even though it’s a small difference), we’ll put him in B. Similarly we’ll put Kyle Abbott in cluster A: 3/31 was more likely to come from that distribution.</p>
<p>We can do that for every player using <code>group_by</code> and <code>top_n</code>:</p>
<pre><code><span>assignments</span><span> </span><span>&lt;-</span><span> </span><span>starting_data</span><span> </span><span>%>%</span><span>
</span><span>select</span><span>(</span><span>-</span><span>cluster</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>crossing</span><span>(</span><span>fits</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>likelihood</span><span> </span><span>=</span><span> </span><span>prior</span><span> </span><span>*</span><span> </span><span>VGAM</span><span>::</span><span>dbetabinom.ab</span><span>(</span><span>H</span><span>,</span><span> </span><span>AB</span><span>,</span><span> </span><span>alpha</span><span>,</span><span> </span><span>beta</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>group_by</span><span>(</span><span>playerID</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>top_n</span><span>(</span><span>1</span><span>,</span><span> </span><span>likelihood</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>ungroup</span><span>()</span><span>
</span><span>assignments</span></code></pre><pre><code>## # A tibble: 3,209 × 11
##     playerID               name     H    AB average cluster alpha  beta
##        &lt;chr>              &lt;chr> &lt;int> &lt;int>   &lt;dbl>  &lt;fctr> &lt;dbl> &lt;dbl>
## 1  abbotje01        Jeff Abbott    11    42  0.2619       B  13.6  47.9
## 2  abbotji01         Jim Abbott     2    21  0.0952       B  13.6  47.9
## 3  abbotku01        Kurt Abbott   475  1860  0.2554       B  13.6  47.9
## 4  abbotky01        Kyle Abbott     3    31  0.0968       A  12.1  43.3
## 5  abercre01 Reggie Abercrombie    86   386  0.2228       B  13.6  47.9
## 6  abnersh01        Shawn Abner   110   531  0.2072       B  13.6  47.9
## 7  abreubo01        Bobby Abreu  1607  5395  0.2979       B  13.6  47.9
## 8  abreuto01         Tony Abreu   129   509  0.2534       B  13.6  47.9
## 9  acevejo01       Jose Acevedo     8   101  0.0792       A  12.1  43.3
## 10 aceveju01       Juan Acevedo     6    65  0.0923       A  12.1  43.3
## # ... with 3,199 more rows, and 3 more variables: number &lt;int>,
## #   prior &lt;dbl>, likelihood &lt;dbl></code></pre><p>That’s the expectation step: <strong>assigning each person to the most likely cluster</strong>. How do our assignments look after that?</p>
<pre><code><span>ggplot</span><span>(</span><span>assignments</span><span>,</span><span> </span><span>aes</span><span>(</span><span>average</span><span>,</span><span> </span><span>fill</span><span> </span><span>=</span><span> </span><span>cluster</span><span>))</span><span> </span><span>+</span><span>
</span><span>geom_histogram</span><span>()</span></code></pre><p></p>
<p>Something really important happened here: even though the two beta models we’d fit were very similar, we still split up the data rather neatly. Generally batters with a higher average ended up in cluster B, while batters with a lower average were in cluster A. (Note that due to B having a slightly higher prior probability, it was possible for players with a low average- but also a low AB- to be assigned to cluster B).</p>
<h3>Expectation-Maximization</h3>
<p>The above two steps got to a better set of assignments than our original, random ones. But there’s no reason to believe these are as good as we can get. So we <strong>repeat</strong> the two steps, choosing new parameters for each distribution in the mixture and then making new assignments each time.</p>
<p>For example, now that we’ve reassigned each player’s cluster, we could re-fit the beta-binomial with the new assignments. Those distributions would look like this:</p>
<p></p>
<p>Unlike our first model fit, we can see that cluster A and cluster B have diverged a lot. Now we can take those parameters and perform a new estimation step. Generally we will do this multiple times, as an iterative process. This is the heart of an expectation-maximization algorithm, where we switch between assigning clusters (expectation) and fitting the model from those clusters (maximization).</p>
<pre><code><span>set.seed</span><span>(</span><span>1337</span><span>)</span><span>
</span><span>iterate_em</span><span> </span><span>&lt;-</span><span> </span><span>function</span><span>(</span><span>state</span><span>,</span><span> </span><span>...</span><span>)</span><span> </span><span>{</span><span>
</span><span>fits</span><span> </span><span>&lt;-</span><span> </span><span>state</span><span>$</span><span>assignments</span><span> </span><span>%>%</span><span>
</span><span>group_by</span><span>(</span><span>cluster</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>do</span><span>(</span><span>mutate</span><span>(</span><span>fit_bb_mle</span><span>(</span><span>.</span><span>$</span><span>H</span><span>,</span><span> </span><span>.</span><span>$</span><span>AB</span><span>),</span><span> </span><span>number</span><span> </span><span>=</span><span> </span><span>nrow</span><span>(</span><span>.</span><span>)))</span><span> </span><span>%>%</span><span>
</span><span>ungroup</span><span>()</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>prior</span><span> </span><span>=</span><span> </span><span>number</span><span> </span><span>/</span><span> </span><span>sum</span><span>(</span><span>number</span><span>))</span><span>
</span><span>assignments</span><span> </span><span>&lt;-</span><span> </span><span>assignments</span><span> </span><span>%>%</span><span>
</span><span>select</span><span>(</span><span>playerID</span><span>:</span><span>average</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>crossing</span><span>(</span><span>fits</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>likelihood</span><span> </span><span>=</span><span> </span><span>prior</span><span> </span><span>*</span><span> </span><span>VGAM</span><span>::</span><span>dbetabinom.ab</span><span>(</span><span>H</span><span>,</span><span> </span><span>AB</span><span>,</span><span> </span><span>alpha</span><span>,</span><span> </span><span>beta</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>group_by</span><span>(</span><span>playerID</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>top_n</span><span>(</span><span>1</span><span>,</span><span> </span><span>likelihood</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>ungroup</span><span>()</span><span>
</span><span>list</span><span>(</span><span>assignments</span><span> </span><span>=</span><span> </span><span>assignments</span><span>,</span><span>
</span><span>fits</span><span> </span><span>=</span><span> </span><span>fits</span><span>)</span><span>
</span><span>}</span><span>
</span><span>library</span><span>(</span><span>purrr</span><span>)</span><span>
</span><span>iterations</span><span> </span><span>&lt;-</span><span> </span><span>accumulate</span><span>(</span><span>1</span><span>:</span><span>5</span><span>,</span><span> </span><span>iterate_em</span><span>,</span><span> </span><span>.init</span><span> </span><span>=</span><span> </span><span>list</span><span>(</span><span>assignments</span><span> </span><span>=</span><span> </span><span>starting_data</span><span>))</span></code></pre><p>Here I used the <code>accumulate</code> function from the <code>purrr</code> package, which is useful for running data through the same function repeatedly and keeping intermediate states. I haven’t seen others use this tidy approach to EM algorithms, and there are <a href="http://ase.tufts.edu/gsc/gradresources/guidetomixedmodelsinr/mixed%20model%20guide.html?utm_source=dlvr.it&utm_medium=twitter">existing R approaches to mixture models</a>.<a href="http://varianceexplained.org/#fn:mixture">2</a> But I like this approach both because it’s transparent about what we’re doing in each iteration, and because our iterations are now combined in a tidy format, which is convenient to summarize and visualize.</p>
<p>For example, how did our assignments change over the course of the iteration?</p>
<p></p>
<p>We notice that only the first few iterations led to a shift in the assignments, after which it appears to converge. Similarly, how did the estimated beta distributions change over these iterations?</p>
<pre><code><span>fit_iterations</span><span> </span><span>&lt;-</span><span> </span><span>iterations</span><span> </span><span>%>%</span><span>
</span><span>map_df</span><span>(</span><span>&quot;fits&quot;</span><span>,</span><span> </span><span>.id</span><span> </span><span>=</span><span> </span><span>&quot;iteration&quot;</span><span>)</span><span>
</span><span>fit_iterations</span><span> </span><span>%>%</span><span>
</span><span>crossing</span><span>(</span><span>x</span><span> </span><span>=</span><span> </span><span>seq</span><span>(</span><span>.001</span><span>,</span><span> </span><span>.4</span><span>,</span><span> </span><span>.001</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>density</span><span> </span><span>=</span><span> </span><span>prior</span><span> </span><span>*</span><span> </span><span>dbeta</span><span>(</span><span>x</span><span>,</span><span> </span><span>alpha</span><span>,</span><span> </span><span>beta</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>ggplot</span><span>(</span><span>aes</span><span>(</span><span>x</span><span>,</span><span> </span><span>density</span><span>,</span><span> </span><span>color</span><span> </span><span>=</span><span> </span><span>iteration</span><span>,</span><span> </span><span>group</span><span> </span><span>=</span><span> </span><span>iteration</span><span>))</span><span> </span><span>+</span><span>
</span><span>geom_line</span><span>()</span><span> </span><span>+</span><span>
</span><span>facet_wrap</span><span>(</span><span>~</span><span> </span><span>cluster</span><span>)</span></code></pre><p></p>
<p>This confirms that it took about three iterations to converge, and then stayed about the same after that. Also notice that in the process, cluster B got much more likely than cluster A, which makes sense since there are more non-pitchers than pitchers in the dataset.</p>
<h3>Assigning players to clusters</h3>
<p>We now have some final parameters for each cluster:</p>
<pre><code>## # A tibble: 2 × 6
##   iteration cluster alpha  beta number prior
##       &lt;chr>  &lt;fctr> &lt;dbl> &lt;dbl>  &lt;int> &lt;dbl>
## 1         5       A  43.0   312    740 0.231
## 2         5       B  98.3   292   2469 0.769</code></pre><p>How would we assign players to clusters, and get a posterior probability that the player belongs to that cluster? Well, let’s arbitrarily pick the six players that each batted exactly 100 times:</p>
<pre><code><span>batter_100</span><span> </span><span>&lt;-</span><span> </span><span>career</span><span> </span><span>%>%</span><span>
</span><span>filter</span><span>(</span><span>AB</span><span> </span><span>==</span><span> </span><span>100</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>arrange</span><span>(</span><span>average</span><span>)</span><span>
</span><span>batter_100</span></code></pre><pre><code>## # A tibble: 6 × 8
##    playerID            name   bats     H    AB  year average isPitcher
##       &lt;chr>           &lt;chr> &lt;fctr> &lt;int> &lt;int> &lt;dbl>   &lt;dbl>     &lt;lgl>
## 1 dejesjo01   Jose de Jesus      R    11   100  1990    0.11      TRUE
## 2 nicasju01    Juan Nicasio      R    12   100  2012    0.12      TRUE
## 3 mahonmi02    Mike Mahoney      R    18   100  2002    0.18     FALSE
## 4 cancero01 Robinson Cancel      R    20   100  2007    0.20     FALSE
## 5 buschmi01      Mike Busch      R    22   100  1996    0.22     FALSE
## 6 shealry01     Ryan Shealy      R    32   100  2006    0.32     FALSE</code></pre><p>Where would we classify each of them? Well, we’d consider the likelihood each would get the number of hits they did if they were a pitcher (cluster A) or a non-pitcher (cluster B):</p>
<p></p>
<p>By Bayes’ Theorem, we can simply use the ratio of one likelihood (say, A in red) to the sum of the two likelihoods to get the posterior probability:</p>
<p></p>
<p>Based on this, we feel confident that Juan Nicasio and Jose de Jesus are pitchers, and that the others probably aren’t. And we’d be right! (Check out the <code>isPitcher</code> column in the <code>batter_100</code> table above).</p>
<p>This allows us to assign all players in the dataset to one of the two clusters.</p>
<pre><code><span>career_likelihoods</span><span> </span><span>&lt;-</span><span> </span><span>career</span><span> </span><span>%>%</span><span>
</span><span>filter</span><span>(</span><span>AB</span><span> </span><span>></span><span> </span><span>20</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>crossing</span><span>(</span><span>final_parameters</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>likelihood</span><span> </span><span>=</span><span> </span><span>prior</span><span> </span><span>*</span><span> </span><span>VGAM</span><span>::</span><span>dbetabinom.ab</span><span>(</span><span>H</span><span>,</span><span> </span><span>AB</span><span>,</span><span> </span><span>alpha</span><span>,</span><span> </span><span>beta</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>group_by</span><span>(</span><span>playerID</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>posterior</span><span> </span><span>=</span><span> </span><span>likelihood</span><span> </span><span>/</span><span> </span><span>sum</span><span>(</span><span>likelihood</span><span>))</span><span>
</span><span>career_assignments</span><span> </span><span>&lt;-</span><span> </span><span>career_likelihoods</span><span> </span><span>%>%</span><span>
</span><span>top_n</span><span>(</span><span>1</span><span>,</span><span> </span><span>posterior</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>ungroup</span><span>()</span></code></pre><p>Since we know whether each player actually is a pitcher or not, we can also get a <a href="https://en.wikipedia.org/wiki/Confusion_matrix">confusion matrix</a>. How many pitchers were accidentally assigned to cluster B, and how many non-pitchers were assigned to cluster A? In this case we’ll look only at the ones for which we had at least 80% confidence in our classification.</p>
<pre><code><span>career_assignments</span><span> </span><span>%>%</span><span>
</span><span>filter</span><span>(</span><span>posterior</span><span> </span><span>></span><span> </span><span>.8</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>count</span><span>(</span><span>isPitcher</span><span>,</span><span> </span><span>cluster</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>spread</span><span>(</span><span>cluster</span><span>,</span><span> </span><span>n</span><span>)</span></code></pre><pre><code>## Source: local data frame [2 x 3]
## Groups: isPitcher [2]
## 
##   isPitcher     A     B
## *     &lt;lgl> &lt;int> &lt;int>
## 1     FALSE    23  2026
## 2      TRUE   493   157</code></pre><p>Not bad, considering the only information we used was the batting average- and note that we didn’t even use data on who were pitchers to train the model, but just let the clusters define themselves.</p>
<p>It looks like we were a lot more likely to call a pitcher a non-pitcher than vice versa. There’s a lot more we could do to examine this model, how well calibrated its posterior estimates are, and what kinds of pitchers may be mistaken for non-pitchers (e.g. good batters who pitched only a few times), but we won’t consider them in this post.</p>
<h3>Empirical bayes shrinkage with a mixture model</h3>
<p>We’ve gone to all this work posterior probabilities of each player’s assignments. How can we use this in <a href="http://varianceexplained.org/r/empirical_bayes_baseball/">empirical Bayes shrinkage</a>, or with the other methods we’ve described in this series?</p>
<p>Well, consider that all of our other methods have worked because the posterior was another beta distribution (thanks to the beta being the conjugate prior of the binomial). However, now that each point might belong to one of two beta distributions, our posterior will be a mixture of betas. This mixture is made up of the posterior from each cluster, weighted by the probability the point belongs to that cluster.</p>
<p>For example, consider the six players who had exactly 100 at-bats. Their posterior distributions would look like this:</p>
<pre><code><span>batting_data</span><span> </span><span>&lt;-</span><span> </span><span>career_likelihoods</span><span> </span><span>%>%</span><span>
</span><span>ungroup</span><span>()</span><span> </span><span>%>%</span><span>
</span><span>filter</span><span>(</span><span>AB</span><span> </span><span>==</span><span> </span><span>100</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>name</span><span> </span><span>=</span><span> </span><span>paste0</span><span>(</span><span>name</span><span>,</span><span> </span><span>&quot; (&quot;</span><span>,</span><span> </span><span>H</span><span>,</span><span> </span><span>&quot;/&quot;</span><span>,</span><span> </span><span>AB</span><span>,</span><span> </span><span>&quot;)&quot;</span><span>),</span><span>
</span><span>name</span><span> </span><span>=</span><span> </span><span>reorder</span><span>(</span><span>name</span><span>,</span><span> </span><span>H</span><span>),</span><span>
</span><span>alpha1</span><span> </span><span>=</span><span> </span><span>H</span><span> </span><span>+</span><span> </span><span>alpha</span><span>,</span><span>
</span><span>beta1</span><span> </span><span>=</span><span> </span><span>AB</span><span> </span><span>-</span><span> </span><span>H</span><span> </span><span>+</span><span> </span><span>beta</span><span>)</span><span>
</span><span>batting_data</span><span> </span><span>%>%</span><span>
</span><span>crossing</span><span>(</span><span>x</span><span> </span><span>=</span><span> </span><span>seq</span><span>(</span><span>0</span><span>,</span><span> </span><span>.4</span><span>,</span><span> </span><span>.001</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>posterior_density</span><span> </span><span>=</span><span> </span><span>posterior</span><span> </span><span>*</span><span> </span><span>dbeta</span><span>(</span><span>x</span><span>,</span><span> </span><span>alpha1</span><span>,</span><span> </span><span>beta1</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>group_by</span><span>(</span><span>name</span><span>,</span><span> </span><span>x</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>summarize</span><span>(</span><span>posterior_density</span><span> </span><span>=</span><span> </span><span>sum</span><span>(</span><span>posterior_density</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>ggplot</span><span>(</span><span>aes</span><span>(</span><span>x</span><span>,</span><span> </span><span>posterior_density</span><span>,</span><span> </span><span>color</span><span> </span><span>=</span><span> </span><span>name</span><span>))</span><span> </span><span>+</span><span>
</span><span>geom_line</span><span>(</span><span>show.legend</span><span> </span><span>=</span><span> </span><span>FALSE</span><span>)</span><span> </span><span>+</span><span>
</span><span>geom_vline</span><span>(</span><span>aes</span><span>(</span><span>xintercept</span><span> </span><span>=</span><span> </span><span>average</span><span>),</span><span> </span><span>data</span><span> </span><span>=</span><span> </span><span>batting_data</span><span>,</span><span> </span><span>lty</span><span> </span><span>=</span><span> </span><span>2</span><span>)</span><span> </span><span>+</span><span>
</span><span>facet_wrap</span><span>(</span><span>~</span><span> </span><span>name</span><span>)</span><span> </span><span>+</span><span>
</span><span>labs</span><span>(</span><span>x</span><span> </span><span>=</span><span> </span><span>&quot;Batting average (actual average shown as dashed line)&quot;</span><span>,</span><span>
</span><span>y</span><span> </span><span>=</span><span> </span><span>&quot;Posterior density after updating&quot;</span><span>)</span></code></pre><p></p>
<p>For example, we are pretty sure that Jose de Jesus and Juan Nicasio are part of the “pitcher” cluster, so that makes up most of their posterior mass, and all of Ryan Shealy’s density is in the “non-pitcher” cluster. However, we’re pretty split on Mike Mahoney- he could be a pitcher who is unusually good at batting, or a non-pitcher who is unusually bad.</p>
<p>Can we perform shrinkage like we did in that early post? If our goal is still to find the mean of each posterior, then yes! Thanks to <a href="https://en.wikipedia.org/wiki/Expected_value#Linearity">linearity of expected value</a>, we can simply average the two distribution means, weighing each by the probability the player belongs to that cluster:</p>
<pre><code><span>eb_shrinkage</span><span> </span><span>&lt;-</span><span> </span><span>career_likelihoods</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>shrunken_average</span><span> </span><span>=</span><span> </span><span>(</span><span>H</span><span> </span><span>+</span><span> </span><span>alpha</span><span>)</span><span> </span><span>/</span><span> </span><span>(</span><span>AB</span><span> </span><span>+</span><span> </span><span>alpha</span><span> </span><span>+</span><span> </span><span>beta</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>group_by</span><span>(</span><span>playerID</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>summarize</span><span>(</span><span>shrunken_average</span><span> </span><span>=</span><span> </span><span>sum</span><span>(</span><span>posterior</span><span> </span><span>*</span><span> </span><span>shrunken_average</span><span>))</span></code></pre><p>For example, we are pretty sure that Jose de Jesus and Juan Nicasio are part of the “pitcher” cluster, which means they mostly get shrunken towards that center. We are quite certain Ryan Shealy is not a pitcher, so he’ll be updated based entirely on that distribution.</p>
<p></p>
<p>Notice that instead of shrinking towards a single value, the batting averages are now shrunken towards two centers: one higher value for the non-pitcher cluster, one smaller value for the pitcher cluster. Ones that are exactly in between don’t really get shrunken in either direction- they’re “pulled equally”.</p>
<p>(For simplicity’s sake I didn’t use our <a href="http://varianceexplained.org/r/beta_binomial_baseball/">beta-binomial regression</a> approach in this model, but that could easily be added to take into account the relationship between average and AB).</p>
<p>Not all of the methods we’ve used in this series are so easy to adapt to a multimodal distribution. For example, a <a href="http://varianceexplained.org/r/credible_intervals_baseball/">credible interval</a> is ambiguous in a multimodal distribution (see <a href="https://en.wikipedia.org/wiki/Credible_interval">here</a> for more), and we’d need to rethink our approach to <a href="http://varianceexplained.org/r/bayesian_ab_baseball/">Bayesian A/B testing</a>. But since we do have a posterior distribution for each player- even though it’s not a beta- we’d be able to face these challenges.</p>
<h3>What’s Next: Combining into an R package</h3>
<p>We’ve introduced a number of statistical techniques in this series for dealing with empirical Bayes, the beta-binomial relationship, A/B testing, etc. Since I’ve provided the code at each stage, you could certainly apply these methods to your own data (as <a href="http://juliasilge.com/blog/Bayesian-Blues/">some already have!</a>). However, you’d probably find yourself copying and pasting a rather large amount of code, which isn’t necessarily something you want to do every time you run into this kind of binomial data (it takes you out of the flow of your own data analysis).</p>
<p>In my next post I’ll introduce an R package for performing empirical Bayes on binomial data that encapsulates many of the analyses we’ve performed in this series. These statistical techniques aren’t original to me (most can be found in an elementary Bayesian statistics textbook), but providing them in a convenient R package can still be useful for the community. We’ll also go over some of the choices one makes in developing a statistics package in R, particularly one that is compatible with the tidy tools we’ve been using.</p>
<div>
<ol><li>
<p>I’m changing this analysis slightly to look only at National League batters since the year 1980. Why? Because National League pitchers are required to bat (while American League pitchers don’t in typical games), and because looking at modern batters helps reduce the noise within each group. <a href="http://varianceexplained.org/#fnref:subset">↩</a></p>
</li>
<li>
<p>I should note that I haven’t yet gotten an existing R mixture model package to work with a beta-binomial model like we do in this post If you have an approach you’d recommend, please share it in the comments or on Twitter! <a href="http://varianceexplained.org/#fnref:mixture">↩</a></p>
</li>
</ol></div>