<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/who-knew-likelihood-functions-could-be-so-pretty/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.rdatagen.net/post/mle-can-be-pretty/"> ouR data generation</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>I just released a new iteration of <code>simstudy</code> (version 0.1.6), which fixes a bug or two and adds several spline related routines (available on <a rel="nofollow" href="https://cran.r-project.org/web/packages/simstudy/index.html" target="_blank">CRAN</a>). The <a rel="nofollow" href="https://www.rdatagen.net/post/generating-non-linear-data-using-b-splines/" target="_blank">previous post</a> focused on using spline curves to generate data, so I won’t repeat myself here. And, apropos of nothing really – I thought I’d take the opportunity to do a simple simulation to briefly explore the likelihood function. It turns out if we generate lots of them, it can be pretty, and maybe provide a little insight.</p>
<p>If a probability density (or mass) function is more or less forward-looking – answering the question of what is the probability of seeing some future outcome based on some known probability model, the likelihood function is essentially backward-looking. The likelihood takes the data as given or already observed – and allows us to assess how likely that outcome was under different assumptions the underlying probability model. While the form of the model is not necessarily in question (normal, Poisson, binomial, etc) – though it certainly should be – the specific values of the parameters that define the location and shape of that distribution are not known. The likelihood function provides a guide as to how the backward-looking probability varies across different values of the distribution’s parameters for a <em>given</em> data set.</p>
<p>We are generally most interested in finding out where the peak of that curve is, because the parameters associated with that point (the maximum likelihood estimates) are often used to describe the “true” underlying data generating process. However, we are also quite interested in the shape of the likelihood curve itself, because that provides information about how certain we can be about our conclusions about the “true” model. In short, a function that has a more clearly defined peak provides more information than one that is pretty flat. When you are climbing Mount Everest, you are pretty sure you know when you reach the peak. But when you are walking across the rolling hills of Tuscany, you can never be certain if you are at the top.</p>
<div>
<h3>The setup</h3>
<p>A likelihood curve is itself a function of the observed data. That is, if we were able to draw different samples of data from a single population, the curves associated with each of those sample will vary. In effect, the function is a random variable. For this simulation, I repeatedly make draws from an underlying known model – in this case a very simple linear model with only one unknown slope parameter – and plot the likelihood function for each dataset set across a range of possible slopes along with the maximum point for each curve.</p>
<p>In this example, I am interested in understanding the relationship between a variable <span>\(X\)</span> and some outcome <span>\(Y\)</span>. In truth, there is a simple relationship between the two:</p>
<p><span>\[ Y_i = 1.5 \times X_i + \epsilon_i \ ,\]</span> where <span>\(\epsilon_i \sim Normal(0, \sigma^2)\)</span>. In this case, we have <span>\(n\)</span> individual observations, so that <span>\(i \in (1,…n)\)</span>. Under this model, the likelihood where we do know <span>\(\sigma^2\)</span> but don’t know the coefficient <span>\(\beta\)</span> can be written as:</p>
<p><span>\[L(\beta;y_1, y_2,…, y_n, x_1, x_2,…, x_n,\sigma^2) = (2\pi\sigma^2)^{-n/2}\text{exp}\left(-\frac{1}{2\sigma^2} \sum_{i=1}^n (y_i – \beta x_i)^2\right)\]</span></p>
<p>Since it is much easier to work with sums than products, we generally work with the log-likelihood function:</p>
<p><span>\[l(\beta;y_1, y_2,…, y_n, x_1, x_2,…, x_n, \sigma^2) = -\frac{n}{2}\text{ln}(2\pi\sigma^2) – \frac{1}{2\sigma^2} \sum_{i=1}^n (y_i – \beta x_i)^2\]</span> In the log-likelihood function, <span>\(n\)</span>, <span>\(x_i\)</span>’s, <span>\(y_i\)</span>’s, and <span>\(\sigma^2\)</span> are all fixed and known – we are trying to estimate <span>\(\beta\)</span>, the slope. That is, the likelihood (or log-likelihood) is a function of <span>\(\beta\)</span> only. Typically, we will have more than unknown one parameter – say multiple regression coefficients, or an unknown variance parameter (<span>\(\sigma^2\)</span>) – but visualizing the likelihood function gets very hard or impossible; I am not great in imagining (or plotting) in <span>\(p\)</span>-dimensions, which is what we need to do if we have <span>\(p\)</span> parameters.</p>
</div>
<div>
<h3>The simulation</h3>
<p>To start, here is a one-line function that returns the log-likelihood of a data set (containing <span>\(x\)</span>’s and <span>\(y\)</span>’s) based on a specific value of <span>\(\beta\)</span>.</p>
<pre><code>library(data.table)

