Bayesian inference with rejection sampling
This code implements Bayesian inference using the rejection sampling method to simulate from the posterior distribution. The problem involves estimating the posterior distribution for a model with a normal likelihood and a Cauchy prior
Likelihood
and
Prior
which is a heavy-tailed distribution with no finite mean or variance
Target The posterior distribution is proportional to the product of the likelihood and the prior, which is intractable
We approximate the posterior distribution by generating samples using rejection sampling and compute the posterior expectation (Bayesian estimate) using a Monte Carlo approximation
Target Function target.tilde(theta):
Represents the unnormalized posterior: likelihood
times the prior
(Cauchy)
Proposal Distribution proposal.tilde(theta)
The proposal distribution is the Cauchy distribution
which is a good candidate due to the prior also being Cauchy
Rejection Sampling Procedure
A sample
is drawn from the Cauchy distribution using rt(1, 1)
A uniform random variable
is generated
The acceptance probability
is computed as the ratio of the target to the proposal, scaled by
If
, the sample is accepted and stored in simu[i]; otherwise, the loop continues until a valid sample is accepted
nsimu: Keeps track of the total number of simulations attempted (including rejected samples)
Monte Carlo Estimate
After generating the samples, the posterior expectation (or any other statistic of interest) can be approximated using the empirical mean of the simulated values stored in simu
This method leverages rejection sampling and the Monte Carlo approach to perform Bayesian inference for models where the posterior distribution cannot be computed exactly
# Bayesian inference problem
# likelihood x|theta ~ N(theta,1)
# prior theta ~ Cauchy
# we observe x = 0.8
# the posterior distribution is intractable
# Bayesian estimate, the posterior expectation is also intractable
# we use the rejection sampling scheme to simulate from the posterior
# we approximate the posterior expectation using the empirical mean over the simulations
# that is a Monte Carlo method
x <- 0.8
target.tilde <- function(theta) exp(x*theta-theta^2/2)/(1+theta^2)
proposal.tilde <- function(theta) 1/(1+theta^2) # Cauchy (Student(1))
M.tilde <- exp(x^2/2)
n <- 10000
simu <- rep(0,n)
nsimu <- 0
for (i in 1:n)
{
bool <- TRUE
while (bool)
{
y <- rt(1,1) # one simulation from a Cauchy
u <- runif(1) # one simulation from a uniform on [0,1]
rho <- target.tilde(y)/(proposal.tilde(y)*M.tilde) # acceptance probability
if (u <= rho) {simu[i] <- y ; bool <- FALSE}
nsimu <- nsimu +1
}
}