<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Jesse Fagan, PhD]]></title><description><![CDATA[Social scientist, data scientist, and human.]]></description><link>https://www.jessefagan.com/</link><image><url>https://www.jessefagan.com/favicon.png</url><title>Jesse Fagan, PhD</title><link>https://www.jessefagan.com/</link></image><generator>Ghost 3.18</generator><lastBuildDate>Mon, 11 Jan 2021 17:24:02 GMT</lastBuildDate><atom:link href="https://www.jessefagan.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Automating Middle Management]]></title><description><![CDATA[<p>A talk given to the Ex-AI club at the University of Exeter. 25th of September, 2020.</p><p>Link to the <a href="https://docs.google.com/presentation/d/1Srb5g2XBf0XQ7saIOl_YYw0J6wfNGYGWC4O89a-7tKw/edit?usp=sharing">slides here</a>.</p><p>Organizations are a form of technology primed for disruption. The fundamental roles of human organizations (e.g. coordinate activity, distribute resources, allocate tasks, etc) are quickly being handed over</p>]]></description><link>https://www.jessefagan.com/automating-middle-management/</link><guid isPermaLink="false">5f6daefbeda30d0001fc2843</guid><dc:creator><![CDATA[Jesse Fagan]]></dc:creator><pubDate>Fri, 25 Sep 2020 08:50:33 GMT</pubDate><content:encoded><![CDATA[<p>A talk given to the Ex-AI club at the University of Exeter. 25th of September, 2020.</p><p>Link to the <a href="https://docs.google.com/presentation/d/1Srb5g2XBf0XQ7saIOl_YYw0J6wfNGYGWC4O89a-7tKw/edit?usp=sharing">slides here</a>.</p><p>Organizations are a form of technology primed for disruption. The fundamental roles of human organizations (e.g. coordinate activity, distribute resources, allocate tasks, etc) are quickly being handed over to algorithmic control piece by piece. In this talk I will address the advancement of AI in the domain of middle management and the coming rise of self-driving organizations. In my work on email networks, social network analysis, and natural language processing in organizations I have discovered the accuracy and usefulness of using machine learning to predict employee outcomes. It’s a short step from this research to the deployment of predictive or prescriptive systems which automate key staffing decisions. These changes could lead to a healthier working environment where systems optimize for human well-being, or they could go a different direction in which human needs are sidestepped in the interest of alternative goals. The goal of this talk is to continue this important discussion.<br></p>]]></content:encoded></item><item><title><![CDATA[Bayes from Scratch, Part 2: Bayesian Regression using Grid Search]]></title><description><![CDATA[<p>This is Part 2 in the <em>Bayes from Scratch</em> series. <a href="https://jessefagan.com/bayesian-grid-mean/">Read Part 1 - Bayesian Grid Mean here</a>.</p><p>In Part 1 I wanted to understand how Bayes Theorem could be used to compute the mean for a single variable without using MCMC, instead I used grid search. A brute force</p>]]></description><link>https://www.jessefagan.com/bayes-from-scratch-part-2-bayesian-regression-using-grid-search/</link><guid isPermaLink="false">5f4559c2eda30d0001fc26ba</guid><dc:creator><![CDATA[Jesse Fagan]]></dc:creator><pubDate>Tue, 01 Sep 2020 22:19:26 GMT</pubDate><content:encoded><![CDATA[<p>This is Part 2 in the <em>Bayes from Scratch</em> series. <a href="https://jessefagan.com/bayesian-grid-mean/">Read Part 1 - Bayesian Grid Mean here</a>.</p><p>In Part 1 I wanted to understand how Bayes Theorem could be used to compute the mean for a single variable without using MCMC, instead I used grid search. A brute force method that computes the posterior for a grid of every combination of parameters within some range.</p><h2 id="miles-per-gallon-by-engine-displacement">Miles per Gallon by Engine Displacement</h2><figure class="kg-card kg-image-card"><img src="https://www.jessefagan.com/content/images/2020/08/image.png" class="kg-image"></figure><p></p><p>In Part 2 I'm going to try a regression. We just need to add one new parameter, and a structural equation. Miles-per-gallon <code>mpg</code> is distributed by a normal distribution with mean <code>m</code> and standard deviation <code>s</code>. The mean <code>m</code> is determined by the equation $m = \beta \cdot \text{disp} + \alpha$. The engine displacement variable is centered at the mean, so when <code>disp</code> is 0 the <code>alpha</code> parameter should represent the expected <code>mpg</code> for the average vehicle.</p><p>$$<br>mpg \sim Normal(m, s) \\<br>m = \beta \cdot \text{disp} + \alpha \\<br>\beta \sim Normal(0,2) \\<br>\alpha \sim Normal(18, 3) \\<br>s \sim Uniform(0, 20)<br>$$</p><h2 id="estimating-parameters-using-grid-search">Estimating Parameters using Grid Search</h2><p>When I first attempted this, I had two predictors in the model (thus 4 parameters), for, you know, fun. This was a mistake. I was quickly reminded the curse of dimensionality. I pared it back to one new parameter. My laptop, with 16 GB of ram, can't actually compute a grid with <code>N = 200</code>.</p><pre><code class="language-{r}">N &lt;- 200
g &lt;- expand_grid(alpha = seq(1, 100, length.out = N)
                 , beta = seq(-10, 10, length.out = N)
                 , s = seq(0.1,20, length.out = N))