ll &lt;- function(b, dt, var) {
  dt[, sum(dnorm(x = y, mean = b*x, sd = sqrt(var), log = TRUE))]  
}

test &lt;- data.table(x=c(1,1,4), y =c(2.0, 1.8, 6.3))
ll(b = 1.8, test, var = 1)</code></pre>
<pre><code>## [1] -3.181816</code></pre>
<pre><code>ll(b = 0.5, test, var = 1)</code></pre>
<pre><code>## [1] -13.97182</code></pre>
<p>Next, I generate a single draw of 200 observations of <span>\(x\)</span>’s and <span>\(y\)</span>’s:</p>
<pre><code>library(simstudy)

b &lt;- c(seq(0, 3, length.out = 500))
truevar = 1

defX &lt;- defData(varname = &quot;x&quot;, formula = 0, 
                variance = 9, dist = &quot;normal&quot;)

defA &lt;- defDataAdd(varname = &quot;y&quot;, formula = &quot;1.5*x&quot;, 
                   variance = truevar, dist = &quot;normal&quot;)

set.seed(21)
dt &lt;- genData(200, defX)
dt &lt;- addColumns(defA, dt)
dt</code></pre>
<pre><code>##       id         x          y
##   1:   1  2.379040  4.3166333
##   2:   2  1.566754  0.9801416
##   3:   3  5.238667  8.4869651
##   4:   4 -3.814008 -5.6348268
##   5:   5  6.592169  9.6706410
##  ---                         
## 196: 196  3.843341  4.5740967
## 197: 197 -1.334778 -1.5701510
## 198: 198  3.583162  5.0193182
## 199: 199  1.112866  1.5506167
## 200: 200  4.913644  8.2063354</code></pre>
<p>The likelihood function is described with a series of calls to function <code>ll</code> using <code>sapply</code>. Each iteration uses one value of the <code>b</code> vector. What we end up with is a likelihood estimation for each potential value of <span>\(\beta\)</span> given the data.</p>
<pre><code>loglik &lt;- sapply(b, ll, dt = dt, var = truevar)

bt &lt;- data.table(b, loglike = loglik)
bt</code></pre>
<pre><code>##                b   loglike
##   1: 0.000000000 -2149.240
##   2: 0.006012024 -2134.051
##   3: 0.012024048 -2118.924
##   4: 0.018036072 -2103.860
##   5: 0.024048096 -2088.858
##  ---                      
## 496: 2.975951904 -2235.436
## 497: 2.981963928 -2251.036
## 498: 2.987975952 -2266.697
## 499: 2.993987976 -2282.421
## 500: 3.000000000 -2298.206</code></pre>
<p>In a highly simplified approach to maximizing the likelihood, I simply select the <span>\(\beta\)</span> that has the largest likelihood based on my calls to <code>ll</code> (I am limiting my search to values between 0 and 3, just because I happen to know the true value of the parameter). Of course, this is not how things work in the real world, particularly when you have more than one parameter to estimate – the estimation process requires elaborate algorithms. In the case of a normal regression model, it is actually the case that the ordinary least estimate of the regression parameters is the maximum likelihood estimate (you can see in the above equations that maximizing the likelihood <em>is</em> minimizing the sum of the squared differences of the observed and expected values).</p>
<pre><code>maxlik &lt;- dt[, max(loglik)]
lmfit &lt;- lm(y ~ x - 1, data =dt) # OLS estimate

