<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>
</ul><p>Suppose you were a scout hiring a new baseball player, and were choosing between two that have had 100 at-bats each:</p>
<ul><li>A left-handed batter who has hit <strong>30 hits / 100 at-bats</strong></li>
<li>A right-handed batter who has hit <strong>30 hits / 100 at-bats</strong></li>
</ul><p>Who would you guess was the better batter?</p>
<p>This seems like a silly question: they both have the same exact batting record. But what if I told you that historically, left-handed batters are slightly better hitters than right-handed? How could you incorporate that evidence?</p>
<p>In <a href="http://varianceexplained.org/r/beta_binomial_baseball">the last post</a>, we used the method of <strong>beta binomial regression</strong> to incorporate information (specifically the number of at-bats a player had) into a per-player prior distribution. We did this to correct a bias of the algorithm, but we could do a lot with this method: in particular, we can include other factors that might change our prior expectations of a player.</p>
<p>These are particular applications of <a href="https://en.wikipedia.org/wiki/Bayesian_hierarchical_modeling">Bayesian hierarchical modeling</a>, where the priors for each player are not fixed, but rather depend on other latent variables. In our empirical Bayesian approach to hierarchical modeling, we’ll estimate this prior using beta binomial regression, and then apply it to each batter. This strategy is useful in many applications beyond baseball- for example, if I were analyzing ad clickthrough rates on a website, I may notice that different countries have different clickthrough rates, and therefore fit different priors for each. This could influence our Bayesian <a href="http://varianceexplained.org/r/bayesian_ab_baseball/">A/B tests</a>, <a href="http://varianceexplained.org/r/credible_intervals_baseball/">credible intervals</a>, and more.</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/2016-10-12-hierarchical_bayes_baseball.Rmd">here</a>).</p>
<pre><code><span>library</span><span>(</span><span>gamlss</span><span>)</span><span>
</span><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># Grab career batting average of non-pitchers
# (allow players that have pitched &lt;= 3 games, like Ty Cobb)
</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>%>%</span><span>
</span><span>anti_join</span><span>(</span><span>pitchers</span><span>,</span><span> </span><span>by</span><span> </span><span>=</span><span> </span><span>&quot;playerID&quot;</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># 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>Based on our <a href="http://varianceexplained.org/r/beta_binomial_baseball">last post</a>, we perform beta binomial regression using the gamlss package. This fits a model that allows the mean batting average to depend on the number of at-bats a player has had.</p>
<pre><code><span>library</span><span>(</span><span>gamlss</span><span>)</span><span>
</span><span>fit</span><span> </span><span>&lt;-</span><span> </span><span>gamlss</span><span>(</span><span>cbind</span><span>(</span><span>H</span><span>,</span><span> </span><span>AB</span><span> </span><span>-</span><span> </span><span>H</span><span>)</span><span> </span><span>~</span><span> </span><span>log</span><span>(</span><span>AB</span><span>),</span><span>
</span><span>data</span><span> </span><span>=</span><span> </span><span>dplyr</span><span>::</span><span>select</span><span>(</span><span>career</span><span>,</span><span> </span><span>-</span><span>bats</span><span>),</span><span>
</span><span>family</span><span> </span><span>=</span><span> </span><span>BB</span><span>(</span><span>mu.link</span><span> </span><span>=</span><span> </span><span>&quot;identity&quot;</span><span>))</span></code></pre><p>The prior and can then be computed for each player based on and a dispersion parameter :</p>
<pre><code><span>career_eb</span><span> </span><span>&lt;-</span><span> </span><span>career</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>mu</span><span> </span><span>=</span><span> </span><span>fitted</span><span>(</span><span>fit</span><span>,</span><span> </span><span>&quot;mu&quot;</span><span>),</span><span>
</span><span>sigma</span><span> </span><span>=</span><span> </span><span>fitted</span><span>(</span><span>fit</span><span>,</span><span> </span><span>&quot;sigma&quot;</span><span>),</span><span>
</span><span>alpha0</span><span> </span><span>=</span><span> </span><span>mu</span><span> </span><span>/</span><span> </span><span>sigma</span><span>,</span><span>
</span><span>beta0</span><span> </span><span>=</span><span> </span><span>(</span><span>1</span><span> </span><span>-</span><span> </span><span>mu</span><span>)</span><span> </span><span>/</span><span> </span><span>sigma</span><span>,</span><span>
</span><span>alpha1</span><span> </span><span>=</span><span> </span><span>alpha0</span><span> </span><span>+</span><span> </span><span>H</span><span>,</span><span>
</span><span>beta1</span><span> </span><span>=</span><span> </span><span>beta0</span><span> </span><span>+</span><span> </span><span>AB</span><span> </span><span>-</span><span> </span><span>H</span><span>,</span><span>
</span><span>estimate</span><span> </span><span>=</span><span> </span><span>alpha1</span><span> </span><span>/</span><span> </span><span>(</span><span>alpha1</span><span> </span><span>+</span><span> </span><span>beta1</span><span>))</span></code></pre><p>Now we’ve corrected for one confounding factor, . One important aspect of this prediction is that it won’t be useful when we’ve just hired a “rookie” player, and we’re wondering what his batting average will be. This observed variable is based on a player’s entire career, such that a low number is evidence that a player didn’t have much of a chance to bat. (If we wanted to make a prediction, we’d have to consider the distribution of possible ’s the player could end up with and integrate over that, which is beyond the scope of this post).</p>
<p>But there’s some information we can use even at the start of a player’s career. Part of the philosophy of the Bayesian approach is to bring our prior expectations in mathematically. Let’s try doing that with some factors that influence batting success.</p>
<h3>Right- and left- handed batters</h3>
<p>It’s well known in sabermetrics that left-handed batters <a href="http://www.hardballtimes.com/the-advantage-of-batting-left-handed/">tend to bat slightly better</a>. (In fact, the general belief is that left-handed batters have an advantage against right-handed pitchers, but since most pitchers historically have been right-handed this evens out to an advantage). The Lahman dataset provides that information in the <code>bats</code> column: in the above code, I retained it as part of the <code>career</code> dataset.</p>
<pre><code><span>career</span><span> </span><span>%>%</span><span>
</span><span>count</span><span>(</span><span>bats</span><span>)</span></code></pre><pre><code>## # A tibble: 4 × 2
##     bats     n
##   &lt;fctr> &lt;int>
## 1      B   815
## 2      L  2864
## 3      R  5869
## 4     NA   840</code></pre><p>These letters represent “Both” (<a href="https://en.wikipedia.org/wiki/Switch_hitter">switch hitters</a>), “Left”, and “Right”, respectively. One interesting feature is that while the ratio of righties to lefties is about 9-to-1 in the general population, in professional baseball it is only 2-to-1. Managers like to hire left-handed batters- in itself, this is some evidence of a left-handed advantage! We also see that there are a number of batters (mostly from earlier in the game’s history) that we don’t have handedness information for. We’ll filter them out of this analysis.</p>
<p>Incorporating this as a predictor is as simple as adding <code>bats</code> to the formula in the <code>gamlss</code> call (our beta-binomial regression):</p>
<pre><code><span># relevel to set right-handed batters as the baseline
</span><span>career2</span><span> </span><span>&lt;-</span><span> </span><span>career</span><span> </span><span>%>%</span><span>
</span><span>filter</span><span>(</span><span>!</span><span>is.na</span><span>(</span><span>bats</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>bats</span><span> </span><span>=</span><span> </span><span>relevel</span><span>(</span><span>bats</span><span>,</span><span> </span><span>&quot;R&quot;</span><span>))</span><span>
</span><span>fit2</span><span> </span><span>&lt;-</span><span> </span><span>gamlss</span><span>(</span><span>cbind</span><span>(</span><span>H</span><span>,</span><span> </span><span>AB</span><span> </span><span>-</span><span> </span><span>H</span><span>)</span><span> </span><span>~</span><span> </span><span>log</span><span>(</span><span>AB</span><span>)</span><span> </span><span>+</span><span> </span><span>bats</span><span>,</span><span>
</span><span>data</span><span> </span><span>=</span><span> </span><span>career2</span><span>,</span><span>
</span><span>family</span><span> </span><span>=</span><span> </span><span>BB</span><span>(</span><span>mu.link</span><span> </span><span>=</span><span> </span><span>&quot;identity&quot;</span><span>))</span></code></pre><p>We can then look at the coefficients:</p>
<pre><code><span>library</span><span>(</span><span>broom</span><span>)</span><span>
</span><span>tidy</span><span>(</span><span>fit2</span><span>)</span></code></pre><pre><code>##   parameter        term estimate std.error statistic  p.value
## 1        mu (Intercept)  0.14077  0.001626      86.6 0.00e+00
## 2        mu     log(AB)  0.01516  0.000219      69.1 0.00e+00
## 3        mu       batsB -0.00108  0.000990      -1.1 2.73e-01
## 4        mu       batsL  0.01011  0.000634      15.9 1.75e-56
## 5     sigma (Intercept) -6.37789  0.023299    -273.7 0.00e+00</code></pre><p>According to our beta-binomial regression, there is indeed a statistically significant advantage to being left-handed, with lefties hitting about 1% more often. This may seem like a small effect, but over the course of multiple games it could certainly make a difference. In contrast, there’s apparently no detectable advantage to being able to bat with both hands. (This surprised me- does anyone know a reason this might be?)</p>
<p>For our empirical Bayes estimation, this means every combination of handedness and AB now has its own prior:</p>
<p></p>
<p>We can use these priors to improve our estimates of each player, by effectively giving a natural advantage to each left-handed batter. Note that this prior can still easily be overcome by enough evidence. For example, consider our hypothetical pair of battters from the introduction, where each has a 30% success rate, but where one is left-handed and one right-handed. If the batters had few at-bats, we’d guess that the left-handed batter was better, but the posterior for the two will converge as AB increases:</p>
<pre><code><span>crossing</span><span>(</span><span>bats</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>&quot;L&quot;</span><span>,</span><span> </span><span>&quot;R&quot;</span><span>),</span><span>
</span><span>AB</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>10</span><span>,</span><span> </span><span>100</span><span>,</span><span> </span><span>1000</span><span>,</span><span> </span><span>10000</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>augment</span><span>(</span><span>fit2</span><span>,</span><span> </span><span>newdata</span><span> </span><span>=</span><span> </span><span>.</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>H</span><span> </span><span>=</span><span> </span><span>.3</span><span> </span><span>*</span><span> </span><span>AB</span><span>,</span><span>
</span><span>alpha0</span><span> </span><span>=</span><span> </span><span>.fitted</span><span> </span><span>/</span><span> </span><span>sigma</span><span>,</span><span>
</span><span>beta0</span><span> </span><span>=</span><span> </span><span>(</span><span>1</span><span> </span><span>-</span><span> </span><span>.fitted</span><span>)</span><span> </span><span>/</span><span> </span><span>sigma</span><span>,</span><span>
</span><span>alpha1</span><span> </span><span>=</span><span> </span><span>alpha0</span><span> </span><span>+</span><span> </span><span>H</span><span>,</span><span>
</span><span>beta1</span><span> </span><span>=</span><span> </span><span>beta0</span><span> </span><span>+</span><span> </span><span>AB</span><span> </span><span>-</span><span> </span><span>H</span><span>,</span><span>
</span><span>estimate</span><span> </span><span>=</span><span> </span><span>alpha1</span><span> </span><span>/</span><span> </span><span>(</span><span>alpha1</span><span> </span><span>+</span><span> </span><span>beta1</span><span>),</span><span>
</span><span>conf.low</span><span> </span><span>=</span><span> </span><span>qbeta</span><span>(</span><span>.025</span><span>,</span><span> </span><span>alpha1</span><span>,</span><span> </span><span>beta1</span><span>),</span><span>
</span><span>conf.high</span><span> </span><span>=</span><span> </span><span>qbeta</span><span>(</span><span>.975</span><span>,</span><span> </span><span>alpha1</span><span>,</span><span> </span><span>beta1</span><span>),</span><span>
</span><span>record</span><span> </span><span>=</span><span> </span><span>paste</span><span>(</span><span>H</span><span>,</span><span> </span><span>AB</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>ggplot</span><span>(</span><span>aes</span><span>(</span><span>estimate</span><span>,</span><span> </span><span>record</span><span>,</span><span> </span><span>color</span><span> </span><span>=</span><span> </span><span>bats</span><span>))</span><span> </span><span>+</span><span>
</span><span>geom_point</span><span>()</span><span> </span><span>+</span><span>
</span><span>geom_errorbarh</span><span>(</span><span>aes</span><span>(</span><span>xmin</span><span> </span><span>=</span><span> </span><span>conf.low</span><span>,</span><span> </span><span>xmax</span><span> </span><span>=</span><span> </span><span>conf.high</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;Estimate w/ 95% credible interval&quot;</span><span>,</span><span>
</span><span>y</span><span> </span><span>=</span><span> </span><span>&quot;Batting record&quot;</span><span>,</span><span>
</span><span>color</span><span> </span><span>=</span><span> </span><span>&quot;Batting hand&quot;</span><span>)</span></code></pre><p></p>
<h3>Over time</h3>
<p>One of the most dramatic pieces of information we’ve “swept under the rug” in our analysis is the time period when each player was active. It’s absurd to expect that players in the 1880s would have the same ranges of batting averages as players today, and we should take that into account in our estimates. I thus included <code>year = mean(yearID)</code> in the summary of each player when I constructed this data, to summarize the time period of each player using the midpoint of their career.</p>
<p>Could we simply fit a linear model with respect to year (<code>~ log10(AB) + bats + year</code>)? Well, before we fit a model we should always look at a graph. A boxplot comparing decades is a good start (here I’m looking only at players with >= 500 AB in their career):</p>
<p></p>
<p>Well, there’s certainly a trend over time, but there’s nothing linear about it: batting averages have both risen and fallen across time. If you’re interested in baseball history and not just Bayesian statistics, you may notice that this graph marks the “power struggle” between offense and defense:</p>
<ul><li>The rise in the 1920s and 1930s marks <a href="https://en.wikipedia.org/wiki/Dead-ball_era#The_end_of_the_dead-ball_era">the end of the dead-ball era</a>, where hitting, especially home runs, became a more important part of the game</li>
<li>The batting average “cools off” as pitchers adjust their technique, especially when <a href="http://www.thisgreatgame.com/1968-baseball-history.html">the range of the strike zone was increased in 1961</a></li>
<li>Batting average rose again in the 1970s thanks to the <a href="https://en.wikipedia.org/wiki/Designated_hitter">designated hitter rule</a>, where pitchers (in one of the two main leagues) were no longer required to bat</li>
<li>It looks like batting averages may <a href="http://www.latimes.com/sports/la-sp-mlb-declining-offense-20150405-story.html">again be drifting downward</a></li>
</ul><p>In any case, we certainly can’t fit a simple linear trend here. We could instead fit a <a href="http://varianceexplained.org/Spline_interpolation">natural cubic spline</a> using the <a href="http://www.inside-r.org/r-doc/splines/ns">ns function</a>:<a href="http://varianceexplained.org/#fn:df">1</a></p>
<pre><code><span>library</span><span>(</span><span>splines</span><span>)</span><span>
</span><span>fit3</span><span> </span><span>&lt;-</span><span> </span><span>gamlss</span><span>(</span><span>cbind</span><span>(</span><span>H</span><span>,</span><span> </span><span>AB</span><span> </span><span>-</span><span> </span><span>H</span><span>)</span><span> </span><span>~</span><span> </span><span>0</span><span> </span><span>+</span><span> </span><span>ns</span><span>(</span><span>year</span><span>,</span><span> </span><span>df</span><span> </span><span>=</span><span> </span><span>5</span><span>)</span><span> </span><span>+</span><span> </span><span>bats</span><span> </span><span>+</span><span> </span><span>log</span><span>(</span><span>AB</span><span>),</span><span>
</span><span>data</span><span> </span><span>=</span><span> </span><span>career2</span><span>,</span><span>
</span><span>family</span><span> </span><span>=</span><span> </span><span>BB</span><span>(</span><span>mu.link</span><span> </span><span>=</span><span> </span><span>&quot;identity&quot;</span><span>))</span></code></pre><p>(If you’re not familiar with splines, don’t worry about them- what’s important is that even in a linear model, we can include nonlinear trends)</p>
<p>We now have a prior for each year, handedness, and number of at-bats. For example, here’s the distributions for a hypothetical player with AB = 1000:</p>
<p></p>
<p>Note that those intervals don’t represent uncertainty about our trend: they represent the 95% range in prior batting averages. Each combination of year and left/right handedness is a beta distribution, of which we’re seeing just one cross-section.</p>
<p>One of the implicit assumptions of the above model is that the effect of left-handedness hasn’t changed over time. But this may not be true! We can change the formula to allow an <a href="https://en.wikipedia.org/wiki/Interaction_(statistics)">interaction term</a> <code>ns(year, 5) * bats</code>, which lets the effect of handedness change over time:</p>
<pre><code><span>fit4</span><span> </span><span>&lt;-</span><span> </span><span>gamlss</span><span>(</span><span>cbind</span><span>(</span><span>H</span><span>,</span><span> </span><span>AB</span><span> </span><span>-</span><span> </span><span>H</span><span>)</span><span> </span><span>~</span><span> </span><span>0</span><span> </span><span>+</span><span> </span><span>ns</span><span>(</span><span>year</span><span>,</span><span> </span><span>5</span><span>)</span><span> </span><span>*</span><span> </span><span>bats</span><span> </span><span>+</span><span> </span><span>log</span><span>(</span><span>AB</span><span>),</span><span>
</span><span>data</span><span> </span><span>=</span><span> </span><span>career2</span><span>,</span><span>
</span><span>family</span><span> </span><span>=</span><span> </span><span>BB</span><span>(</span><span>mu.link</span><span> </span><span>=</span><span> </span><span>&quot;identity&quot;</span><span>))</span></code></pre><p>The priors now look like:</p>
<p></p>
<p>Interesting- we can now see that the gap between left-handed and right-handed batters has been closing since the start of the game, such that today the gap has basically completely disappeared. This suggests that managers and coaches may have learned how to deal with left-handed batters. Inspired by this, I might wonder if the percentage of games started by left-handed pitchers has been going up over time, and I notice that it has:</p>
<p></p>
<p>This is one thing I like about fitting hierarchical models like these- they don’t just improve your estimation, they can also give you insights into your data.</p>
<p>Let’s go back to those two batters with a record of 30 hits out of 100 at-bats. We’ve now seen that this would be a different question in different years. Let’s consider what it would look like in three different years, each 50 years apart:</p>
<pre><code><span>players</span><span> </span><span>&lt;-</span><span> </span><span>crossing</span><span>(</span><span>year</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>1915</span><span>,</span><span> </span><span>1965</span><span>,</span><span> </span><span>2015</span><span>),</span><span>
</span><span>bats</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>&quot;L&quot;</span><span>,</span><span> </span><span>&quot;R&quot;</span><span>),</span><span>
</span><span>H</span><span> </span><span>=</span><span> </span><span>30</span><span>,</span><span>
</span><span>AB</span><span> </span><span>=</span><span> </span><span>100</span><span>)</span><span>
</span><span>players_posterior</span><span> </span><span>&lt;-</span><span> </span><span>players</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>mu</span><span> </span><span>=</span><span> </span><span>predict</span><span>(</span><span>fit4</span><span>,</span><span> </span><span>what</span><span> </span><span>=</span><span> </span><span>&quot;mu&quot;</span><span>,</span><span> </span><span>newdata</span><span> </span><span>=</span><span> </span><span>players</span><span>),</span><span>
</span><span>sigma</span><span> </span><span>=</span><span> </span><span>predict</span><span>(</span><span>fit4</span><span>,</span><span> </span><span>what</span><span> </span><span>=</span><span> </span><span>&quot;sigma&quot;</span><span>,</span><span> </span><span>newdata</span><span> </span><span>=</span><span> </span><span>players</span><span>,</span><span> </span><span>type</span><span> </span><span>=</span><span> </span><span>&quot;response&quot;</span><span>),</span><span>
</span><span>alpha0</span><span> </span><span>=</span><span> </span><span>mu</span><span> </span><span>/</span><span> </span><span>sigma</span><span>,</span><span>
</span><span>beta0</span><span> </span><span>=</span><span> </span><span>(</span><span>1</span><span> </span><span>-</span><span> </span><span>mu</span><span>)</span><span> </span><span>/</span><span> </span><span>sigma</span><span>,</span><span>
</span><span>alpha1</span><span> </span><span>=</span><span> </span><span>alpha0</span><span> </span><span>+</span><span> </span><span>H</span><span>,</span><span>
</span><span>beta1</span><span> </span><span>=</span><span> </span><span>beta0</span><span> </span><span>+</span><span> </span><span>AB</span><span> </span><span>-</span><span> </span><span>H</span><span>)</span><span>
</span><span>players_posterior</span></code></pre><pre><code>## # A tibble: 6 × 10
##    year  bats     H    AB    mu   sigma alpha0 beta0 alpha1 beta1
##   &lt;dbl> &lt;chr> &lt;dbl> &lt;dbl> &lt;dbl>   &lt;dbl>  &lt;dbl> &lt;dbl>  &lt;dbl> &lt;dbl>
## 1  1915     L    30   100 0.230 0.00141    163   545    193   615
## 2  1915     R    30   100 0.211 0.00141    150   559    180   629
## 3  1965     L    30   100 0.208 0.00141    148   561    178   631
## 4  1965     R    30   100 0.201 0.00141    142   566    172   636
## 5  2015     L    30   100 0.212 0.00141    150   558    180   628
## 6  2015     R    30   100 0.212 0.00141    150   558    180   628</code></pre><p>How do these posterior distributions (the <code>alpha1</code> and <code>beta1</code> we chose) differ?</p>
<p></p>
<p>If this comparison had happened in 1915, you may have wanted to pick the left-handed batter. We wouldn’t have been sure he was better (we’d need <a href="http://varianceexplained.org/r/bayesian_ab_baseball/">to apply one of these methods</a> for that), but it was more likely than not. But today, there’d be basically no reason to: left- versus right- handedness has almost no extra information.</p>
<h4>Note: Uncertainty in hyperparameters</h4>
<p>We’ve followed the philosophy of empirical Bayes so far: we fit hyperparameters (, , or our coefficients for time and handedness) for our model using maximum likelihood (e.g. beta-binomial regression), and then use that as the prior for each of our observations.</p>
<blockquote class="twitter-tweet"><p dir="ltr" lang="en">Empirical Bayes in a nutshell: Estimate priors like a frequentist then carry out a Bayesian analysis.</p>— Data Science Fact (@DataSciFact) <a href="https://twitter.com/DataSciFact/status/741333031110225920">June 10, 2016</a></blockquote>
<p>There’s a problem I’ve been ignoring so far with the empirical Bayesian approach, which is that there’s uncertainty in these hyperparameters as well. When we come up with an alpha and beta, or come up with particular coefficients over time, we are treating those as fixed knowledge, as if these are the priors we “entered” the experiment with. But in fact each of these parameters were chosen from this same data, and in fact each comes with a confidence interval that we’re entirely ignoring. This is sometimes called the “double-dipping” probably among critics of empirical Bayes.</p>
<p>This wasn’t a big deal when we were estimating just and for the overall dataset: we had so much data, and were estimating so few parameters, that we could feel good about the approach. But now that we’re fitting this many parameters, we’re pushing it. Actually quantifying this, and choosing methods robust to the charge of “double-dipping”, involves Bayesian methods outside the scope of this series. But I wanted to note that this post reaches the edge of what empirical Bayes can be used for.</p>
<h3>What’s Next: Mixture models</h3>
<p>We’ve been treating our overall distribution of batting averages as a beta distribution. 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?</p>
<p>We’ve been filtering out pitchers during this analysis. But when we leave them in, the data looks a lot less like a beta. The dashed density curve represents the beta distribution we would naively fit to this data.</p>
<p></p>
<p>We can see that batting averages with pitchers incldued isn’t made up of a single beta distribution- it’s more like two separate ones mixed together. Imagine that you didn’t know which players were pitchers,<a href="http://varianceexplained.org/#fn:pitchers">2</a> 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 my next post I’m going to introduce <a href="https://en.wikipedia.org/wiki/Mixture_model">mixture models</a>, treating the distribution of batting averages as a <strong>mixture of two beta-binomial distributions</strong> and estimating 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 see that mixture models are still a good fit for the empirical Bayes framework, and show how to calculate a posterior probability for the cluster each player belongs to.</p>
<h3>Footnotes</h3>
<div>
<ol><li>
<p>Why 5 degrees of freedom? Not very scientific- I just tried a few and picked one that roughly captured the shapes we saw in the boxplots. If you have too few degrees of freedom you can’t capture the complex trend we’re seeing here, but if you have too many you’ll overfit to noise in your data. <a href="http://varianceexplained.org/#fnref:df">↩</a></p>
</li>
<li>
<p>Admittedly it’s not very realistic to assume we don’t know which players are pitchers. But this gives us a great example of fitting a mixture model, which will be an important element of this series. <a href="http://varianceexplained.org/#fnref:pitchers">↩</a></p>
</li>
</ol></div>