Bayesian statistics I
A screen-reader-friendly transcript of the lecture slides: all slide text, tables, figure descriptions, and speaker notes.
About these notes
Each section is one slide. Figures carry text descriptions where available. For the concepts with worked examples, also read the plain-language summary and lab for this session.Slide 1
Introduction to Bayesian Analysis
Many slides adapted from Matt Falcy ODFW, and SESYNC course by Chris Che-Castaldo, Mary B. Collins, N. Thompson Hobbs (with permission)
Slide 2
- “Frequentist” or classical inference
- Probability is a long-run relative frequency.
- Parameters are fixed and unknown constants.
- Statistical procedures are judged by how they perform over hypothetical replications of data that are never actually observed.
- Bayesian inference
- Probability is a degree of belief.
- Once data are observed, they are treated as fixed (not random) values.
- Parameters are unknown, therefore treated as random variables
- Rules of probability used to revise “prior” beliefs in light of data.
Frequentist and Bayesian inference
Slide 3
Remember Bayes Rule?
We derived this from simple rules of conditional probability
P(A,B) = P(A|B)P(B)
Slide 4
1% of women at age forty who participate in routine screening have breast cancer. 80% of women with breast cancer will get positive mammographies. 9.6% of women without breast cancer will also get positive mammographies. A woman in this age group had a positive mammography in a routine screening. What is the probability that she actually has breast cancer?
[c | + ] =
[ +|c ] * [c]
[ + ]
[+ |c ] * [c]
[ +| c]*[c] + [+ | not c]*[not c]
=
0.8 * 0.01
0.8*0.01 + 0.096*0.99
= 0.0776
95 out of 100 doctors put it at 0.70 to 0.80 (Eddy 1982, with replicated results)!!
Slide 5
We had complete information about medical testing probabilities
In almost all practical scenarios, we will just have data, y, and then want to make inference about parameters, θ.
Slide 6
[θ | y] =
[y | θ] [θ]
[y]
What is the marginal probability of the data?
L(θ|y) = [y| θ] ≠ [θ | y]
Bayes Rule
Prior
Posterior
Slide 7
Integrating B out of the joint distribution
Slide 8
[θ | y] =
[y | θ] [θ]
[y]
What is the marginal probability of the data?
[y] = [y| θ] [θ] dθ
- It’s the integral (or sum) of the numerator!
- This “scales” the numerator so that it integrates to 1.
L(θ|y) = [y| θ] ≠ [θ | y]
We call this a normalizing constant
Slide 9
P(X, Y) or [X,Y]
P(X) or [X], and P(Y) or [Y]
- Sum or integrate over all values of the random variable you DON’T care about
- Or if you’ve sampled from the joint distribution, just take the values of the variable of interest
Slide 10
E.g. Number of chocolate chips observed in cookies
For simple problem, can use numerical integration (what would we integrate)
Slide 11
E.g. Number of chocolate chips observed in cookies
For simple problem, can use numerical integration (what would we integrate)
- fun = function(x){
- dpois(5,x)*dpois(10,x)*dpois(11,x)*dpois(12,x)*dpois(14,x)*dpois(9,x)*dpois(8,x)*dpois(6,x) #The likelihood
- *dgamma(x,0.0001,0.0001)} #The prior
- integrate(fun,0,20) #[y]; Integral of the numerator = 8.010413e-14
- integrate(fun,0,20)$value/8.010413e-14
- x=seq(0,20,0.1)
- plot(x,fun(x),type="l")
- plot(x,fun(x)/8.010413e-14,type="l")
Slide 12
[y| θ] “likelihood”
- Data: We get 5 heads out of 12 flips. Binomial process. Make inference on p.
- How would we have done this with maximum likelihood?
- [θ]
- “vague prior”
Beta_pdf(1,1)
Binomial Example
Slide 13
How would we scale this so that it integrates to 1 and becomes a “real distribution”?
[y|θ][θ] Still doesn’t integrate to 1
Slide 14
- The integral is 0.077.
- So lets divide every number on the y-axis by 0.077
- Divide [y|θ][θ] by the are under it’s curve ([y])
- AKA “integral”
Slide 15
- > fun1<-function(x){dbinom(5,12,x)}
- > integrate(fun1,0,1)
- 0.07692308 with absolute error < 8.5e-16
- > fun2<-function(x){dbinom(5,12,x)*dbeta(x,1,1)/0.07692308}
- > integrate(fun2,0,1)
- 1 with absolute error < 1.1e-14
Notice new scale on y-axis. NOW this integrates to 1 and is a proper distribution
- Divide by marginal distribution of the data,
- Which is just a “normalizing constant”
Slide 16
The Bayesian inferential paradigm requires subjective prior beliefs!
Slide 17
The integral of this thing is 0.092308
The integral of this thing is 1
We have 5 heads out of 12 flips – 5/12 = 0.417. Now let’s use an informative prior, Beta(3,2).
Why is posterior mean larger than 0.417?
Question: What is the mean of a Beta(3,2)? What are we saying with this?
E[X] = α / (α + β)
var[X] = αβ / ((α + β)² (α + β + 1))
Slide 18
Instead of 5 heads out of 12 flips, lets see what happens with 50 heads out of 120 flips (50/120 = 0.417)
The integral of this thing is 0.010036
The integral of this thing is 1
- The more data you have, the lower the likelihood.
- (Think here. Why? Likelihood of datum vs. data)
50/120=0.41667
Look at uncertainty
Much closer to data mean than posterior mean now
Slide 19
Think about what we just did
- We multiplied the prior and likelihood
- Each value was divided by the integral of the prior*likelihood, to “normalize” or scale so that it integrates to 1 (thereby satisfying a definition of probability).
- This gave us a posterior for p to make probabilistic inference
- [θ|y] = [y|θ] [θ] / ∫θ [y|θ] [θ] dθ
- (posterior = likelihood × prior ÷ marginal distribution of the data)
Slide 20
Slide 21
Slide 22
Slide 23
If we transform this into many conditional distributions, then we can sample from it
Slide 24
The conditional distributions can be represented by a Directed Acyclic Graph (DAG) based on the dependencies of the process
Variables with arrow heads should be on LHS of conditionality. They depend on tails of arrows, which go on RHS of conditionality. Variables without arrow pointing to them need a prior.
Slide 25
- Complex models are now in widespread use in fisheries and wildlife
- E.g. Joel Ruprecht’s 2021 density estimation paper using spatial capture recapture and spatial mark resight. Can incorporate GPS data, marking process, integrate multiple datasets, etc.
Slide 26
- But let’s start simpler!
- Back to coin flip problem
Slide 27
Instead of 5 heads out of 12 flips, lets see what happens with 50 heads out of 120 flips.
The integral of this thing is 0.010036
The integral of this thing is 1
- The more data you have, the lower the likelihood.
- (Think here. Why? Likelihood of datum vs. data)
50/120=0.41667
Look at uncertainty
Much closer to data mean than posterior mean now
Slide 28
Funny thing is that the beta distribution is the “conjugate prior” to the binomial distribution.
Note: 3 and 2 come from the beta prior
“conjugate priors” have the special property that the posterior follows the same distribution as the prior. This gives us a ‘closed-form’ solution for the posterior
Slide 29
Mean of the NEW Beta distribution is
The new Beta distribution for the posterior of p
- Now we can see precisely how much information the prior adds!
- A Beta(1,1) prior is like observing 1 more success and 1 more failure because y increases by 1 and n increases by 2
- A Beta(3,2) prior is like observing 3 more success and 2 more failures because y increases by 3 and n increases by 5
- Large datasets typically swamp priors, but how would you minimize information in this prior?
- That is called the Haldane prior – an “improper prior”. What is its functional form here?
Sampling from a known posterior is called “Gibbs sampling”
αnew = y + α, βnew = β + n − y
αnew / (αnew + βnew) = (y + α) / (α + β + n)
Slide 30
Beta-Binomial Walkthrough
Slide 31
To reiterate: Conjugacy
- “The beta is the conjugate prior for the binomial distribution”
- “The gamma is the conjugate prior for the Poisson distribution”
- So what does that mean about our Poisson problem from earlier?
- Let’s derive this together
Slide 32
Figure 32.1 — needs description This slide contains an image not yet described in text. Instructor: add a description.
Slide 33
Figure 33.1 — needs description This slide contains an image not yet described in text. Instructor: add a description.
Slide 34
Slide 35
Conjugacy relationships
Note this is the “precision” or inverse of the variance
Slide 36
- The elegance of conjugate priors is not available except for simple models.
- Symbolic calculus usually not possible when extended into multiple dimensions (models with many parameters) and more complex probability distributions.
- The numerical integrations we did earlier…
- can’t be done for high-dimensional (many parameters) problems
- http://math.stackexchange.com/questions/425782/why-does-monte-carlo-integration-work-better-than-naive-numerical-integration-in
- https://en.wikipedia.org/wiki/Numerical_integration
Unfortunately…
- > fun1<-function(x){dbinom(5,12,x)}
- > integrate(fun1,0,1)
- 0.07692308 with absolute error < 8.5e-16
(We did them to illustrate concepts. Not advice on solving real Bayesian problems)
Slide 37
- Because we couldn’t solve high-dimensional integrals, Thomas Bayes’ (1702-1761) approach to inferential logic languished for two centuries!
- In the mean time, Ronald Fisher and others developed an alternative approach that did not use priors and did not attempt to characterize parameters probabilistically.
Slide 38
Markov chain Monte Carlo (MCMC)
Then comes WWII and some mathematical physicists at Los Alamos needed to evaluate high dimensional integrals.
Note: like Newton’s invention of calculus to study gravity/orbits
“Markov” means dependence only on the previous sample
“Monte Carlo” means estimation of properties of a distribution by random sampling from the distribution. Apparently named for the Grand Casino in Monte Carlo
Slide 39
We’re going to sample from the numerator
Pick values of p. Keep them in the chain at a rate proportional to the relative value on the y-axis.
The Metropolis Algorithm
- Nicholas Metropolis
- (1915-1999)
We say: ”The posterior is proportional to the likelihood times the prior”
Slide 40
For example
The symmetry requirement can be problematic if θ is constrained (e.g. standard deviations and proportions must be positive).
If this is too big, then you propose lots of values that don’t get accepted, which is inefficient. If too small there is too much autocorrelation and it takes forever to sample the full posterior
The Metropolis Algorithm
- Nicholas Metropolis
- (1915-1999)
- A small modification:
- The “Metropolis-Hastings” algorithm allows for asymmetric proposals
Slide 41
Time series of an MCMC
Slide 42
Time series of an MCMC
Slide 43
Time series of 3 MCMCs
Slide 44
count
count
Here is the posterior of the joint distribution (both parameters) from which we also have the marginal distribution for each
Slide 45
https://mbjoseph.github.io/posts/2018-12-25-animating-the-metropolis-algorithm/
Slide 46
Slide 47
- https://chi-feng.github.io/mcmc-demo/
There are now many algorithms to solve this problem
- Click on an algorithm below to view interactive demo:
- Random Walk Metropolis Hastings
- Adaptive Metropolis Hastings [1]
- Hamiltonian Monte Carlo [2]
- No-U-Turn Sampler [2]
- Metropolis-adjusted Langevin Algorithm (MALA) [3]
- Hessian-Hamiltonian Monte Carlo (H2MC) [4]
- Gibbs Sampling
- Stein Variational Gradient Descent (SVGD) [5]
- Nested Sampling with RadFriends (RadFriends-NS) [6]
Slide 48
BUGS, JAGS, Nimble, STAN, and INLA oh my!
- In 2008, my first Bayesian professor, Herbie Lee, thought WinBUGS shouldn’t be taught because it would make it too easy so that incompetent people would implement poorly specified models
- Now BUGS (Bayesian Analysis Using Gibbs Sampling) is very common
- OpenBUGS and WinBUGS needs Windows. JAGS was designed to work on multiple platforms.
- Unlike OpenBUGS and WinBUGS, which have a graphical user interface, JAGS works on the command line and interfaces nicely with R. It can be run on UNIX clusters like OSU’s CQLS.
- Nimble is similar to JAGS, but is more flexible and faster for many problems in Ecology!
- STAN uses the very fast Hamiltonian MCMC algorithm, but doesn’t use BUGS language
- INLA is extremely fast because it approximates the posterior instead of sampling. Used for a restricted subset of problems.
Slide 49
MSY = rK/4
Greatest population growth rate
r
K
Greatest per-capita growth rate
“Negative density dependence”
Estimating parameters in logistic population growth
dN/dt = rN(1 − N/K)
(1/N) dN/dt = r(1 − N/K) = r − rN/K
(1/N) dN/dt
N
Slide 50
- JAGS PRIMER
- estimating parameters in logistic population growth
- From Hobbs and Che-Castaldo’s SESYNC course
- Observations of per-capita growth rate paired with population size
- Ah ha, our scientific model is a line! We know what to do with lines!
- Let’s try it with our standard tools.
(1/N)(dN/dt) = r − (r/K) N
Slide 51
reg=lm(GrowthRate~PopulationSize,data=Logistic)
Good Ole Regression Approach
But what can we say about K, K/2 or MSY?
(1/N)(dN/dt) = r − (r/K) N
Slide 52
- JAGS PRIMER
- estimating parameters in logistic population growth
- Joint posterior distribution of parameters is proportional to likelihood*prior
- We want positive continuous values for r and K. Bring on the gamma!
- The gamma is the conjugate prior for the precision term in Normal distribution
- But why gamma(0.001, 0.001)
- μi = r − r xi / K
- [r, K, τ | y] ∝ ∏i=1n [yi | μi, τ] [r] [K] [τ]
- [r, K, τ | y] ∝ ∏i=1n normal(yi | μi, τ) · gamma(K | .001, .001) · gamma(τ | .001, .001) · gamma(r | .001, .001)
Slide 53
- “Bayesian Network” or
- ”Directed Acyclic Graph”
Slide 54
- JAGS PRIMER
- estimating parameters in logistic population growth
JAGS parses this code to set up MCMC sampling, including proposal distribution, tuning parameters, and returns MCMC chain for each parameter so we can approximate posterior distributions and find associated statistics (e.g., means, medians, standard deviations, quantiles).
In general, we always need
#Use “for loop” to loop over all the data
Normal distribution in JAGS is parameterized with precision, not variance or standard deviation
Slide 55
Some other priors
- sink("LogisticJAGS.R")
- cat("
- model {
- # priors
- K ~ dunif(0, 4000)
- r ~ dunif (0, 2)
- sigma ~ dunif(0, 50)
- tau <- 1/sigma^2
- # likelihood
- for(i in 1:n) {
- mu[i] <- r - r/K * x[i]
- y[i] ~ dnorm(mu[i], tau)
- }
- } ",fill = TRUE)
- sink()
Use “sink” to keep all your code in one R script, but can also make JAGS code separately
Normal distribution in JAGS is parameterized with precision, not variance or standard deviation
- μi = r − r xi / K
- τ = 1 / σ²
- [r, K, σ | y] ∝ ∏i=1n normal(yi | μi, τ) · uniform(K | 0, 4000) · uniform(σ | 0, 5) · uniform(r | 0, 2)
Slide 56
- JAGS PRIMER
- estimating parameters in logistic population growth
- Unlike with least squares or maximum likelihood, with Bayesian statistics it is easy to derive chains for other quantities of interest and their posterior distributions.
- These are called “derived quantities”
- For example, K/2, rK/4, N as a function of time, dN/dt as a function of N with uncertainty, or incorporate errors in the observations of population growth rate or population size.
This is a BFD!
Slide 57
JAGS PRIMER
For small models, use the sink() function to write your JAGS model to file for input
JAGS is not a procedural language like R. It is not a set of instructions to be executed sequentially. It is a way to translate a mathematical statement into syntax that determine the MCMC sampler that JAGS uses behind the scenes
Remember another sink() to write the file
fill = TRUE to print on separate lines
Slide 58
JAGS PRIMER – slightly different approaches for rjags, jagsUI, and R2jags packages
Use jags.model() to run JAGS. Specify the data, initial values, and MCMC parameters
Use update() to add iterations to an existing model. Use coda.samples() to access the MCMC chains
JAGS uses this to optimize the MCMC parameters
The burn in
Posterior draws we keep
The burn in
The samples
Slide 59
JAGS PRIMER
- Use update() to add iterations to an existing model. Use coda.samples() to access the MCMC chains.
- Use MCMCsummary() to summarize the parameters and derived quantities (if they exist)
Note that Rhat near 1 means that there is good convergence. This is for model diagnostics.
Slide 60
Nimble PRIMER
- BUGS Code is written in a nimbleCode() function.
- Models compiled into C++ and are more customizable
- Can be much faster than JAGS
- Can produce MCMC output in one line with nimbleMCMC()
- No separate adaption phase to tune MCMC
- Can also compile model first and then run nimbleMCMC
Slide 61
Logistic Growth in Nimble. Visualize and interpret the output