</code></pre><p>One of the problems with grid searches is you have to specify the bounds the grid <em>a priori</em>. Looking at the plot it's easy to see the slope will be negative, and we already know the mean value of <code>mpg</code> is somewhere between 15 and 25.</p><h3 id="priors-advantages-of-log-probabilities">Priors: Advantages of Log Probabilities</h3><p>The priors are pretty simple. The big difference between this run and the previous is that I'm going to be computing <em>log probabilities</em>. There are two great benefits to using log probabilities 1) floating point values can actually store log probabilities, and 2) we can take advantage of the Product Rule for Logarithms.</p><pre><code class="language-{r}">mpg_alpha_prior &lt;- dnorm(g$alpha, mean = 18, sd = 3, log = TRUE)
mpg_s_prior &lt;- dunif(g$s, min = 0, max = 20, log = TRUE)
mpg_beta_prior &lt;- dnorm(g$beta, mean = 0, sd = 2, log = TRUE)
</code></pre><p>Some of the priors or posterior values in raw probabilities will be teeny tiny - very close to zero. Some of the values can be $10^{-100}$. This can be a real problem for floating point computation. </p><figure class="kg-card kg-image-card"><img src="https://www.jessefagan.com/content/images/2020/09/image.png" class="kg-image"></figure><p>The second advantage is the product rule of logarithms. The sum of two logarithms is equal to the logarithm of a product. Bayes Theorem and probability theory relies the product of probabilities in many places, and by using the log probability we can sum the values instead.</p><p>$$<br>\log_{a} xy = \log_{a} x + \log_{a} y<br>$$</p><h3 id="estimating-the-likelihood">Estimating the Likelihood</h3><p>The most computationally difficult part is computing the likelihood. </p><pre><code class="language-{r}">mm &lt;- cbind(1, dcars$disp) # the model matrix
mpg_log_likelihood &lt;- apply(g, 1, FUN = function(r) {
  params &lt;- as.numeric(r[c('alpha', 'beta')])
  m &lt;- as.numeric(mm %*% params)
  sum(dnorm(mtcars$mpg, mean = m, 
            sd = as.numeric(r['s']), log = TRUE))
})</code></pre><p>The <code>g</code> data frame has all the grid parameter values. I computed the likelihood at each combination of parameters on the grid. First we compute the value of the linear model using matrix multiplication: <code>m &lt;- as.numeric(mm %*% params)</code> The matrix <code>mm</code> is the design matrix with a column of the data for the engine displacement, <code>disp</code>, and a column of 1's for the intercept. Then, using the logarithm product rule, I compute the likelihood for that combination of parameters: <code>sum(dnorm(mtcars$mpg, mean = m, sd = as.numeric(r['s']), log = TRUE))</code>. </p><h3 id="computing-the-posterior">Computing the Posterior</h3><p>Then computing the posterior is pretty simple - the likelihood times the prior. Or in our case - the log likelihood plus the log prior. The raw posterior probability can be computed and normalized after computing the log posterior.</p><pre><code class="language-{r}">d &lt;- g %&gt;% 
  mutate(mpg_ll = mpg_log_likelihood) %&gt;% 
  mutate(post = exp(mpg_log_post) / sum(exp(mpg_log_post)))
