Lab 2: Posterior and Posterior Predictive Simulation

Lab 2: Posterior and Posterior Predictive Simulation#

This lab is adapted from AM207 (Harvard). Data files are in the book’s data/ folder. Worked solutions are collapsed: try each exercise before expanding them.

In this lab

  1. Exploring the Beta Prior

  2. Exploring the Beta-Binomial Model

  3. Exploring the Normal-Normal Model

Hide code cell content

### Import basic libraries
import numpy as np
import scipy as sp
import pandas as pd
import sklearn as sk
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
%matplotlib inline

The Beta Prior#

In the beta-binomial model

\[\begin{split}\begin{aligned} Y &\sim Bin(N, \theta)\\ \theta &\sim Beta(\alpha, \beta) \end{aligned}\end{split}\]

the beta distribution represents our prior belief about the parameter \(\theta\).

Using the code for visualizing the beta pdf to experiment with different values of \(\alpha, \beta\), make a specific conjecture about how the hyperparameters \(\alpha, \beta\) effect the shape of the pdf.

#prior definition: beta distribution
alpha = 2
beta = 2

#prior definition: beta distribution
prior = sp.stats.beta(alpha, beta).pdf

fig, ax = plt.subplots(1, 1, figsize=(10, 5))
x = np.linspace(0, 1, 100)
ax.plot(x, prior(x), color='blue')
ax.set_title('Visualization of the Prior')
plt.show()
../_images/21389cb1b667ae619b5df40fa8193ea8eb4dbb8d5348d875e85de2c925d7db1d.png

The Beta-Binomial Posterior and Posterior Predictive#

Say that you generated the data using 10 flips of a coin whose probability of heads is \(\theta = 0.3\).

  1. Visualize the posterior distribution given this data.

  2. Using the code for visualizing the beta pdf to experiment with different values of \(\alpha, \beta\), make a specific conjecture about how the hyperparameters \(\alpha, \beta\) effect the posterior distribution.

  3. Make an argument for how best to choose values of \(\alpha, \beta\).

  4. Simulate data from the posterior predictive. Compare the posterior predictive and the observed data. What does this comparison say about your model?

The Normal-Normal Model#

  1. Generate \(N=50\) data points from \(\mathcal{N}\left( 3, 5\right)\). Visualize their empirical distribution.

  2. Set your likelihood to be \(Y_n \sim \mathcal{N}(\mu, 5)\). In this case, we are going to make inference about the mean \(\mu\). Choose a normal prior for \(\mu\), \(\mu \sim\mathcal{N}(-1, 0.5)\) and visualize the posterior over \(\mu\).

  3. Sample \(N=50\) points from your posterior predictive. Compare the empirical distribution of the observed data with that of the posterior predictive. What does this comparison say about your model?

  4. Repeat this experiment different values of \(N\) (some very small, some large). Make a conjecture about the relationship between \(N\) and the posterior and posterior predictive distributions of this model.