{"id":2902,"date":"2023-02-05T22:20:58","date_gmt":"2023-02-05T22:20:58","guid":{"rendered":"http:\/\/optimumsportsperformance.com\/blog\/?p=2902"},"modified":"2023-02-07T15:38:10","modified_gmt":"2023-02-07T15:38:10","slug":"bayesian-priors-for-categorical-variables-using-rstanarm","status":"publish","type":"post","link":"https:\/\/optimumsportsperformance.com\/blog\/bayesian-priors-for-categorical-variables-using-rstanarm\/","title":{"rendered":"Bayesian Priors for Categorical Variables using rstanarm"},"content":{"rendered":"<p>Continuing with more Bayesian data analysis using the {<strong>rstanarm<\/strong>} package, today walk through the ways of setting priors on categorical variables.<\/p>\n<p><strong>NOTE: <\/strong>Priors are a pretty controversial piece in Bayesian statistics and one of the arguments people make against Bayesian data analysis. Thus, I&#8217;ll also show what happens when you are overly bullish with your priors\/<\/p>\n<p>The full code is accessible on my <strong><span style=\"color: #0000ff;\"><a style=\"color: #0000ff;\" href=\"https:\/\/github.com\/pw2\/Bayes-Priors-using-rstanarm\/blob\/main\/Bayesian%20priors%20for%20categorical%20variables%20using%20rstanarm.R\">GITHUB page<\/a><\/span><\/strong>.<\/p>\n<p><span style=\"text-decoration: underline;\"><strong>Load Packages &amp; Data<\/strong><\/span><\/p>\n<p>We are going to use the\u00a0<strong>mtcars<\/strong> data set from R. The cylinder variable (cyl) is read in as a numeric but it only have three levels (4, 6, 8), therefore, we will convert it to a categorical variable and treat it as such for the analysis.<\/p>\n<p>We are going to build a model that estimates miles per gallon (mpg) from the number of cylinders a\u00a0 car has. So, we will start by looking at the mean and standard deviation of mpg for each level of cyl.<\/p>\n<pre class=\"brush: r; title: ; notranslate\" title=\"\">\r\n## Bayesian priors for categorical variables using rstanarm\r\n\r\nlibrary(rstanarm)\r\nlibrary(tidyverse)\r\nlibrary(patchwork)\r\n\r\n### Data -----------------------------------------------------------------\r\nd &lt;- mtcars %&gt;%\r\n  select(mpg, cyl, disp) %&gt;%\r\n  mutate(cyl = as.factor(cyl),\r\n         cyl6 = ifelse(cyl == &quot;6&quot;, 1, 0),\r\n         cyl8 = ifelse(cyl == &quot;8&quot;, 1, 0))\r\n\r\nd %&gt;% \r\n  head()\r\n\r\nd %&gt;%\r\n  group_by(cyl) %&gt;%\r\n  summarize(avg = mean(mpg),\r\n            SD = sd(mpg))\r\n<\/pre>\n<p><a href=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-12.33.58-PM.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-2903\" src=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-12.33.58-PM.png\" alt=\"\" width=\"361\" height=\"270\" srcset=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-12.33.58-PM.png 468w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-12.33.58-PM-300x224.png 300w\" sizes=\"auto, (max-width: 361px) 100vw, 361px\" \/><\/a><\/p>\n<p><span style=\"text-decoration: underline;\"><strong>Fit the model using Ordinary Least Squares regression<\/strong><\/span><\/p>\n<p>Before constructing our Bayesian model, we fit the model as a basic regression model to see what the output looks like.<\/p>\n<pre class=\"brush: r; title: ; notranslate\" title=\"\">\r\n## Linear regression ------------------------------------------------------\r\nfit_lm &lt;- lm(mpg ~ cyl, data = d)\r\nsummary(fit_lm)\r\n<\/pre>\n<p><a href=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-12.41.00-PM.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-2904\" src=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-12.41.00-PM.png\" alt=\"\" width=\"433\" height=\"347\" srcset=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-12.41.00-PM.png 924w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-12.41.00-PM-300x240.png 300w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-12.41.00-PM-768x615.png 768w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-12.41.00-PM-624x500.png 624w\" sizes=\"auto, (max-width: 433px) 100vw, 433px\" \/><\/a><\/p>\n<ul>\n<li>The model suggests there is a relationship between mpg and cyl number<\/li>\n<li>A 4 cyl car is represented as the intercept. Consequently, the intercept represents the average mpg we would expect from a 4 cylinder car.<\/li>\n<li>The other two coefficients (cyl6 and cyl8) represent the difference in mpg for each of those cylinder cars relative to a 4 cylinder car (the model intercept). So, a 6 cylinder can, on average, will get 7 less mpg than a 4 cylinder car while an 8 cylinder car will, on average, get about 12 less mpg&#8217;s than a 4 cylinder car.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline;\"><strong>Bayesian regression with rstanarm &#8212; No priors specified<\/strong><\/span><\/p>\n<p>First, let&#8217;s fit the model with no priors specified (using the functions default priors) to see what sort of output we get.<\/p>\n<pre class=\"brush: r; title: ; notranslate\" title=\"\">\r\n## setting no prior info\r\nstan_glm(mpg ~ cyl, data = d) %&gt;%\r\n  summary(digits = 3)\r\n<\/pre>\n<p><a href=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-12.54.50-PM.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-2905\" src=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-12.54.50-PM.png\" alt=\"\" width=\"465\" height=\"415\" srcset=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-12.54.50-PM.png 788w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-12.54.50-PM-300x268.png 300w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-12.54.50-PM-768x686.png 768w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-12.54.50-PM-624x557.png 624w\" sizes=\"auto, (max-width: 465px) 100vw, 465px\" \/><\/a><\/p>\n<ul>\n<li>The output is a little different than the OLS model. First we see that there are no p-values (in the spirit of Bayes analysis!).<\/li>\n<li>We do find that the model coefficients are basically the same as those produce with the OLS model and even the standard deviation is similar to the standard errors from above.<\/li>\n<li>Instead of p-values for each coefficient we get 80% credible intervals.<\/li>\n<li>The sigma value at the bottom corresponds to the residual standard error we got in our OLS model.<\/li>\n<\/ul>\n<p>Basically, the default priors <em>&#8220;let the data speak&#8221;<\/em> and reported back the underlying relationship in the empirical data.<\/p>\n<p><span style=\"text-decoration: underline;\"><strong>Setting Some Priors<\/strong><\/span><\/p>\n<p>Next, we can set some minimally informative priors. These priors wont contain much information and, therefore, will be highly influenced by minimal amounts of evidence regarding the underlying relationship that is present in the data.<\/p>\n<p>To set priors on independent variables in <strong>rstanarm<\/strong> we need to create an element to store them. We have two independent variables (cyl6 and cyl8), both requiring priors (we will set the prior for the intercept and the model sigma in the function directly). To set these priors we need to determine a distribution, a mean value (location), and a standard deviation (scale). We add these values into the distribution function in the order in which they will appear in the model. So, there will be a vector of location that is specific to cyl6 and cyl8 and then a vector of scale that is also specific to cyl6 and cyl8, in that order.<\/p>\n<pre class=\"brush: r; title: ; notranslate\" title=\"\">\r\n## Setting priors\r\nind_var_priors &lt;- normal(location = c(0, 0), scale = c(10, 10))\r\n<\/pre>\n<p>Next, we run the model.<\/p>\n<pre class=\"brush: r; title: ; notranslate\" title=\"\">\r\nfit_rstan &lt;- stan_glm(mpg ~ cyl, \r\n                      prior = ind_var_priors,\r\n                      prior_intercept = normal(15, 8),\r\n                      prior_aux = cauchy(0, 3),\r\n                      data = d)\r\n\r\n# fit_rstan\r\nsummary(fit_rstan, digits = 3)\r\n<\/pre>\n<p><a href=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.07.18-PM.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-2906\" src=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.07.18-PM.png\" alt=\"\" width=\"505\" height=\"369\" srcset=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.07.18-PM.png 790w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.07.18-PM-300x219.png 300w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.07.18-PM-768x562.png 768w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.07.18-PM-624x457.png 624w\" sizes=\"auto, (max-width: 505px) 100vw, 505px\" \/><\/a><\/p>\n<p>Again, this model is not so different from the one that used the default priors (or from the findings of the OLS model). But, our priors were uninformative.<\/p>\n<p>One note I&#8217;ll make, before proceeding on, is that you can do this a different way and simply dummy code the categorical variables and enter those dummies directly into the model, setting priors on each, and you will obtain the same result. The below code dummy codes cyl6 and cyl8 as booleans (1 = yes, 0 = no) so when both are 0 we effectively are left with cyl4 (the model intercept).<\/p>\n<pre class=\"brush: r; title: ; notranslate\" title=\"\">\r\n############################################################################################\r\n#### Alternate approach to coding the priors -- dummy coding the categorical variables #####\r\n############################################################################################\r\n\r\nd2 &lt;- d %&gt;%\r\n  mutate(cyl6 = ifelse(cyl == &quot;6&quot;, 1, 0),\r\n         cyl8 = ifelse(cyl == &quot;8&quot;, 1, 0))\r\n\r\nsummary(lm(mpg ~ cyl6 + cyl8, data = d2))\r\n\r\nstan_glm(mpg ~ cyl, \r\n         prior = ind_var_priors,\r\n         prior_intercept = normal(15, 8),\r\n         prior_aux = cauchy(0, 3),\r\n         data = d2) %&gt;%\r\n  summary()\r\n\r\n###########################################################################################\r\n###########################################################################################\r\n<\/pre>\n<p>Okay, back to our regularly scheduled programming&#8230;..<\/p>\n<p>So what&#8217;s the big deal?? The model coefficients are relatively the same as with OLS. Why go through the trouble? Two reasons:<\/p>\n<ol>\n<li>Producing the posterior distribution of model coefficients posterior predictive distribution for the dependent variable allows us to evaluate our uncertainty around each. I&#8217;ve talked a bit about this before (<strong><span style=\"color: #0000ff;\"><a style=\"color: #0000ff;\" href=\"https:\/\/optimumsportsperformance.com\/blog\/making-predictions-with-a-bayesian-regression-model\/\">Making Predictions with a Bayesian Regression Model<\/a><\/span><\/strong>, <strong><span style=\"color: #0000ff;\"><a style=\"color: #0000ff;\" href=\"https:\/\/optimumsportsperformance.com\/blog\/confidence-intervals-vs-prediction-intervals-a-frequentist-bayesian-example\/\">Confidence &amp; Prediction Intervals &#8211; Compare and Contrast Frequentist and Bayesian Approaches<\/a><\/span><\/strong>, and <span style=\"color: #0000ff;\"><strong><a style=\"color: #0000ff;\" href=\"https:\/\/optimumsportsperformance.com\/blog\/approximating-a-bayesian-posterior-prediction\/\">Approximating a Bayesian Posterior with OLS<\/a><\/strong><\/span>).<\/li>\n<li>If we have more information on relationship between mpg and cylinders we can code that in as information the model can use!<\/li>\n<\/ol>\n<p>Let&#8217;s table point 2 for a second and extract out some posterior samples from our Bayesian regression and visualize the uncertainty in the coefficients.<\/p>\n<pre class=\"brush: r; title: ; notranslate\" title=\"\">\r\n# posterior samples\r\npost_rstan &lt;- as.matrix(fit_rstan) %&gt;%\r\n  as.data.frame() %&gt;%\r\n  rename('cyl4' = '(Intercept)')\r\n\r\npost_rstan %&gt;%\r\n  head()\r\n\r\nmu.cyl4 &lt;- post_rstan$cyl4\r\nmu.cyl6 &lt;- post_rstan$cyl4 + post_rstan$cyl6\r\nmu.cyl8 &lt;- post_rstan$cyl4 + post_rstan$cyl8\r\n\r\nrstan_results &lt;- data.frame(mu.cyl4, mu.cyl6, mu.cyl8) %&gt;%\r\n  pivot_longer(cols = everything())\r\n\r\n\r\nrstan_plt &lt;- rstan_results %&gt;%\r\n  left_join(\r\n    \r\n    d %&gt;%\r\n      group_by(cyl) %&gt;%\r\n      summarize(avg = mean(mpg)) %&gt;%\r\n      rename(name = cyl) %&gt;%\r\n      mutate(name = case_when(name == &quot;4&quot; ~ &quot;mu.cyl4&quot;,\r\n                              name == &quot;6&quot; ~ &quot;mu.cyl6&quot;,\r\n                              name == &quot;8&quot; ~ &quot;mu.cyl8&quot;))\r\n    \r\n  ) %&gt;%\r\n  ggplot(aes(x = value, fill = name)) +\r\n  geom_histogram(alpha = 0.4) +\r\n  geom_vline(aes(xintercept = avg),\r\n             color = &quot;black&quot;,\r\n             size = 1.2,\r\n             linetype = &quot;dashed&quot;) +\r\n  facet_wrap(~name, scales = &quot;free_x&quot;) +\r\n  theme_light() +\r\n  theme(strip.background = element_rect(fill = &quot;black&quot;),\r\n        strip.text = element_text(color = &quot;white&quot;, face = &quot;bold&quot;)) +\r\n  ggtitle(&quot;rstanarm&quot;)\r\n\r\nrstan_plt\r\n<\/pre>\n<p><a href=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.20.11-PM.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-large wp-image-2907\" src=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.20.11-PM-1024x801.png\" alt=\"\" width=\"625\" height=\"489\" srcset=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.20.11-PM-1024x801.png 1024w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.20.11-PM-300x235.png 300w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.20.11-PM-768x601.png 768w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.20.11-PM-624x488.png 624w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.20.11-PM.png 1880w\" sizes=\"auto, (max-width: 625px) 100vw, 625px\" \/><\/a><\/p>\n<ul>\n<li>The above plot represents the posterior distribution (the prior combined with the observed data, the likelihood) of the estimated values for each of our cylinder types.<\/li>\n<li>The dashed line is the observed mean mpg for each cylinder type in the data.<\/li>\n<li>The distribution helps give us a good sense of the certainty (or uncertainty) we have in our estimates.<\/li>\n<\/ul>\n<p>We can summarize this uncertainty with point estimates (e.g., mean and median) and measures of spread (e.g., standard deviation, credible intervals, quantile intervals).<\/p>\n<p>&nbsp;<\/p>\n<pre class=\"brush: r; title: ; notranslate\" title=\"\">\r\n# summarize posteriors\r\nmean(mu.cyl4)\r\nsd(mu.cyl4)\r\nqnorm(p = c(0.05, 0.95), mean = mean(mu.cyl4), sd = sd(mu.cyl4))\r\nquantile(mu.cyl4, probs = c(0.05, 0.25, 0.5, 0.75, 0.95))\r\n\r\nmean(mu.cyl6)\r\nsd(mu.cyl6)\r\nqnorm(p = c(0.05, 0.95), mean = mean(mu.cyl6), sd = sd(mu.cyl6))\r\nquantile(mu.cyl6, probs = c(0.05, 0.25, 0.5, 0.75, 0.95))\r\n\r\nmean(mu.cyl8)\r\nsd(mu.cyl8)\r\nqnorm(p = c(0.05, 0.95), mean = mean(mu.cyl8), sd = sd(mu.cyl8))\r\nquantile(mu.cyl8, probs = c(0.05, 0.25, 0.5, 0.75, 0.95))\r\n<\/pre>\n<p>For example, the below information tells us that cyl8 cars will, on average, provide us with ~15.2 mpg with a credible interval between 13.7 and 16.2. The median value is 15.2 with an interquartile range between 14.6 and 15.8 and a 90% quantile interval ranging between 13.7 and 16.6.<a href=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.24.13-PM.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-2908\" src=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.24.13-PM.png\" alt=\"\" width=\"501\" height=\"166\" srcset=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.24.13-PM.png 970w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.24.13-PM-300x100.png 300w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.24.13-PM-768x255.png 768w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.24.13-PM-624x207.png 624w\" sizes=\"auto, (max-width: 501px) 100vw, 501px\" \/><\/a><\/p>\n<p><span style=\"text-decoration: underline;\"><strong>Bullish Priors<\/strong><\/span><\/p>\n<p>As stated earlier, priors are one of the most controversial aspects of Bayesian analysis. Most argue against Bayes because they feel that priors can be be manipulated to fit the data. However, what many fail to recognize is that no analysis is void of human decision-making. All analysis is done by humans and thus there are a number of subjective decisions that need to be made along the way, such as deciding on what to do with outliers, how to handle missing data, the alpha level or level of confidence that you want to test your data against, etc. As I&#8217;ve said before, science isn&#8217;t often as objective as we&#8217;d like it to be. That all said, selecting priors can be done in a variety of ways (aside from just using non-informative priors as we did above). You could get expert opinion, you could use data and observations gained from a pilot study, or you can use information about parameters from previously conducted studies (though be cautious as these also might be bias due to publication issues such as the file drawer phenomenon, p-hacking, and researcher degrees of freedom).<\/p>\n<p>When in doubt, it is probably best to be conservative with your priors. But, let&#8217;s say we sit down with a mechanic and inform him of a study where we are attempting to estimate the miles per gallon for 4, 6, and 8 cylinder cars. We ask him if he can help us with any prior knowledge about the decline in mpg when the number of cylinders increase. The mechanic is very bullish with his prior information and states,<\/p>\n<blockquote><p>&#8220;Of course I know the relationship between cylinders and miles per gallon!! Those 4 cylinder cars tend to be very economical and get around 50 mpg plus or minus 2. I haven&#8217;t seen too many 6 cylinder cars, but my hunch is that there are pretty similar to the 4 cylinder cars. Now 8 cylinder cars&#8230;I do a ton of work on those! Those cars get a bad wrap. In my experience they actually get better gas mileage than the 4 or 6 cylinder cars. My guess would be that they can get nearly 20 miles per gallon more than a 4 cylinder car!&#8221;<\/p><\/blockquote>\n<p>Clearly our mechanic has been sniffing too many fumes in the garage! But, let&#8217;s roll with his beliefs and codify them as prior knowledge for our model and see how such bullish priors influence the model&#8217;s behavior.<\/p>\n<ul>\n<li>We set the intercept to be normally distributed with a mean of 50 and a standard deviation of 2.<\/li>\n<li>Because the mechanic felt like the 6 cylinder car was similar to the 4 cylinder car we will stick suggest that the difference between 6 cylinders and 4 cylinders is normally distributed with a mean of 0 and standard deviation of 2.<\/li>\n<li>Finally, we use the crazy mechanics belief that the 8 cylinder car gets roughly 20 more miles per gallon than the 4 cylinder car and we code its prior to be normally distributed with a mean of 20 and standard deviation of 5.<\/li>\n<\/ul>\n<p>Fit the model&#8230;<\/p>\n<p>&nbsp;<\/p>\n<pre class=\"brush: r; title: ; notranslate\" title=\"\">\r\n## Use wildly different priors ---------------------------------------------------------\r\nind_var_priors2 &lt;- normal(location = c(0, 20), scale = c(10, 5))\r\n\r\nfit_rstan2 &lt;- stan_glm(mpg ~ cyl, \r\n                       prior = ind_var_priors2,\r\n                       prior_intercept = normal(50, 2),\r\n                       prior_aux = cauchy(0, 10),\r\n                       data = d)\r\n\r\nsummary(fit_rstan2, digits = 3)\r\n<\/pre>\n<p><a href=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.48.38-PM.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-2909\" src=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.48.38-PM.png\" alt=\"\" width=\"461\" height=\"379\" srcset=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.48.38-PM.png 708w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.48.38-PM-300x247.png 300w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-1.48.38-PM-624x513.png 624w\" sizes=\"auto, (max-width: 461px) 100vw, 461px\" \/><\/a><br \/>\nWow! Look how much the overly bullish\/informative priors changed the model output.<\/p>\n<ul>\n<li>Our new belief is that a 4 cylinder car gets approximately 39 mpg and the 6 cylinder car gets about 3 more mpg than that, on average.<\/li>\n<li>The 8 cylinder car is now getting roughly 14 mpg more than the 4 cylinder car.<\/li>\n<\/ul>\n<p>The bullish priors have overwhelmed the observed data. Notice that the results are not exact to the prior but the prior, as they are tugged a little bit closer to the observed data, though not by much. For example, we specified the 8 cylinder car to have about 20 mpg over a 4 cylinder car. The observed data doesn&#8217;t indicate this to be true (8 cylinder cars were on average 11 mpg LESS THAN a 4 cylinder car) so the coefficient is getting pulled down slightly, from our prior of 20 to 14.4.<\/p>\n<p>Let&#8217;s plot the posterior distribution.<\/p>\n<pre class=\"brush: r; title: ; notranslate\" title=\"\">\r\n# posterior samples\r\npost_rstan &lt;- as.matrix(fit_rstan2) %&gt;%\r\n  as.data.frame() %&gt;%\r\n  rename('cyl4' = '(Intercept)')\r\n\r\npost_rstan %&gt;%\r\n  head()\r\n\r\nmu.cyl4 &lt;- post_rstan$cyl4\r\nmu.cyl6 &lt;- post_rstan$cyl4 + post_rstan$cyl6\r\nmu.cyl8 &lt;- post_rstan$cyl4 + post_rstan$cyl8\r\n\r\nrstan_results &lt;- data.frame(mu.cyl4, mu.cyl6, mu.cyl8) %&gt;%\r\n  pivot_longer(cols = everything())\r\n\r\n\r\nrstan_plt2 &lt;- rstan_results %&gt;%\r\n  left_join(\r\n    \r\n    d %&gt;%\r\n      group_by(cyl) %&gt;%\r\n      summarize(avg = mean(mpg)) %&gt;%\r\n      rename(name = cyl) %&gt;%\r\n      mutate(name = case_when(name == &quot;4&quot; ~ &quot;mu.cyl4&quot;,\r\n                              name == &quot;6&quot; ~ &quot;mu.cyl6&quot;,\r\n                              name == &quot;8&quot; ~ &quot;mu.cyl8&quot;))\r\n    \r\n  ) %&gt;%\r\n  ggplot(aes(x = value, fill = name)) +\r\n  geom_histogram(alpha = 0.4) +\r\n  geom_vline(aes(xintercept = avg),\r\n             color = &quot;black&quot;,\r\n             size = 1.2,\r\n             linetype = &quot;dashed&quot;) +\r\n  facet_wrap(~name, scales = &quot;free_x&quot;) +\r\n  theme_light() +\r\n  theme(strip.background = element_rect(fill = &quot;black&quot;),\r\n        strip.text = element_text(color = &quot;white&quot;, face = &quot;bold&quot;)) +\r\n  ggtitle(&quot;rstanarm 2&quot;)\r\n\r\nrstan_plt2\r\n<\/pre>\n<p><a href=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-2.04.19-PM.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-large wp-image-2910\" src=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-2.04.19-PM-1024x514.png\" alt=\"\" width=\"625\" height=\"314\" srcset=\"https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-2.04.19-PM-1024x514.png 1024w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-2.04.19-PM-300x151.png 300w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-2.04.19-PM-768x385.png 768w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-2.04.19-PM-624x313.png 624w, https:\/\/optimumsportsperformance.com\/blog\/wp-content\/uploads\/2023\/02\/Screen-Shot-2023-02-05-at-2.04.19-PM.png 1774w\" sizes=\"auto, (max-width: 625px) 100vw, 625px\" \/><\/a><\/p>\n<p>Notice how different these posteriors are than the first Bayesian model. In every case, the predicted mpg from the number of cylinders are all over estimating the observed mpg by cylinder (dashed line).<\/p>\n<p><span style=\"text-decoration: underline;\"><strong>Wrapping Up<\/strong><\/span><\/p>\n<p>Today we went through how to set priors on categorical variables using <strong>rstanarm<\/strong>. Additionally, we talked about some of the skepticism about priors and showed what can happen when the priors you select are too overconfident. The morale of the story is two-fold:<\/p>\n<ol>\n<li>All statistics (Bayes, Frequentist, Machine Learning, etc) have some component of subjectivity as the human doing the analysis has to make decisions about what to do with their data at various points.<\/li>\n<li>Don&#8217;t be overconfident with your priors. Minimally informative priors maybe be useful to allowing us to assert some level of knowledge of the outcome while letting that knowledge be influenced\/updated by what we&#8217;ve just observed.<\/li>\n<\/ol>\n<p>The full code is accessible on my <strong><span style=\"color: #0000ff;\"><a style=\"color: #0000ff;\" href=\"https:\/\/github.com\/pw2\/Bayes-Priors-using-rstanarm\/blob\/main\/Bayesian%20priors%20for%20categorical%20variables%20using%20rstanarm.R\">GITHUB page<\/a><\/span><\/strong>.<\/p>\n<p>If you notice any errors, please reach out!<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Continuing with more Bayesian data analysis using the {rstanarm} package, today walk through the ways of setting priors on categorical variables. NOTE: Priors are a pretty controversial piece in Bayesian statistics and one of the arguments people make against Bayesian data analysis. Thus, I&#8217;ll also show what happens when you are overly bullish with your [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[49,47],"tags":[],"class_list":["post-2902","post","type-post","status-publish","format-standard","hentry","category-bayesian-model-building","category-model-building-in-r"],"_links":{"self":[{"href":"https:\/\/optimumsportsperformance.com\/blog\/wp-json\/wp\/v2\/posts\/2902","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/optimumsportsperformance.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/optimumsportsperformance.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/optimumsportsperformance.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/optimumsportsperformance.com\/blog\/wp-json\/wp\/v2\/comments?post=2902"}],"version-history":[{"count":2,"href":"https:\/\/optimumsportsperformance.com\/blog\/wp-json\/wp\/v2\/posts\/2902\/revisions"}],"predecessor-version":[{"id":2915,"href":"https:\/\/optimumsportsperformance.com\/blog\/wp-json\/wp\/v2\/posts\/2902\/revisions\/2915"}],"wp:attachment":[{"href":"https:\/\/optimumsportsperformance.com\/blog\/wp-json\/wp\/v2\/media?parent=2902"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/optimumsportsperformance.com\/blog\/wp-json\/wp\/v2\/categories?post=2902"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/optimumsportsperformance.com\/blog\/wp-json\/wp\/v2\/tags?post=2902"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}