</code></pre><h2 id="posterior-checks">Posterior Checks</h2><p>Let's see if this posterior makes sense. If we just randomly sample 1000 lines from the grid data frame and plot the different lines on a plot of the data we get something like this.</p><p><code>i &lt;- sample(1:nrow(d), size = 1000, replace = TRUE)</code></p><figure class="kg-card kg-image-card"><img src="https://www.jessefagan.com/content/images/2020/09/image-3.png" class="kg-image"></figure><p>And when I weight the grid samples based on the posterior probability we get something much more reasonable:</p><pre><code class="language-{r}">i &lt;- sample(1:nrow(d), size = 1000, prob = d$post, replace = TRUE)
# i &lt;- sample(1:nrow(d), size = 1000, replace = TRUE)
ggplot() +
  geom_abline(data = d[i,], aes(slope = beta, intercept = alpha, color = beta),
              alpha = 0.3) +
  scale_color_viridis_c(option = 'B') +
  geom_point(data = dcars, aes(x = disp, y = mpg), ) +
  coord_cartesian(xlim = c(min(dcars$disp), max(dcars$disp))) +
  theme_fivethirtyeight()
</code></pre><figure class="kg-card kg-image-card"><img src="https://www.jessefagan.com/content/images/2020/09/image-4.png" class="kg-image"></figure><h2 id="thoughts">Thoughts</h2><p>My first thought - hey, this works! My second thought -  this is incredibly imprecise and computationally expensive! I did the last few plots on my laptop, so I had to reduce the grid size dramatically compared to my beefy desktop machine. This is a really simple regression and the thought that it can't be computed on a relatively powerful laptop is a good indication that this approach is a bad choice.</p><p>But it shows that using Bayes Theorem to estimate models can be done simply - even if it is expensive. When you learn Bayesian statistics there is often so much tied up in trying to understand MCMC. This approach ignores MCMC entirely. Soon though I will write MCMC from scratch as well and pick it apart.</p>]]></content:encoded></item><item><title><![CDATA[Bayes From Scratch, Part 1: Computing the Posterior Mean using Grid Search]]></title><description><![CDATA[<p>I think the best way to learn new statistical methods is to code them myself from scratch. Crack open the papers and books, read the formulas, and build my own software. I don't plan on making software for release, this is a learning exercise. Here is the roadmap of some</p>]]></description><link>https://www.jessefagan.com/bayesian-grid-mean/</link><guid isPermaLink="false">5ee4b18aaf5680000176675c</guid><dc:creator><![CDATA[Jesse Fagan]]></dc:creator><pubDate>Sat, 13 Jun 2020 11:35:16 GMT</pubDate><media:content url="https://www.jessefagan.com/content/images/2020/06/bayesian_grid_mean.png" medium="image"/><content:encoded><![CDATA[<img src="https://www.jessefagan.com/content/images/2020/06/bayesian_grid_mean.png" alt="Bayes From Scratch, Part 1: Computing the Posterior Mean using Grid Search"><p>I think the best way to learn new statistical methods is to code them myself from scratch. Crack open the papers and books, read the formulas, and build my own software. I don't plan on making software for release, this is a learning exercise. Here is the roadmap of some things I want to figure out in Bayesian statistics:</p><ul><li>Grid search posterior mean</li><li>Grid search posterior regression</li><li>Highest Posterior Density Interval</li><li>Metropolis-Hastings algorithm for Markov Chain Monte Carlo</li><li>Evaluating convergence (Rhat, $\widehat{R}$ and effective sample size, EFF)</li><li>Multilevel models</li><li>Hamiltonian MCMC</li></ul><p>I feel like if I can code those things from scratch I will have a much better understanding of the problems that come up with convergence, or how to interpret results.</p><h2 id="the-data">The data</h2><p>For this, I'm doing a super boring dataset that's built into base-R <em>datasets</em> library: <code>mtcars</code>.   I'm going to compute the mean miles-per-gallon using my prior understanding of what the average miles per gallon should be. So here's the data, there are 32 cases, a mean of 20.09 and median of 19.20. </p><figure class="kg-card kg-image-card"><img src="https://www.jessefagan.com/content/images/2020/06/image-8.png" class="kg-image" alt="Bayes From Scratch, Part 1: Computing the Posterior Mean using Grid Search"></figure><h2 id="grid-search">Grid Search</h2><p>In Richard McElreath's book<sup>[1]</sup> he demonstrates estimating the posterior density of the proportion of the Earth that's covered in water. Kruschke's book<sup>[3]</sup> also does an example with a binomial distribution with one parameter. I quickly realized why they chose this approach rather than computing a Bayesian mean. For a binomial density estimate you only need to know the number of attempts, the number of successes, and the probability of success. Thus it's pretty simple. The data is two numbers and you only have one parameter. But to compute the posterior mean you need two parameters the mean, $\mu$, and the standard deviation, $\sigma$, and the data is the vector of all the measurements of the variable.</p><p>It wasn't clear to me about how to adapt  grid search to two parameters from one. The focus of only one parameter left me with a misconception. Because of the very simple introductions I was reading I thought maybe the $\theta$ in <em>ye olde Bayes rule</em>, seen below, was a single parameter. But it represents all the parameters in the entire model. </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://www.jessefagan.com/content/images/2020/06/image-9.png" class="kg-image" alt="Bayes From Scratch, Part 1: Computing the Posterior Mean using Grid Search"><figcaption>From [3]</figcaption></figure><p>So here is the model I'm going to estimate. The $mpg$ is normally distributed with a mean of $m$ and a standard deviation of $s$. And I have defined some prior distributions for $m$ and $s$ that I discuss m</p><p>$$<br>mpg \sim Normal(m, s) \\<br>m \sim Normal(13, 3) \\<br>s \sim Uniform(0, 20) <br>$$</p><p>Following in McElreath's path (Rethinking, pg 40), we're going to take the grid search steps he outlined, with some minor modifications. </p><ol><li>Define a grid. All the possible combinations of parameters we might want to use in estimating a posterior all laid out in a grid.</li><li>Compute the value of the prior for each pair of parameter values on the grid</li><li>Compute the likelihood at each pair of parameter values.</li><li>Compute the unstandardized posterior at each pair of parameter values by multiplying the prior and likelihood.</li><li>After all that, we standardize the posterior by dividing each value by the sum of all values</li></ol><p>So let's just start with what the grid looks like. It's 100 values between 1 and 100 for the mean. And 100 values between 0.1 and 10 for the standard deviation. Already we are showing some of the downsides of this approach. There are only two parameters, and I'm only taking 100 values, but already this table has 10,000 rows ($100 \times 100$). Also what range should we reasonably choose for the values? These are arbitrary decisions. There are some reasonable values for it, but the values should represent what we expect to be the very extremes of the posterior.</p><pre><code class="language-r">N &lt;- 100
g &lt;- expand_grid(m = seq(1, 100, length.out = N),
            s = seq(0.1,10, length.out = N))</code></pre><pre><code class="language-r">&gt; head(g)
