<?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:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mikael Vejdemo-Johansson on Medium]]></title>
        <description><![CDATA[Stories by Mikael Vejdemo-Johansson on Medium]]></description>
        <link>https://medium.com/@michiexile?source=rss-95f9235a303b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*o6eSpp0VcqWiXsZY.png</url>
            <title>Stories by Mikael Vejdemo-Johansson on Medium</title>
            <link>https://medium.com/@michiexile?source=rss-95f9235a303b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:14:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michiexile/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Model Selection (continuing 6.7.2 and 2.11.13)]]></title>
            <link>https://medium.com/cuny-csi-mth594-bayesian-data-analysis/model-selection-continuing-6-7-2-and-2-11-13-52ae0a4766e?source=rss-95f9235a303b------2</link>
            <guid isPermaLink="false">https://medium.com/p/52ae0a4766e</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Mikael Vejdemo-Johansson]]></dc:creator>
            <pubDate>Mon, 02 Dec 2019 18:57:50 GMT</pubDate>
            <atom:updated>2019-12-02T18:57:50.763Z</atom:updated>
            <content:encoded><![CDATA[<p>We have previously looked at a dataset with fatal airplane accidents. First, <a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis/computation-2-11-13-in-rstan-4fba47363281">we created two different models</a> for the count of fatal accidents:</p><ol><li>FatAcc ~ Poisson(𝜃)</li><li>FatAcc ~ Poisson(PassengerMiles * 𝜃)</li></ol><p>Next, we <a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis/posterior-predictive-checking-6-7-2-350ec57c05dc">performed posterior predictive checks on both models</a>. The models assume — among other things — independence from year to year, and the absence of a time trend (beyond the exposure model’s increases in total passenger miles flown). Already for the posterior predictive checks we get reasons to abandon model 2: the time trend assumption was shown to be false.</p><p>Nevertheless, as an example for how to do model selection, we shall press on!</p><p>Bayesian Data Analysis (3rd ed) ultimately recommends the leave-one-out cross-validated information criterion (LOO-IC), with the Watanabe-Akaike information criterion (WAIC) as a decent more lightweight alternative.</p><p>Both are implemented in the R package loo , where the functions all expect you to provide log likelihoods for your data from each of your MCMC samples. The easy way to do this is to embed your log likelihood computation into the Stan code directly — so that as you sample, you immediately compute log likelihood as well. Alternatively, you could use something like scipy.stats to get access to likelihood functions and compute it yourself while iterating over the sampled parameter values.</p><p>The Stan code might end up looking like this for Model 1:</p><pre>data {<br>  int&lt;lower=0&gt; N;<br>  int&lt;lower=0&gt; FatAcc[N];<br>}<br>parameters {<br>  real&lt;lower=0&gt; theta;<br>}<br>model {<br>  theta ~ gamma(25.55, 1.07);<br>  FatAcc ~ poisson(theta);<br>}<br>generated quantities {<br>  int&lt;lower=0&gt; FatAccPred[N];<br>  real log_lik[N];<br>  for(n in 1:N) {<br>    FatAccPred[n] = poisson_rng(theta);<br>    log_lik[n] = poisson_lpmf(FatAcc[n] | theta);<br>  }<br>}</pre><p>We have added as a generated quantity not only the FatAccPred we used in the last post, but also the array log_lik. The name here is a naming convention that makes it easy to use functions from loo to extract the data for later processing: loo::extract_log_lik will look for a generated quantity named log_lik .</p><p>We fill the array with the log likelihoods. Since the Poisson distribution is discrete, the log likelihood function has the _lpmf suffix (for <em>log probability mass function</em>) instead of the continuous _lpdf suffix. Likelihood functions in Stan take first the data value at which to compute the likelihood, then separates it from the parameters to evaluate with an | (rather than the function argument , one might have expected).</p><p>Similarly, for Model 2, the Stan code might look like this:</p><pre>data {<br>  int&lt;lower=0&gt; N;<br>  int&lt;lower=0&gt; FatAcc[N];<br>  real&lt;lower=0&gt; MilesE12[N];<br>  <br>  real&lt;lower=0&gt; MilesE12new;<br>}<br>parameters {<br>  real&lt;lower=0&gt; theta;<br>}<br>model {<br>  theta ~ gamma(25.55, 1.07);<br>  for(n in 1:N)<br>    FatAcc[n] ~ poisson(MilesE12[n]*theta);<br>}<br>generated quantities {<br>  int&lt;lower=0&gt; FatAccPred;<br>  int&lt;lower=0&gt; FatAccPreds[N];<br>  real log_lik[N];<br>  FatAccPred = poisson_rng(MilesE12new*theta);<br>  for(n in 1:N) {<br>    FatAccPreds[n] = poisson_rng(MilesE12[n]*theta);<br>    log_lik[n] = poisson_lpmf(FatAcc[n] | MilesE12[n]*theta);<br>  }<br>}</pre><p>Regardless of model, the next step is to use sampling to run the MCMC calculation and get a random sample from the posterior — together with predictions and log likelihoods the way these two models were written.</p><p>With the log likelihoods generated, extract_log_lik will pull the data out. In order to use LOO-IC, we will need the <em>relative effective sample sizes</em>, which are calculated by comparing different chains of the MCMC output. Adding the argument merge_chains=FALSE to extract_log_lik will produce the data in a shape that allows the function relative_eff to calculate these relative effective sample sizes.</p><p>Important note: relative_eff takes <strong>likelihoods</strong> and not log likelihoods. We need to exponentiate to use it.</p><p>Put it all together, and the command sequence (after creating the Stan model itself) looks like this:</p><pre>fit = sampling(model, data=...)<br>log_lik = extract_log_lik(fit, merge_chains=FALSE)<br>r_eff = relative_eff(exp(log_lik))</pre><p>With these quantities in place, we can compute WAIC and LOO-IC as follows</p><pre>waic(log_lik)<br>loo(log_lik, r_eff=r_eff)</pre><p>There is also a function loo_compare that summarizes the comparison for us.</p><p>Returning to the fatal accidents case, WAIC and LOO-IC produces the same values for the information criterion, resulting in the following:</p><p>For Model 1:</p><pre>Computed from 4000 by 10 log-likelihood matrix<br><br>         Estimate  SE<br>elpd_loo    -30.0 1.8<br>p_loo         0.8 0.3<br>looic        60.1 3.6<br>------<br>Monte Carlo SE of elpd_loo is 0.0.<br><br>All Pareto k estimates are good (k &lt; 0.5).<br>See help(&#39;pareto-k-diagnostic&#39;) for details.</pre><p>And for Model 2:</p><pre>Computed from 4000 by 10 log-likelihood matrix<br><br>         Estimate  SE<br>elpd_loo    -40.3 4.4<br>p_loo         2.3 0.7<br>looic        80.6 8.7<br>------<br>Monte Carlo SE of elpd_loo is 0.0.<br><br>All Pareto k estimates are good (k &lt; 0.5).<br>See help(&#39;pareto-k-diagnostic&#39;) for details.</pre><p>Recall that for information criteria, lower is better. This computation tells us to prefer the first model — the exposure model is not a good enough fit to be a preferred model here.</p><h3>Over to you</h3><p>Just like in the previous posts, it is now your task to compare the models as fitted on the fatality counts from the accidents — these blog posts only deal with the number of accidents, not the number of fatalities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52ae0a4766e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis/model-selection-continuing-6-7-2-and-2-11-13-52ae0a4766e">Model Selection (continuing 6.7.2 and 2.11.13)</a> was originally published in <a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis">CUNY CSI MTH594 Bayesian Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Posterior Predictive Checking (6.7.2)]]></title>
            <link>https://medium.com/cuny-csi-mth594-bayesian-data-analysis/posterior-predictive-checking-6-7-2-350ec57c05dc?source=rss-95f9235a303b------2</link>
            <guid isPermaLink="false">https://medium.com/p/350ec57c05dc</guid>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Mikael Vejdemo-Johansson]]></dc:creator>
            <pubDate>Thu, 21 Nov 2019 12:29:52 GMT</pubDate>
            <atom:updated>2019-11-21T12:29:52.813Z</atom:updated>
            <content:encoded><![CDATA[<p>Our <a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis/computation-2-11-13-in-rstan-4fba47363281">previous look at exercise 2.11.13</a> continues in exercise 6.7.2 with posterior predictive checking of the models we implemented.</p><p>The question posed is whether — for each of the model we constructed — we can check</p><ol><li>the assumption of independence between the years, and</li><li>the assumption of a lack of a time trend</li></ol><p>through picking appropriate test statistics and performing a posterior predictive check.</p><p>The source exercise poses two models each for two quantities (# of fatal accidents; # of passenger deaths) over a decade — either as joint constant rate independent Poisson distributions, or as independent Poisson distributions with rate proportional to the total number of passenger miles travelled. We will — like in the previous post — leave the passenger death count as an exercise to the reader and focus on treating the accident counts.</p><p>For all of our solutions, we will be doing replication predictions: predictions under the exact circumstances that come as input to our models. For the constant rate model, this just means drawing at random from that distribution, while for the exposure model — where rates are proportional to the <em>exposure </em>of passenger miles travelled — it means reusing the data from each year to calculate the rates.</p><p>Our modified models look like this for the constant rate model:</p><pre>```{stan output.var=&quot;model&quot;}<br>data {<br>  int&lt;lower=0&gt; N;<br>  int&lt;lower=0&gt; FatAcc[N];<br>}<br>parameters {<br>  real&lt;lower=0&gt; theta;<br>}<br>model {<br>  theta ~ gamma(25.55, 1.07);<br>  FatAcc ~ poisson(theta);<br>}<br>generated quantities {<br>  int&lt;lower=0&gt; FatAccPred[N];<br>  for(n in 1:N)<br>    FatAccPred[n] = poisson_rng(theta);<br>}<br>```</pre><p>And for the exposure model, our Stan code ends up looking like this:</p><pre>```{stan output.var=&quot;expmodel&quot;}<br>data {<br>  int&lt;lower=0&gt; N;<br>  int&lt;lower=0&gt; FatAcc[N];<br>  real&lt;lower=0&gt; MilesE12[N];<br>  <br>  real&lt;lower=0&gt; MilesE12new;<br>}<br>parameters {<br>  real&lt;lower=0&gt; theta;<br>}<br>model {<br>  theta ~ gamma(25.55, 1.07);<br>  for(n in 1:N)<br>    FatAcc[n] ~ poisson(MilesE12[n]*theta);<br>}<br>generated quantities {<br>  int&lt;lower=0&gt; FatAccPred;<br>  int&lt;lower=0&gt; FatAccPreds[N];<br>  FatAccPred = poisson_rng(MilesE12new*theta);<br>  for(n in 1:N)<br>    FatAccPreds[n] = poisson_rng(MilesE12[n]*theta);<br>}<br>```</pre><p>In both of these models the main change we have done is to introduce an array in the generated quantities part that generates as many values as we have input years.</p><p>After running sampling to fit the model and generate random draws from the posterior and of the generated quantities, we use extract to get hold of the random draws:</p><pre>```{r}<br>FatAccPred = extract(fit, permuted=TRUE)$FatAccPred<br>expFatAccPreds = extract(expfit, permuted=TRUE)$FatAccPreds<br>```</pre><h3>Independence</h3><p>While dependency between random variables can happen without Pearson correlation, a significantly non-zero Pearson correlation is an indication against independence of variables. An alternative would be to use either Spearman or Kendall correlation, to avoid getting stuck on linearity vs. non-linearity in the dependencies. Thus one way we should be able to check whether there are dependencies between the years would be to take a look at the correlations between adjacent years — the lag 1 autocorrelations. We will use Spearman.</p><p>Using sapply we can comfortably calculate our statistic on the simulated data. Thus, this code will calculate the data autocorrelation and the simulated autocorrelation for the constant rate model.</p><pre>```{r}<br>y = cor(accidents$FatAcc[2:nrow(accidents)], <br>        accidents$FatAcc[1:(nrow(accidents)-1)],<br>        method=&quot;spearman&quot;)<br>yrep = sapply(1:(dim(FatAccPred)[1]), function(i) {<br>  cor(FatAccPred[i,2:(dim(FatAccPred)[2])], <br>      FatAccPred[i,1:((dim(FatAccPred)[2])-1)],<br>      method=&quot;spearman&quot;)<br>})<br>```</pre><p>For the exposure rate, we simply replace every instance of FatAccPred with expFatAccPreds.</p><p>We calculate a p-value (tail area) using a standard formula: rank/N. A nice plot can be produced using ggformula and ggplot:</p><pre>```{r}<br>p = rank(c(y,yrep))[1]/dim(FatAccPred)[1]<br>p = min(p, 1-p)<br>data.frame(yrep=yrep) %&gt;%<br>  gf_rug(~yrep, alpha=0.05) %&gt;%<br>  gf_density(~yrep, fill=&quot;blue&quot;, alpha=0.25) %&gt;%<br>  gf_vline(xintercept = y) %&gt;%<br>  gf_labs(title=glue(&quot;one-sided tail area p = {p}&quot;)) +<br>  theme_light()<br>```</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*ZKOUfD_WpNBodZcUN-y5Iw.png" /><figcaption>Posterior predictive distribution, and observed data value, for lag 1 autocorrelation using the constant rate Poisson model. Arguably, since we did not pick whether we were looking for a remarkably high or a remarkably low value, we should be doubling the p-value, yielding p~0.17275 and no major indication of an autocorrelation.</figcaption></figure><p>The code to do this for the second model is pretty much identical — requiring y and ypred to have been computed using expFatAccPreds instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*2lalfT1qsLCCHk65MmDDgw.png" /><figcaption>Posterior predictive distribution, and observed data value, for lag 1 autocorrelation using the exposure Poisson model. With this graph and this tail area, we have no reason to exclude independence based on the correlation: model and data behave pretty similar to one another.</figcaption></figure><p>It would seem that the assumption of independence between the years is not obviously unreasonable.</p><h3>Time trend</h3><p>The second question was whether there was a time trend in the data that we ignored when modeling. For this, an immediate candidate is to look at correlations between the fatal accident count and the year. We will use Spearman correlation again to allow for non-linear trends. A lot of the code looks the same, only the calculations of y and yrep change somewhat. For the constant rate Poisson model, we get</p><pre>y = cor(accidents$FatAcc, <br>        accidents$Year,<br>        method=&quot;spearman&quot;)<br>yrep = sapply(1:(dim(FatAccPred)[1]), function(i) {<br>  cor(FatAccPred[i,], <br>      accidents$Year,<br>        method=&quot;spearman&quot;)<br>})</pre><p>Calculating p-values and plotting the distributions we get for our first model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*Dxoi4dmdvFvrRac-EwAbgQ.png" /><figcaption>Density plot for Spearman correlation between the year and the constant rate Poisson model. Neither p-value nor plot are terribly dramatic — especially after doubling the p-value to account for the fact that we did not start out looking for a particular tail. A time trend in the data compared to this model is not obvious.</figcaption></figure><p>And for the second, exposure Poisson, model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*ehKSyAhM_lIZ0vkzKteRYA.png" /><figcaption>Density plot for Spearman correlation between the year and the exposure rate Poisson model. After controlling for the amount of travelling done in any year, the lack of time trend assumption looks far less convincing: the data shows a clear decreasing trend, while the simulations all produce increasing trends — which would be reasonable since the exposure keeps going up as air travel gets more and more popular.</figcaption></figure><h3>Over to you, dear reader</h3><p>Now it’s your turn. Having dealt with the Passenger Death variable before, perform posterior predictive checks to see whether the data is compatible with these two modeling assumptions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=350ec57c05dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis/posterior-predictive-checking-6-7-2-350ec57c05dc">Posterior Predictive Checking (6.7.2)</a> was originally published in <a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis">CUNY CSI MTH594 Bayesian Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computation: 2.11.13 in RStan]]></title>
            <link>https://medium.com/cuny-csi-mth594-bayesian-data-analysis/computation-2-11-13-in-rstan-4fba47363281?source=rss-95f9235a303b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fba47363281</guid>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[homework-statistics]]></category>
            <dc:creator><![CDATA[Mikael Vejdemo-Johansson]]></dc:creator>
            <pubDate>Thu, 03 Oct 2019 17:45:35 GMT</pubDate>
            <atom:updated>2019-11-15T16:21:16.709Z</atom:updated>
            <content:encoded><![CDATA[<p>To give us another close look at modeling and computing using RStan, here’s exercise 2.11.13.</p><p>We start out with a table of fatal airplane accidents and deaths per year over a 10-year period. The death rate is number of passenger deaths per 1e8 passenger miles.</p><pre>Year   Fatal Acc.    Pass. Death  Death Rate<br>1976       24          734        0.19<br>1977       25          516        0.12<br>1978       31          754        0.15<br>1979       31          877        0.16<br>1980       22          814        0.14<br>1981       21          362        0.06<br>1982       26          764        0.13<br>1983       20          809        0.13<br>1984       16          223        0.03<br>1985       22         1066        0.15</pre><h3>a)</h3><p>First we are instructed to assume these are Poisson distributed. We get to pick a prior ourselves, and should determine a posterior distribution estimating the Poisson rate. Using the rate, give a 95% predictive interval for the number of fatal accidents in 1986.</p><p>As pointed out in the text, Gamma is a reasonable conjugate prior for the Poisson distribution. The text suggests that in order to pick a good prior, we can estimate mean and standard deviation from the data, and then solve for the corresponding parameters. We get</p><pre>data = data.frame(<br>  Year = 1976:1985,<br>  FatAcc = c(24,25,31,31,22,21,26,20,16,22),<br>  Deaths = c(734,516,754,877,814,362,764,809,223,1066))<br>data %&gt;% summarize(FatAcc_mu = mean(FatAcc), <br>                   FatAcc_var = var(FatAcc))</pre><pre>  FatAcc_mu FatAcc_var<br>1      23.8   22.17778</pre><p>We seek Gamma parameters that produce mean 23.8 and variance 22.17. Stan uses the shape/rate version of the Gamma distribution, so that for gamma(alpha,beta), we get</p><ul><li>mean = alpha/beta</li><li>variance = alpha/beta²</li></ul><p>Solving for alpha and beta:</p><ul><li>alpha = 25.55</li><li>beta = 1.07</li></ul><p>Hence the model we can propose is going to be</p><ul><li>FatAcc ~ Poisson(theta)</li><li>theta ~ Gamma(25.55,1.07)</li></ul><p>One way that Stan handles predictions is to make the predicted variable a <strong>generated quantity</strong>. These are sampled alongside the parameters as the model fits.</p><p>Armed with this, we are ready to write some Stan code!</p><pre>```{stan output.var=&quot;model&quot;}<br>data {<br>  int&lt;lower=0&gt; N;<br>  int&lt;lower=0&gt; FatAcc[N];<br>}<br>parameters {<br>  real&lt;lower=0&gt; theta;<br>}<br>model {<br>  theta ~ gamma(25.55, 1.07);<br>  FatAcc ~ poisson(theta);<br>}<br>generated quantities {<br>  int&lt;lower=0&gt; FatAccPred;<br>  FatAccPred = poisson_rng(theta);<br>}<br>```</pre><p>Our data is the count of fatal accidents. We know it can’t be negative. We do allow for more than one observation — which necessitates the N and the array shape for FatAcc.</p><p>Our parameter 𝜃 is the rate for our Poisson distribution.</p><p>Our prior is the Gamma prior with hyperparameters as we estimated from the data.</p><p>Once the model is created, we can start sampling from it to get empirical distributions on 𝜃. We draw 1000 predictions to get a good empirical distribution for the prediction.</p><pre>fit = sampling(model, data=list(N=nrow(accidents), <br>                                FatAcc=accidents$FatAcc))</pre><p>As usual, this gives a long output with progress reports on the sampling simulation. At the end we get an object fit out, with the fitted model. Inspecting the results:</p><pre>&gt; print(fit)<br>Inference for Stan model: stan-436319e1c875.<br>4 chains, each with iter=2000; warmup=1000; thin=1; <br>post-warmup draws per chain=1000, total post-warmup draws=4000.<br><br>             mean se_mean   sd   2.5%    25%    50%    75%  97.5%<br>theta       23.81    0.04 1.49  20.96  22.79  23.80  24.77  26.83<br>FatAccPred  23.89    0.09 5.21  14.00  20.00  24.00  27.00  35.00<br>lp__       571.39    0.02 0.73 569.25 571.21 571.68 571.85 571.90<br>           n_eff Rhat<br>theta       1431    1<br>FatAccPred  3748    1<br>lp__        1723    1<br><br>Samples were drawn using NUTS(diag_e) at Thu Oct  3 13:22:20 2019.<br>For each parameter, n_eff is a crude measure of effective sample size,<br>and Rhat is the potential scale reduction factor on split chains (at <br>convergence, Rhat=1).</pre><p>From the printout we can read off a 95% predictive interval as (14.00, 35.00).</p><h3>b)</h3><p>Now, let’s do the same thing — but with each year independent Poisson with a rate and exposure, where exposure is proportional to passenger miles flown. In other words FatAcc ~ poisson(x*theta) for some x proportional to the passenger miles flown.</p><p>We can estimate x from the rate and the passenger deaths as (using 10¹² passenger miles as our unit)</p><pre>accidents$MilesE12 = 1e8 * accidents$Deaths / accidents$Rate / 1e12</pre><p>We can assume that the joint proportionality constant is absorbed by the 𝜃 parameter, making our model:</p><pre>data {<br>  int&lt;lower=0&gt; N;<br>  int&lt;lower=0&gt; FatAcc[N];<br>  real&lt;lower=0&gt; MilesE8[N];<br>  <br>  real&lt;lower=0&gt; MilesE8new;<br>}<br>parameters {<br>  real&lt;lower=0&gt; theta;<br>}<br>model {<br>  theta ~ gamma(25.55, 1.07);<br>  for(n in 1:N)<br>    FatAcc[n] ~ poisson(MilesE8[n]*theta);<br>}<br>generated quantities {<br>  int&lt;lower=0&gt; FatAccPred;<br>  FatAccPred = poisson_rng(MilesE8new*theta);<br>}</pre><p>We run and examine the model. The input 8 * 10¹¹ for prediction was given in the exercise.</p><pre>expfit = sampling(expmodel, data=list(<br>  N = nrow(accidents), FatAcc = accidents$FatAcc,<br>  MilesE12 = accidents$MilesE12, MilesE12new = 8e11/1e12<br>))<br>&gt; print(expfit)<br>Inference for Stan model: stan-43636ec3d8c0.<br>4 chains, each with iter=2000; warmup=1000; thin=1; <br>post-warmup draws per chain=1000, total post-warmup draws=4000.</pre><pre>mean se_mean   sd   2.5%    25%    50%    75%  97.5%<br>theta       38.89    0.06 2.36  34.61  37.19  38.82  40.41  43.80<br>FatAccPred  31.14    0.10 5.89  20.00  27.00  31.00  35.00  43.00<br>lp__       558.41    0.02 0.67 556.51 558.24 558.66 558.84 558.89<br>           n_eff Rhat<br>theta       1718    1<br>FatAccPred  3395    1<br>lp__        1383    1</pre><pre>Samples were drawn using NUTS(diag_e) at Thu Oct  3 13:41:17 2019.<br>For each parameter, n_eff is a crude measure of effective sample size,<br>and Rhat is the potential scale reduction factor on split chains (at <br>convergence, Rhat=1).</pre><p>We can read off the 95% predictive interval as (20,43).</p><h3>Now you…</h3><p>The next two steps ask for the same thing — but with passenger deaths instead of number of accidents. Adapt the code to this case and produce posterior distributions and predictions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fba47363281" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis/computation-2-11-13-in-rstan-4fba47363281">Computation: 2.11.13 in RStan</a> was originally published in <a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis">CUNY CSI MTH594 Bayesian Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exponential Families II: Samples and sufficiency]]></title>
            <link>https://medium.com/cuny-csi-mth594-bayesian-data-analysis/exponential-families-ii-samples-and-sufficiency-3cf485925226?source=rss-95f9235a303b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cf485925226</guid>
            <category><![CDATA[exponential-families]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Mikael Vejdemo-Johansson]]></dc:creator>
            <pubDate>Thu, 26 Sep 2019 19:32:28 GMT</pubDate>
            <atom:updated>2019-09-26T19:46:21.029Z</atom:updated>
            <content:encoded><![CDATA[<p>In our <a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis/exponential-families-i-definitions-and-examples-2a89c2fb3549">last installment</a>, we defined exponential families and gave examples from a range of familiar distributions. Now I would like to spend some time looking at a few reasons why we should care about these families in the first place.</p><h3>Sufficiency</h3><p>One major reason why exponential families are nice is that they deliver <em>sufficient statistics </em>for us basically for free. So what are sufficient statistics?</p><h4>Definition</h4><p>A statistic T(y) is <strong>sufficient for a parameter 𝜃 </strong>if and only if the likelihood function can be factored as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*NudvcsQReZoK1CwpX_N_mQ.png" /></figure><p>In other words, <em>T</em> is sufficient if we can separate out the influences of the data itself so that they only interact with the parameter through the sufficient statistic.</p><h4>In exponential families</h4><p>Returning back to our exponential families, with the generic form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*VwEGAj5KFsQCIXE5A0Sl-A.png" /></figure><p>We see clearly that the only interaction between <em>y</em> and 𝜃 is through the function <em>T(y)</em>. Hence, the <em>T</em> we needed to choose to determine the family in the first place is a sufficient statistic.</p><h3>Samples</h3><p>Given a set y[1], …, y[n] of iid samples from a distribution in an exponential family, their joint likelihood also follows an exponential distribution. Why? Well, because</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*Qf_FVaV7XyVMttR2ka2Brw.png" /></figure><p>The final expression here has the same decomposition as the exponential families require.</p><p>It follows that for our iid sample, mean(T(y)) is a sufficient statistic for the sample. For most of our needs, we can just throw away everything else about the data — and still do most inferences we are interested in doing.</p><h3>Sufficient Statistics for Distributions</h3><p>So what are the sufficient statistics for the distributions we looked at?</p><ul><li>Normal Distribution, known 𝜎²: mean(y)</li><li>Normal Distribution, unknown 𝜎²: mean(y^2 — 2µy)</li><li>Poisson: mean(y)</li><li>Binomial, known n: mean(y)</li><li>Gamma, unknown 𝛽: mean(y)</li><li>Gamma, unknown 𝛼: mean(log(y))</li><li>Gamma, both unknown: the pair mean(y) and mean(log(y)).</li></ul><h3>Bayesian updates</h3><p>Since the exponential families have such a strictly prescribed shape, they form natural candidates for conjugate priors. As we saw already, mean(T(y)) or for that matter <em>∑T(y)</em> form sufficient statistics for iid samples.</p><p>When we are doing Bayesian updates, the contribution from <em>B(y)</em> is absorbed by the proportionality constant — which means that if our prior is in an exponential family with</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*WiH-RNagpMiBi1BouYf7EQ.png" /></figure><p>Then after seeing <strong>y</strong> with n iid samples, the posterior will be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*kFRgqcdY7BZnX45NvJuXuw.png" /></figure><p>So that with a sufficiently wide definition of our A (allowing it to take the n into account), we get an automatic conjugate prior.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cf485925226" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis/exponential-families-ii-samples-and-sufficiency-3cf485925226">Exponential Families II: Samples and sufficiency</a> was originally published in <a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis">CUNY CSI MTH594 Bayesian Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exponential Families I: Definitions and Examples]]></title>
            <link>https://medium.com/cuny-csi-mth594-bayesian-data-analysis/exponential-families-i-definitions-and-examples-2a89c2fb3549?source=rss-95f9235a303b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a89c2fb3549</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[exponential-families]]></category>
            <dc:creator><![CDATA[Mikael Vejdemo-Johansson]]></dc:creator>
            <pubDate>Thu, 26 Sep 2019 15:43:56 GMT</pubDate>
            <atom:updated>2019-09-26T19:45:34.746Z</atom:updated>
            <content:encoded><![CDATA[<p>Many of the distributions we keep meeting in statistics have density functions that can be written as <em>exp[…]</em> for something useful inside the brackets. And many of the things one might want to do (say, compute likelihood for an entire sample, or update a prior, …) boil down to multiplying density functions, which turns into adding the content inside.</p><p>It turns out we can save a lot of mileage by working out parts of the theory for such families in the abstract, and then applying it in specific cases as and when needed.</p><h3>Definition</h3><p>We call a family of probability distributions an <em>exponential family</em> parametrized by some parameter 𝜃 if there are functions 𝜂, T, A and B such that each density in the family can be written as:</p><figure><img alt="p(y|𝜃) = exp[𝜂(𝜃).T(y) + A(𝜃) + B(y)]" src="https://cdn-images-1.medium.com/max/618/1*VwEGAj5KFsQCIXE5A0Sl-A.png" /><figcaption>Generic form of an exponential family density</figcaption></figure><p>Here, both 𝜂 and T can be vector valued as long as they are of the same size.</p><p>The idea is to separate out mixed terms (coming from the dot product) from pure terms (A for the parameter and B for the data).</p><h3>Examples</h3><p>A definition helps nothing at all unless we can produce a few examples to show us what’s actually going on. So here are some very common probability densities:</p><h4>Normal</h4><p>The normal distribution has density function</p><figure><img alt="p(y|\mu,\sigma²) = \frac{1}{\sqrt{2\pi\sigma²}}\exp\left[\frac{-(y-\mu)²}{2\sigma²}\right]" src="https://cdn-images-1.medium.com/max/577/1*H-bq9MpN0ES6RBovq9q0ww.png" /><figcaption>Normal distribution density function</figcaption></figure><p>Once we recognize that 1/√2π𝜎² = -1/2 * log(2π𝜎²), and after expanding the square we can rewrite all of this as</p><figure><img alt="p(y|\mu,\sigma²) = \exp\left[\frac{-1}{2}\left(\frac{-y²+2y\mu-\mu²}{\sigma²}+\log(2\pi) + \log(\sigma²)\right)\right]" src="https://cdn-images-1.medium.com/max/972/1*2bNX-jJENe0SIgQiCTa5Ug.png" /></figure><p>Now, depending on which parameters are considered known, the normal distributions are exponential in a few different ways:</p><p><strong>𝜎² known, µ unknown:</strong></p><p>The mixed term is going to be -1/2𝜎² * 2yµ. Everything else is either pure parameter or pure data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQrjzIbANqnH9_ccCzsr3A.png" /></figure><p><strong>𝜎² unknown, µ known:</strong></p><p>Now both µy and y² contribute to mixed terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_2HEzU2gYm0kYohi6etUQ.png" /></figure><p>By looking carefully at all the terms, we can conclude that this is also the exponential family for the case when <strong>both parameters are unknown</strong>.</p><h4>Poisson</h4><p>Recall the Poisson probability mass function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*lAbaDnG1vpm2-bcRhzJyAQ.png" /></figure><p>From this we can now pick out mixed and pure terms quite easily:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*NMfDulFqzcrCiUosostTOg.png" /></figure><h4>Binomial and Bernoulli</h4><p>Recall the Binomial probability mass function (Bernoulli is the special case of <em>n=1</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*93gAhEsD9nq2I4uDiCVT8A.png" /></figure><p>This can actually be simplified, and the <em>T</em> made more intuitive, by rewriting the mass function a little bit. By extracting the <em>-k</em> in the exponent into an actual division we are left with</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*ERXzJbOuzQ0LdM8Rs1W7fQ.png" /></figure><p>where we write o for the <em>odds: o = p/(1-p)</em>. A little algebra shows us that then <em>p = o/(o+1)</em> and <em>(1-p) = 1/(o+1)</em>. Taking logarithms, this can be rewritten as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hydz9jUgYZNLPVBhonjCMA.png" /></figure><p>We could imagine not knowing <em>n</em>. It’s weird, but not unfathomable. We get three cases:</p><p><strong>n known, p unknown:</strong></p><p>Here, k log o is our mixed term. We get the exponential family defined through:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*6OenXEDjvQt8BJxPpeblEA.png" /></figure><p><strong>n unknown:</strong></p><p>Now our mixed term includes the binomial coefficient. It is not clear to me that this mixed term can be neatly written as a dot product between vectors of fixed sizes.</p><p><strong>Beta distribution:</strong></p><p>The Beta distribution is very closely related. We leave it as an exercise to derive the exponential family form for the Beta distribution from this.</p><h4>Gamma</h4><p>The Gamma distributions include as special cases both the exponential and the chi-squared distributions.</p><p>Gamma comes with three different commonly used parameter sets:</p><ol><li>Shape <em>k</em> and scale 𝜃</li><li>Shape <em>k</em> and rate 𝛽; <em>k</em> is also often called 𝛼.</li><li>Shape <em>k</em> and mean µ</li></ol><p>These are connected through: 𝛽 = 1/𝜃, and µ = <em>k</em>𝜃 = <em>k</em>/𝛽</p><p>Their probability mass functions are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*KnPkRtRpN9KZb86JZUF1mg.png" /></figure><p>We get the exponential distribution as the case when k=1 and chi-squared when 𝜃=2. Recall also that 𝛤 here is the factorial on positive integers.</p><p>The shape/rate case is an exponential family as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*XcNmMNr6QAeTOO3vlY1zRQ.png" /></figure><p><strong>𝛼 known, 𝛽 unknown:</strong></p><p>The mixed term is -𝛽y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*p8HERjs4wjGMqcw273ENUw.png" /></figure><p><strong>𝛼 unknown, 𝛽 known:</strong></p><p>The mixed term is (𝛼-1)log y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*SCo4js-9ADQGm3OG5Ev6qw.png" /></figure><p><strong>both unknown:</strong></p><p>Mixed term is a dot product capturing both mixed terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*7bpCSgCpXRzfvtFkd35gYg.png" /></figure><p>The two remaining forms (shape/scale and shape/mean) we leave as an exercise. 😉</p><h3>For our next post…</h3><p>Next post will discuss sufficient statistics and how to read them directly off of an exponential family, as well as the sampling distributions for combining iid samples.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a89c2fb3549" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis/exponential-families-i-definitions-and-examples-2a89c2fb3549">Exponential Families I: Definitions and Examples</a> was originally published in <a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis">CUNY CSI MTH594 Bayesian Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structure of an article: This is a title]]></title>
            <link>https://medium.com/@michiexile/structure-of-an-article-this-is-a-title-8b0d3f5d135d?source=rss-95f9235a303b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b0d3f5d135d</guid>
            <category><![CDATA[hon223]]></category>
            <category><![CDATA[writing]]></category>
            <dc:creator><![CDATA[Mikael Vejdemo-Johansson]]></dc:creator>
            <pubDate>Wed, 25 Sep 2019 18:55:17 GMT</pubDate>
            <atom:updated>2019-09-25T18:55:17.728Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the first paragraph. Especially in news articles, the first paragraph serves to give an enticement for the rest of the article — it is a way to draw the reader into the text and keep them around. This article, for instance, will talk about how many articles are structured to help my students with an example to guide their own reading and analyses.</p><p>From the second paragraph and onwards, the article goes on to tell its actual story. Often the paragraphs carry more or less separate topics, so that a paragraph break comes when the topic of discussion shifts.</p><p>Pretty much all articles <em>do</em> however have the structure of a sequence of paragraphs. The one exception that comes to mind is when the article is rather more like a wall of text. This is inadvisable since the paragraphs help quite a lot with reading the text, and walls of text are difficult to read.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b0d3f5d135d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A first look at computation]]></title>
            <link>https://medium.com/cuny-csi-mth594-bayesian-data-analysis/a-first-look-at-computation-2bcb4301b5f?source=rss-95f9235a303b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bcb4301b5f</guid>
            <category><![CDATA[stan]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Mikael Vejdemo-Johansson]]></dc:creator>
            <pubDate>Wed, 18 Sep 2019 01:14:34 GMT</pubDate>
            <atom:updated>2019-10-21T16:58:27.902Z</atom:updated>
            <content:encoded><![CDATA[<p>We will be digging far deeper into this as the semester goes on, but having already seen a first Bayesian inference step in the 3rd seminar, it’s time for us to try to Compute Things™.</p><p>The tool of choice is going to be (because it’s what BDA3 likes) <a href="https://mc-stan.org/">Stan</a>, accessed through the RStan package and — preferably — in an RMarkdown document written in RStudio. If you have taken my lower level statistics courses, this will all seem awfully familiar.</p><p>Stan is its own language, specifically designed for probabilistic and Bayesian computing. As luck has it, knitr and RStudio both understand Stan, and we can simply build a separate code block for the Stan code specification.</p><p>At a minimum, a Stan model has:</p><ul><li>a data section, specifying what information you will be providing the model</li><li>a parameters section, specifying what information you are trying to quantify</li><li>a model section, specifying how everything is connected, and what probability distributions are going to be used for everything.</li></ul><p>There is a lot more that can be done — specifying custom written functions, computing transformations on parameters, specifying extra information you want to be able to extract, etc. But for now we will focus on these three and a minimal example.</p><h3>Our example</h3><p>From the seminar discussion, we met the problem of estimating whether or not an infection rate of 10% was plausible having seen 2 infected in a sample of 20 randomly chosen individuals.</p><p>Similarly, in the BDA3 text, there was a classical example estimating whether or not 50% was a plausible rate of female births in Paris in the 1700s based on observations of total numbers of male and female births over several years.</p><p>Both of these do roughly the same thing: estimate a probability parameter for a Binomial model. So our model looks approximately the same in both cases:</p><h4>Given</h4><p>Observed total number of trials <em>N</em>, and observed successes <em>S</em>.</p><h4>Estimand</h4><p>Probability 𝜃</p><h4>Model</h4><p><em>S</em> ~ Binomial<em>(𝜃, N)</em></p><h4>Prior</h4><p>𝜃 ~ Beta(1,1) ( = Uniform)</p><p>As we will see, specifying it like this will give us the corresponding Stan code almost immediately for free.</p><h3>Translating to Stan</h3><p>First off, Stan code blocks start with ```{stan, output.var=”model”} . This makes RStudio handle writing the code out to a file and running the Stan compiler over it automatically. The resulting model object is written to the variable name specified as output.var in the code block initializer.</p><p>The three sections are specified as follows:</p><pre>data {<br>...<br>}<br>parameters {<br>...<br>}<br>model {<br>...<br>}</pre><p>Here, within the { .. } , statements are ; -terminated, and comments are included using //.</p><p>For both the data and the parameters block, the contents is a sequence of variable declarations. For our purposes, we will use the data types int and real. We will also be using a really cute feature — Stan allows you to state some of your assumptions on the variables outright.</p><p>Vectors are possible (actually quite common) — but not needed here, so we won’t include those.</p><p>Now to translate from our spec to the Stan model. The <strong>Given</strong> will fit in data, the <strong>Estimand </strong>will fit in parameters and the <strong>Prior</strong> and the <strong>Model</strong> both fit in model. We know that both <em>N</em> and <em>S</em> are non-negative integers — and S cannot be larger than N, and we know 𝜃 to be a real number in the interval [0,1]. Transcribing everything looks like this:</p><pre>data {<br>  int&lt;lower=0&gt; N;<br>  int&lt;lower=0,upper=N&gt; S;<br>}<br>parameters {<br>  real&lt;lower=0,upper=1&gt; theta;<br>}<br>model {<br>  theta ~ beta(1,1);<br>  S ~ binomial(N, theta);<br>}</pre><p>This forms a complete Stan program. Running the code block (remember to close it with ``` ) generates a compiled model object available in the next R code block afterwards.</p><p>Training the model is done using the sampling function in rstan . It takes the model as its first argument, and also the argument data=list(N=20,S=2) — handing the model the data is done through a list with named entries. Under the hood this launches a Monte-Carlo Markov Chain sampling process (which we will talk more about later int he semester) and will print out piles of information about the process.</p><p>Once the model is trained, we can do various things with it. For starters, a really useful information dump comes from the print function. It can look like this:</p><pre>fit = sampling(model, data=list(N=20,S=2))<br># skipped LOTS of printouts here<br>print(fit, digits=3)</pre><pre>Inference for Stan model: stan-1173d2bab4c1d.<br>4 chains, each with iter=2000; warmup=1000; thin=1; <br>post-warmup draws per chain=1000, total post-warmup draws=4000.<br><br>        mean se_mean    sd    2.5%    25%    50%    75%  97.5% n_eff  Rhat<br>theta  0.134   0.002 0.071   0.030  0.080  0.124  0.177  0.297  1372 1.000<br>lp__  -9.296   0.020 0.720 -11.432 -9.494 -9.012 -8.822 -8.763  1363 1.002<br><br>Samples were drawn using NUTS(diag_e) at Tue Sep 17 20:54:42 2019.<br>For each parameter, n_eff is a crude measure of effective sample size,<br>and Rhat is the potential scale reduction factor on split chains (at <br>convergence, Rhat=1).</pre><p>There is a lot of information packed here. From what we have learned so far in this study group, the key numbers are mean, 50% (median) and the interval with endpoints 2.5% and 97.5% (the 95% central posterior interval).</p><p>For 2 infected among 20 observations, we have a mean infection rate estimate of 13.4%, a median of 12.4% and a central posterior interval of (3.0% — 29.7%). There is not a good reason here to reject 10% as a possible value. (unless, that is, we doubt the uniform prior — in which case, redefining the model and rerunning the sampling will give us new information)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7sFdGUTuQ6tWRxSBtX_YJg.png" /></figure><p>There are also plenty of functions for plotting interesting depictions of the data. Beyond the point-interval estimates we extracted here, the stan_ plotting functions for ggplot2 are quite useful. RStan includes a quick way of setting up the plots through quietgg, so that the command quietgg(stan_dens(fit)) for instance produces a density plot of the samples from the posterior distribution of 𝜃, as seen here. We have a pretty wide spread of values that do peak quite close to 10%, but spreads out quite far — as could also be seen in the (3.0% — 29.7%) posterior interval.</p><h3>Over to you</h3><p>To check whether you have understood this, I will let you do the next example on your own. BDA3 describes Laplace working on data with births in Paris 1745 to 1770. The observations were:</p><ul><li># girls born: 241,945</li><li># boys born: 251,527</li><li># total born: 493,472</li></ul><p>The question Laplace approached was whether or not 50% was a reasonable estimate for the proportion of girls born.</p><p><strong>Your task:</strong> Fit a binomial model with some prior that you like (uniform, or some other beta prior are the easiest — they only require you adapt the code here slightly). Then check whether 50% falls within the posterior interval. Draw a histogram or a density for the random draws from the posterior distribution. Summarize everything by offering an argument about whether or not a 50% female birth rate can be rejected or not.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bcb4301b5f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis/a-first-look-at-computation-2bcb4301b5f">A first look at computation</a> was originally published in <a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis">CUNY CSI MTH594 Bayesian Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ℙ or Pr or p or … ?]]></title>
            <link>https://medium.com/cuny-csi-mth594-bayesian-data-analysis/%E2%84%99-or-pr-or-p-or-e66dab8d5173?source=rss-95f9235a303b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e66dab8d5173</guid>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Mikael Vejdemo-Johansson]]></dc:creator>
            <pubDate>Wed, 11 Sep 2019 19:18:13 GMT</pubDate>
            <atom:updated>2019-09-11T19:18:13.271Z</atom:updated>
            <content:encoded><![CDATA[<h3>ℙ or Pr or p or … ?</h3><p>There are a LOT of different p floating around anything probability related, and it’s not always clear how they fit together, nor what manipulations are valid where.</p><p>So let’s talk about it.</p><p>I will be using the following convention here:</p><ul><li>ℙ is the probability measure. ℙ(E) is the probability of the event E, which in turn is a subset of the outcome space Ω (check out our <a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis/probability-preliminaries-ca46d473383b">previous post</a> for what I mean by this)</li><li>I’m personally not all that fond of Pr, so I will be skipping it. We may reintroduce it later on to encode priors. Maybe.</li><li>p is the probability density function — and the probability mass function. They boil down to the same thing if you do a bit of futzing around with point masses and linear combinations of Dirac measures.<br>Their difference will be in whether Ω is discrete or continuous; and in whether we use ∑ or ∫ to combine them.</li></ul><h4>Random Variables</h4><p>We haven’t been as diligent as maybe we should have been about random variables — largely because the outcome space itself can be seen as a random variable, and it’s tempting to just blur the distinction.</p><p>A <em>real-valued random variable X</em> is a function X:Ω→ℝ. We will also often deal with a <em>vector-valued random variable</em>, in which case instead of ℝ as a target space, we’ll have ℝᵈ for some dimension d.</p><p>We can create a new probability space out of a random variable by using ℝ as our outcomes, and picking a collection of nice subsets of ℝ as our events. Unions of open subsets of ℝ is a common candidate here. The probability measure 𝕏 is defined through<br> 𝕏(U) = ℙ(X⁻¹(U))<br>or in other words, the probability of X∈U is the probability of the event consisting of everything in Ω that gets mapped to U.</p><p>For random variables, we define two (three) important functions:</p><ul><li>CDF — the <em>Cumulative Distribution Function</em> is defined as <br>CDF(x) = 𝕏((-∞,x]) = ℙ(X ≤ x)</li><li>PDF — the <em>Probability Density Function</em> is the derivative of the CDF. This means that PDF (which we have tended to denote as p) is the function such that<br>ℙ(E) = ∫ p(x)dx, where the integral goes over E. (Unicode and Medium fail me in writing arbitrary subscripts 😞</li><li>PMF — The <em>Probability Mass Function</em> is the discrete version of the PDF. In the discrete case, we can still talk about CDF and about probability measures, but CDF will be discontinuous and the PDF will be ill-behaved. A solution is to introduce something that works almost the same way, the PMF — a function p such that<br>ℙ(E) = ∑ p(x), where the sum goes over elements of E.</li></ul><p>By constructing the PMF as a sum of Dirac distributions (gadgets that integrate to step functions), then this sum is identical to the corresponding integral — this is why people can get quite sloppy in distinguishing between when to use ∫ and when to use ∑.</p><h4>Nested Expectations</h4><p>Another topic that may require a bit of attention are the nested expectation equalities we saw when discussing conditional probabilities earlier.</p><p>We know for a fact that</p><p>𝔼[ 𝔼[X|Y] ] = 𝔼[X]</p><p>But how do we get there? And what do we mean with the different expectations?</p><p>If we had had proper subscripts (Medium is less and less suited for mathematical text the more I try to use it for that), then we could have made it clearer which random variable and which probability space each expectation operates over.</p><p>Let’s be clear in our definitions. By 𝔼[X|Y] we mean the <em>conditional expectation</em>, defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*fJdlteAhrLjddYSnEfsoYQ.png" /></figure><p>We need to pick a single value for the random variable Y to condition on; and then we could think of it as partial evaluation of the joint probability. In the discrete case, as expected, the integral turns into a sum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*6H9icagC5oIWpt2umVE4vg.png" /></figure><p>Now, as we vary <em>y</em>, this conditional expectation varies too — it is a function of <em>y</em>. So we can take the expectation across different values for <em>y.</em> This gets us</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*0rU8lyKO51kxte00-OyQSQ.png" /></figure><p>The last step is because <em>p(x,y) = p(x|y)p(y)</em> defines conditional density.</p><p>To write it all out in the discrete case, it ends up looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*ABX0_5P_RjC6mSRpstMiHw.png" /></figure><h4>Wait, wait, conditional density?</h4><p>The details are finicky, but it turns out that the following relations hold:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IM63qL8XZZND98WZ0UzDxQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e66dab8d5173" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis/%E2%84%99-or-pr-or-p-or-e66dab8d5173">ℙ or Pr or p or … ?</a> was originally published in <a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis">CUNY CSI MTH594 Bayesian Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Probability Preliminaries]]></title>
            <link>https://medium.com/cuny-csi-mth594-bayesian-data-analysis/probability-preliminaries-ca46d473383b?source=rss-95f9235a303b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca46d473383b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[probability-theory]]></category>
            <dc:creator><![CDATA[Mikael Vejdemo-Johansson]]></dc:creator>
            <pubDate>Tue, 10 Sep 2019 17:23:23 GMT</pubDate>
            <atom:updated>2019-09-12T16:49:57.188Z</atom:updated>
            <content:encoded><![CDATA[<p>There are a fair number of things that the first chapter of BDA3 (Bayesian Data Analysis, 3rd ed) skips over — considering them to be expected prerequisites. I will spend a few lines of text unpacking some of these, to make sure we all are on the same starting level.</p><h3>What is probability?</h3><p>A probability space is a triple of things:</p><ol><li>A set Ω of <em>outcomes</em>.</li><li>A set ∑ of possible <em>events</em> — an event is a subset of Ω, but we are allowed to disallow some events. This way we can avoid some pathological behaviors.</li><li>A measure — ie a function ℙ: ∑→[0,1]<br>(note: measures can take values in [0,∞) — but probability measures are restricted to [0,1])</li></ol><p>We need for these to fulfill certain conditions. Some of the most important ones are:</p><ol><li>ℙ(Ø) = 0</li><li>ℙ(Ω) = 1</li><li>ℙ(X union Y) = ℙ(X) + ℙ(Y) <strong>if</strong> X is disjoint from Y</li></ol><p>It’s useful to distinguish between the cases where Ω is <em>discrete</em> or <em>continuous</em>.</p><p>Most if not all cases we will be dealing with are well behaved in a number of nice ways. One of them is that the probability will very often be given by a <em>probability density</em> (or <em>probability mass</em> in the discrete case) — in other words a function <em>p</em> such that</p><figure><img alt="The probability of an event E is the integral over E of the density function." src="https://cdn-images-1.medium.com/max/560/1*CxRfLWbDtiSHjPBg1pbxxA.png" /></figure><p>Throughout, a lot of probabilities and probability manipulations show up as integrals. The same statements hold for discrete cases — swapping each ∫ against a ∑ and summing instead of integrating.</p><p>To give us a couple of running examples to check everything against:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*L0F9uLbf3Uw-s9yPTsPSUQ.png" /></figure><ol><li>With Ω=ℝ and p(x) as to the left here, we get the ubiquitous <em>standard normal distribution</em>.</li><li>With Ω={1,2,3,4,5,6} and each outcome sharing the same probability 1/6, we get the probability space of a fair D6. This is an example of a <em>discrete uniform distribution</em>.</li></ol><h4>Joint and Marginal Probability</h4><p>Given two probability spaces with outcome sets Ω.1 and Ω.2, we can form a new probability space with outcome set Ω.1 x Ω.2 — the Cartesian product of the two original spaces. We will skip the construction of the corresponding event set and probability measure.</p><p>One useful way to visualize this is where you can draw a probability density for either of the sets as a function graph over a line, say:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*6K79fiYPLkyPUaysC2erdQ.png" /></figure><p>The joint probability of two probability spaces is a function over the product of the two — so something closer to a function on a square or a plane. We can visualize that as a square with colors representing function values like follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*vI16gFutwgHh2AcQlDSJ4w.png" /></figure><p>When writing in terms of density functions, the density of a joint probability at a particular pair of outcomes (x,y) is written p(x,y). Similarly we can define p(x,y,z,…) for taking the joint probability from several densities.</p><p>We can recover the component probabilities through integration: the <em>marginal probability density of x</em> is given by the integral <em>p(x) = </em>∫<em> p(x,y)dy</em> over all possible values for the other component.</p><p>This amounts to integrating down (or across) a single line cutting through the density map.</p><h4>Conditional Probability</h4><p>In Bayesian data analysis, almost everything focuses on <em>conditional probabilities</em>: given that we know some new data <em>y</em>, what happens to our knowledge about some unknown quantity 𝜃?</p><p>These conditional probabilities can also be defined in terms of the same kind of lines cutting through the joint probability square as in the last section. However, instead of integrating along the line and taking the result to be the interesting quantity, conditional probability restricts the function to the line and then rescales to create a new probability density function.</p><p>The rescaling is such that integrating along the line should now produce the total probability of 1 to fulfill the axioms we mentioned earlier. But integrating along a line produces the marginal probability from above. So by dividing by the marginal probability we get the resulting probability density.</p><p>Based on this we define the <em>conditional probability of x given y</em> to be <br><em>p(x | y) = p(x, y)/p(y)</em>. <br>We can easily work with more than two densities here:<br><em>p(x | y, z) = p(x,y,z)/p(y,z)<br>p(x, y | z) = p(x,y,z)/p(z)</em></p><p>The definition here rewrites into <em>p(x,y) = p(x|y)p(y)</em>. This can unpack into a whole chain of conditional probabilities:<br><em>p(x,y,z) = p(x|y,z)p(y,z) = p(x|y,z)p(y|z)p(z)</em></p><p>This points us to an important set of rules to keep in mind: how things in a conditional expression can move around — and how they can be added and removed. This starts with the notion of <em>independence</em>.</p><h4>Independent Probabilities</h4><p>Two events are <em>independent</em> if conditioning does not influence the probability:<br><em>p(x|y) = p(x)</em></p><p>This definition looks asymmetric — what about <em>p(y|x)</em> — but we’ll cover that in a moment.</p><p>If the two events are independent, then <em>p(x,y) = p(x|y)p(y) = p(x)p(y)</em>. This is often taken as the actual definition — two events are independent if their joint probability (or density, or mass) is the product of the components.</p><p>The density depicted earlier is not of two independent densities. In such pictures, independence shows up as a kind of stripiness.</p><p>Clearly when defining in terms of the joint probability, we see the symmetry. We can also recover this directly:</p><p><strong>Theorem</strong> If <em>p(x|y) = p(x)</em> then <em>p(y|x) = p(y)</em>.</p><p><strong>Proof </strong>We know <em>p(y|x) = p(x,y)/p(x)</em> by definition. Furthermore, <em>p(x,y) = p(x|y)p(y)</em>, giving us <em>p(y|x) = p(x|y)p(y)/p(x)</em>. Since <em>p(x|y) = p(x)</em> it follows that (unless <em>p(x)</em> is 0 anywhere on our outcome space…) we can cancel <em>p(x)</em> and get <em>p(y|x) = p(x)p(y)/p(x) = p(y)</em>. □</p><p>We have — sort of accidentally along the way here — also proven the most fundamental building block in Bayesian statistics: Bayes theorem.</p><p><strong>Bayes Theorem</strong> <em>p(y|x) = p(x|y)p(y)/p(x)</em>.</p><h4>Conditional Independence</h4><p>One way of viewing conditioning is that we are restricting our probability space Ω to some subset Ω’ in ∑. But the restriction is also a probability space — so everything we have done holds true inside the restriction! In particular, we can define <em>conditional independence</em> as the independence within this restriction:</p><p><em>p(x|z)</em> is conditionally independent to <em>p(y|z)</em> if <em>p(x,y|z) = p(x|z)p(y|z)</em>.</p><p>Proving equivalence between this factoring definition and the conditioning cancellation definition above is straightforward.</p><h3>Rules for manipulating conditionals</h3><p>Pulling all of this together, we get that</p><ol><li><em>p(x,y) = p(x|y)p(y)</em></li><li><em>p(x,y|z) = p(x|y,z)p(y|z)</em><br>if you are already conditioning, the condition just carries along with you.</li><li>If <em>x, y</em> are conditionally independent given <em>z</em>, then<br><em>p(x|y,z) = p(x|z)</em></li><li>It is also often useful to know that you can get the margin by integrating over all possible conditionings. This is like using points on vertical stripes in the joint probability square to compute the integral along a horizontal stripe:<br><em>p(x) = </em>∫<em> p(x|y)p(y)dy </em>— continuous case<em><br>p(x) = ∑ p(x|y)p(y) </em>— discrete case</li></ol><h3>More useful probability notation and results</h3><p>Here are some more of the things BDA3 brings up in Chapter 1.</p><ol><li>Expectation (that I like to write <em>𝔼[x]</em>) is defined as <em>𝔼[f(x)] =</em> ∫<em> f(x)p(x)dx.<br></em>Expectation is linear: <em>𝔼[ax+by] = a𝔼[x]+b𝔼[y]</em>— because integrals are linear.</li><li>Variance (that I like as <em>𝕍[x]</em> — but I’m possibly too fond of blackboard bold) is the expectation of the mean square deviation from the mean.<br><em>𝕍[x] = 𝔼[(x-𝔼[x])²] = 𝔼[x²]-𝔼[x]²</em>.</li><li>More importantly we get covariance — also for random vectors (yes, we skimmed past the definition of random variables here. sorry.) — as the expected product of deviations from the expectation:<br><em>cov(x,y) = 𝔼[(x-𝔼[x])(y-𝔼[y])ᵀ]</em></li><li>The expected value when conditioning changes with what you condition on — but if you take the expected value over all conditions, you get the marginal distribution back:<br><em>𝔼[𝔼[x|y]] = 𝔼[x]</em></li><li>For variance, we get a combination of expectations and variances:<br>𝔼[var(x|y)] + var(𝔼[x|y]) = var(x)</li><li>4. and 5. hold in a vector setting as well.</li></ol><p>Now, this should set our stage pretty thoroughly I hope.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca46d473383b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis/probability-preliminaries-ca46d473383b">Probability Preliminaries</a> was originally published in <a href="https://medium.com/cuny-csi-mth594-bayesian-data-analysis">CUNY CSI MTH594 Bayesian Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MTH513 Course blog submission instructions]]></title>
            <link>https://medium.com/cuny-csi-mth513/mth513-course-blog-submission-instructions-441c0887c7c9?source=rss-95f9235a303b------2</link>
            <guid isPermaLink="false">https://medium.com/p/441c0887c7c9</guid>
            <category><![CDATA[medium]]></category>
            <dc:creator><![CDATA[Mikael Vejdemo-Johansson]]></dc:creator>
            <pubDate>Wed, 20 Mar 2019 20:09:04 GMT</pubDate>
            <atom:updated>2019-03-20T20:10:01.901Z</atom:updated>
            <content:encoded><![CDATA[<p>We will be using Medium for the MTH513 (Machine Learning) blog posts. Some important details for writing your post follow here:</p><ol><li>Create a Medium account, and then let the professor know how to find your account. We can look at it during class time if you are uncertain of how to do this.</li><li>Your professor will give you access to the <a href="https://medium.com/cuny-csi-mth513">course blog</a>.</li><li>Write your blog post.</li><li>At the bottom of your finished blog post, click the … button and then pick the course blog as the publication to submit to.</li><li>Feedback will be given directly on the post, and you can edit it after publication.</li></ol><p>Important (and less obvious) detail for editing: use ``` (three backticks) at the beginning of a text block to embed code snippets into your post. Images can be uploaded by clicking the (+) symbol to the left of an empty code block.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=441c0887c7c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cuny-csi-mth513/mth513-course-blog-submission-instructions-441c0887c7c9">MTH513 Course blog submission instructions</a> was originally published in <a href="https://medium.com/cuny-csi-mth513">CUNY CSI MTH513</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>