gretaR is a Bayesian statistical modelling package
for R built on the torch backend. It provides an intuitive,
R-native syntax for defining probabilistic models, which are then
compiled to differentiable torch computations and sampled using
Hamiltonian Monte Carlo (HMC) or the No-U-Turn Sampler (NUTS).
Key features:
posterior,
bayesplot, and looSuppose we observe data from a normal distribution and want to estimate the mean and standard deviation.
library(gretaR)
# Simulate data
set.seed(42)
y_obs <- rnorm(100, mean = 3, sd = 1.5)
# Define priors
mu <- normal(0, 10)
sigma <- half_cauchy(5)
# Wrap observed data
y <- as_data(y_obs)
# Define likelihood
distribution(y) <- normal(mu, sigma)
# Compile model
m <- model(mu, sigma)
print(m)# Draw posterior samples
fit1 <- mcmc(m, n_samples = 500, warmup = 500, chains = 2)
# Summarise
summary(fit1)The two chains mix over the same range of mu and
sigma from the first sampled draw, with no visible trend or
one chain sitting apart from the other – consistent with the R-hat close
to 1 and the effective sample size reported by
summary(fit1).
# Simulate data
set.seed(123)
n <- 100
x_obs <- rnorm(n)
y_obs <- 2 + 3 * x_obs + rnorm(n, 0, 0.5)
# Reset model state for new model
reset_gretaR_env()
# Priors
alpha <- normal(0, 10)
beta <- normal(0, 10)
sigma <- half_cauchy(2)
# Data
x <- as_data(x_obs)
y <- as_data(y_obs)
# Linear predictor
mu <- alpha + beta * x
# Likelihood
distribution(y) <- normal(mu, sigma)
# Compile
m <- model(alpha, beta, sigma)
print(m)The three densities are unimodal, chain-to-chain agreement is close,
and the posterior mass for alpha, beta and
sigma brackets the values used to simulate
y_obs, confirming the model recovers the generating
parameters on this synthetic dataset.
as_data()normal(), half_cauchy(), etc.)+, *, log(), etc.)distribution(y) <- ...model()mcmc()posterior,
bayesplot, or loo| Function | Distribution | Support |
|---|---|---|
normal(mean, sd) |
Normal | \((-\infty, \infty)\) |
half_normal(sd) |
Half-Normal | \((0, \infty)\) |
half_cauchy(scale) |
Half-Cauchy | \((0, \infty)\) |
student_t(df, mu, sigma) |
Student-t | \((-\infty, \infty)\) |
uniform(lower, upper) |
Uniform | \((a, b)\) |
exponential(rate) |
Exponential | \((0, \infty)\) |
gamma_dist(shape, rate) |
Gamma | \((0, \infty)\) |
beta_dist(alpha, beta) |
Beta | \((0, 1)\) |
bernoulli(prob) |
Bernoulli | \(\{0, 1\}\) |
binomial_dist(size, prob) |
Binomial | \(\{0, \ldots, n\}\) |
poisson_dist(rate) |
Poisson | \(\{0, 1, 2, \ldots\}\) |
multivariate_normal(mean, cov) |
Multivariate Normal | \(\mathbb{R}^k\) |
vignette("hierarchical-models", package = "gretaR")bayesplot::mcmc_trace() and
bayesplot::mcmc_dens_overlay() for diagnosticsloo::loo() on the posterior
draws