# A tibble: 6 x 2
      m     s
  &lt;dbl&gt; &lt;dbl&gt;
1     1   0.1
2     1   0.2
3     1   0.3
4     1   0.4
5     1   0.5
6     1   0.6</code></pre><h2 id="priors">Priors</h2><p>Bayesian statistics deviates from classical, frequentist statistics in a very key way - it considers prior knowledge of the systems we are studying as part of its calculation.  The choice of the prior can be from any information you may have <em>prior</em> to examining the data.</p><p>The priors have some good information. I choose a mean of 18 for the prior mpg because I had a car that regularly had 18 miles per gallon (now I live in the UK where that would be horrible, but it was somewhat common in the US). A frequentist approach would ignore prior knowledge about how the real world would work. For instance, without having any real values of fuel economy, we know that miles-per-gallon won't be negative. So our prior in this case greatly reduces the chances of seeing that.</p><pre><code class="language-{r}">mpg_m_prior &lt;- dnorm(g$m, mean = 18, sd = 3)
mpg_s_prior &lt;- dunif(g$s, min = 0, max = 20)
</code></pre><p>The prior density is computed for every value of <code>m</code> and <code>s</code> in the grid. </p><figure class="kg-card kg-image-card"><img src="https://www.jessefagan.com/content/images/2020/06/image-10.png" class="kg-image" alt="Bayes From Scratch, Part 1: Computing the Posterior Mean using Grid Search"></figure><figure class="kg-card kg-image-card"><img src="https://www.jessefagan.com/content/images/2020/06/image-11.png" class="kg-image" alt="Bayes From Scratch, Part 1: Computing the Posterior Mean using Grid Search"></figure><p>I think one issue with this prior is that it's probably too strong. In the UK, for instance, my tiny Yaris gets 40 mpg easily. If I had collected data in the UK using my prior knowledge from the US, the prior would push me to the wrong answer.</p><h2 id="likelihood">Likelihood</h2><p>The likelihood is the probability of the data given some parameter values. I got hung up here for some time. None of the books really make it up-front and clear. It wasn't until <a href="https://stats.stackexchange.com/questions/344779/compute-the-likelihood-in-metropolis-hastings-how-does-it-relate-to-a-posterior">I saw a post on Cross Validated </a>that I figure out what to do. I had always understood that the likelihood was the observations, but I didn't know how you could transform that into a distribution that could be multiplied by the prior. So here's what we do:</p><ol><li>Choose two of the parameter values from the grid (the mean and standard deviation)</li><li>For each value of the data compute the probability using the density function using those two parameter values</li><li>Multiply all of these probabilities together</li><li>That's your likelihood probability density estimate for that point in the parameter space, for that pair of the mean and standard deviation</li></ol><p>$$f(\mathbf{Y}|\theta)= \prod_{i=1}^n f(y_i|\theta) $$</p><p>It seems obvious in retrospect how to do this, but it didn't make sense at first.</p><pre><code class="language-{r}">mpg_likelihood &lt;- apply(g, 1, FUN = function(r) {
  prod(dnorm(mtcars$mpg, mean = r['m'], sd = r['s']))
})
</code></pre><p>The R code does exactly what was describe above. It uses the <code>apply</code> function to use each row of the grid table. Then it computes the probability of observing each <code>mpg</code> value we observed if the mean and standard deviation were the values we got from the grid.</p><h3 id="log-probabilities">Log probabilities</h3><p>One thing I found was that the probabilities these functions produce were super itty bitty - even using values that were very close to what the actual values were. This presents some difficult problems with floating point arithmetic.</p><pre><code class="language-r">&gt; prod(dnorm(mtcars$mpg, mean = 18, sd = 7))
[1] 3.767108e-46</code></pre><p>Which is one of the reasons to use <em>log probabilities</em>. When you use the log probability density the values are far more manageable. You also sum each of values instead of multiplying them (as a consequence of the math of logarithms). </p><pre><code class="language-r">&gt; sum(dnorm(mtcars$mpg, mean = 18, sd = 7, log = TRUE))
[1] -104.5926</code></pre><p>However, this isn't explicitly called out in the math of the basic bayesian introductions. I will be doing this from now on, after this experiment.</p><h2 id="the-posterior">The Posterior</h2><p>Now that the likelihood and prior have been computed.... we just multiply them! That creates the unstandardized posterior, then we divide it by the sum of itself. Bam. Posterior.</p><pre><code class="language-{r}">d &lt;- tibble(m = g$m, s = g$s, 
       mpg_m_prior, mpg_s_prior, mpg_likelihood) %&gt;% 
  mutate(mpg_post_unstd = mpg_m_prior * mpg_s_prior * mpg_likelihood) %&gt;% 
  mutate(post = mpg_post_unstd / sum(mpg_post_unstd))
