if (FALSE) {
# 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, hessian = TRUE)
o$hessian
# 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, hessian = TRUE)
o$hessian
# using set.seed or tensorflow::set_random_seed to set RNG for MCMC
a <- normal(0, 1)
y <- normal(a, 1)
m <- model(y)
set.seed(12345)
one <- mcmc(m, n_samples = 1, chains = 1)
set.seed(12345)
two <- mcmc(m, n_samples = 1, chains = 1)
# same
all.equal(as.numeric(one), as.numeric(two))
tensorflow::set_random_seed(12345)
one_tf <- mcmc(m, n_samples = 1, chains = 1)
tensorflow::set_random_seed(12345)
two_tf <- mcmc(m, n_samples = 1, chains = 1)
# same
all.equal(as.numeric(one_tf), as.numeric(two_tf))
# different
all.equal(as.numeric(one), as.numeric(one_tf))
}
Run the code above in your browser using DataLab