# NOT RUN {
# define a simple Bayesian model
x <- rnorm(10)
mu <- normal(0, 5)
sigma <- lognormal(1, 0.1)
distribution(x) <- normal(mu, sigma)
m <- model(mu, sigma)
# carry out mcmc on the model
draws <- mcmc(m, n_samples = 100)
# add some more samples
draws <- extra_samples(draws, 200)
#' # initial values can be passed for some or all model variables
draws <- mcmc(m, chains = 1, initial_values = initials(mu = -1))
# if there are multiple chains, a list of initial values should be passed,
# othewise the same initial values will be used for all chains
inits <- list(initials(sigma = 0.5), initials(sigma = 1))
draws <- mcmc(m, chains = 2, initial_values = inits)
# you can auto-generate a list of initials with something like this:
inits <- replicate(4,
initials(mu = rnorm(1), sigma = runif(1)),
simplify = FALSE)
draws <- mcmc(m, chains = 4, initial_values = inits)
# or find the MAP estimate
opt_res <- opt(m)
# get the MLE of the normal variance
mu <- variable()
variance <- variable(lower = 0)
distribution(x) <- normal(mu, sqrt(variance))
m2 <- model(variance)
# adjust = FALSE skips the jacobian adjustments used in MAP estimation, to
# give the true maximum likelihood estimates
o <- opt(m2, adjust = FALSE)
# the MLE corresponds to the *unadjusted* sample variance, but differs
# from the sample variance
o$par
mean((x - mean(x)) ^ 2) # same
var(x) # different
# initial values can also be passed to optimisers:
o <- opt(m2, initial_values = initials(variance = 1))
# and you can return a list of the hessians for each of these parameters
o <- opt(m2, hessians = TRUE)
o$hessians
# to get a hessian matrix across multiple greta arrays, you must first
# combine them and then split them up for use in the model (so that the
# combined vector is part of the model) and pass that vector to model:
params <- c(variable(), variable(lower = 0))
mu <- params[1]
variance <- params[2]
distribution(x) <- normal(mu, sqrt(variance))
m3 <- model(params)
o <- opt(m3, hessians = TRUE)
o$hessians
# }
Run the code above in your browser using DataCamp Workspace