</code></pre><p>And here's a visualization of what that looks like. The posterior here is two-dimensional, so I used <code>geom_tile</code> to get  sense of it.</p><pre><code class="language-{r}">ggplot(d, aes(x = m, y = s, fill = post, z= mpg_post_unstd)) +
  geom_tile() +
  scale_fill_viridis_c() +
  theme_minimal()
</code></pre><figure class="kg-card kg-image-card"><img src="https://www.jessefagan.com/content/images/2020/06/image-12.png" class="kg-image" alt="Bayes From Scratch, Part 1: Computing the Posterior Mean using Grid Search"></figure><p>And the Bayesian mean here is <strong>20</strong>.</p><pre><code class="language-r">&gt; d[which.max(d$post),]
# A tibble: 1 x 7
      m     s mpg_m_prior mpg_s_prior mpg_likelihood mpg_post_unstd   post
  &lt;dbl&gt; &lt;dbl&gt;       &lt;dbl&gt;       &lt;dbl&gt;          &lt;dbl&gt;          &lt;dbl&gt;  &lt;dbl&gt;
1    20   5.9       0.106        0.05       3.43e-45       1.83e-47 0.0201</code></pre><p> The precision of this estimate is restricted by the resolution of the grid. It's exactly 20 because the grid doesn't have values for 20.1 or such.</p><p>I increased <code>N</code> to 1000 instead of 100 (thus there were 1,000,000 combinations of parameter values), and I estimated the mean as <strong>19.8</strong>.</p><pre><code class="language-r">&gt; d[which.max(d$post),]
# A tibble: 1 x 7
      m     s mpg_m_prior mpg_s_prior mpg_likelihood mpg_post_unstd     post
  &lt;dbl&gt; &lt;dbl&gt;       &lt;dbl&gt;       &lt;dbl&gt;          &lt;dbl&gt;          &lt;dbl&gt;    &lt;dbl&gt;
1  19.8  5.94       0.110        0.05       3.34e-45       1.85e-47 0.000199</code></pre><figure class="kg-card kg-image-card"><img src="https://www.jessefagan.com/content/images/2020/06/image-15.png" class="kg-image" alt="Bayes From Scratch, Part 1: Computing the Posterior Mean using Grid Search"></figure><h2 id="highest-posterior-density-interval">Highest Posterior Density Interval</h2><p>The posterior is not a point though - it's a distribution. I just used the highest value of the posterior in the grid to select a point value. This gives us some options, do we choose the maximum? - the median? How do we define the credible interval? That's what I wanted to explore in the next post.</p><p>[1]: McElreath, R. 2020. <strong><em>Statistical rethinking: A Bayesian course with examples in R and Stan</em></strong>. Boca Raton, FL: Chapman &amp; Hall/CRC Press.</p><p>[2]: Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., &amp; Rubin, D. B. (2013). <em>Bayesian data analysis</em>. CRC press.</p><p>[3]: Kruschke, J. (2014). <em>Doing Bayesian data analysis: A tutorial with R, JAGS, and Stan</em>. Academic Press.</p>]]></content:encoded></item></channel></rss>