(maxest &lt;- bt[loglik == maxlik, b]) # value of beta that maxmizes likelihood</code></pre>
<pre><code>## [1] 1.472946</code></pre>
<p>The plot below on the left shows the data and the estimated slope using OLS. The plot on the right shows the likelihood function. The <span>\(x\)</span>-axis represents the values of <span>\(\beta\)</span>, and the <span>\(y\)</span>-axis is the log-likelihood as a function of those <span>\(\beta's\)</span>:</p>
<pre><code>library(ggplot2)

slopetxt &lt;- paste0(&quot;OLS estimate: &quot;, round(coef(lmfit), 2))

p1 &lt;- ggplot(data = dt, aes(x = x, y= y)) +
  geom_point(color = &quot;grey50&quot;) +
  theme(panel.grid = element_blank()) +
  geom_smooth(method = &quot;lm&quot;, se = FALSE, 
              size = 1, color = &quot;#1740a6&quot;) +
  annotate(geom = &quot;text&quot;, label = slopetxt,
           x = -5, y = 7.5, 
           family = &quot;sans&quot;) 

p2 &lt;- ggplot(data = bt) +
  scale_y_continuous(name = &quot;Log likelihood&quot;) +
  scale_x_continuous(limits = c(0, 3), 
                     breaks = seq(0, 3, 0.5),
                     name = expression(beta)) +
  theme(panel.grid.minor = element_blank())  +
  geom_line(aes(x = b, y = loglike), 
            color = &quot;#a67d17&quot;, size = 1) +
  geom_point(x = maxest, y = maxlik, color = &quot;black&quot;, size = 3)

library(gridExtra)
grid.arrange(p1, p2, nrow = 1)</code></pre>
<p><img src="https://i1.wp.com/www.rdatagen.net/post/2017-10-23-repeated-sampling-to-see-what-the-likelihood-function-looks-like-literally_files/figure-html/unnamed-chunk-5-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
</div>
<div>
<h3>Adding variation</h3>
<p>Now, for the pretty part. Below, I show plots of multiple likelihood functions under three scenarios. The only thing that differs across each of those scenarios is the level of variance in the error term, which is specified in <span>\(\sigma^2\)</span>. (I have not included the code here since essentially loop through the process describe above.) If you want the code just let me know, and I will make sure to post it. I do want to highlight the fact that I used package <code>randomcoloR</code> to generate the colors in the plots.)</p>
<p><img src="https://i2.wp.com/www.rdatagen.net/post/2017-10-23-repeated-sampling-to-see-what-the-likelihood-function-looks-like-literally_files/figure-html/unnamed-chunk-6-1.png?w=450&ssl=1" data-recalc-dims="1"><img src="https://i0.wp.com/www.rdatagen.net/post/2017-10-23-repeated-sampling-to-see-what-the-likelihood-function-looks-like-literally_files/figure-html/unnamed-chunk-6-2.png?w=450&ssl=1" data-recalc-dims="1"><img src="https://i0.wp.com/www.rdatagen.net/post/2017-10-23-repeated-sampling-to-see-what-the-likelihood-function-looks-like-literally_files/figure-html/unnamed-chunk-6-3.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>What we can see here is that as the variance increases, we move away from Mt. Everest towards the Tuscan hills. The variance of the underlying process clearly has an impact on the uncertainty of the maximum likelihood estimates. The likelihood functions flatten out and the MLEs have more variability with increased underlying variance of the outcomes <span>\(y\)</span>. Of course, this is all consistent with maximum likelihood theory.</p>
</div>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://www.rdatagen.net/post/mle-can-be-pretty/"> ouR data generation</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/LV-hqzgX3XQ" height="1"></a></div>