Example: Logistic Regression with Random Effects
We will use the Seeds for demonstration. This example concerns the proportion of seeds that germinated on each of 21 plates. Here, we transform the data into a NamedTuple:
data = (
r = [10, 23, 23, 26, 17, 5, 53, 55, 32, 46, 10, 8, 10, 8, 23, 0, 3, 22, 15, 32, 3],
n = [39, 62, 81, 51, 39, 6, 74, 72, 51, 79, 13, 16, 30, 28, 45, 4, 12, 41, 30, 51, 7],
x1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
x2 = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
N = 21,
)where r[i] is the number of germinated seeds and n[i] is the total number of the seeds on the $i$-th plate. Let $p_i$ be the probability of germination on the $i$-th plate. Then, the model is defined by:
\[\begin{aligned} b_i &\sim \text{Normal}(0, \tau) \\ \text{logit}(p_i) &= \alpha_0 + \alpha_1 x_{1 i} + \alpha_2 x_{2i} + \alpha_{12} x_{1i} x_{2i} + b_{i} \\ r_i &\sim \text{Binomial}(p_i, n_i) \end{aligned}\]
where $x_{1i}$ and $x_{2i}$ are the seed type and root extract of the $i$-th plate. The original BUGS program for the model is:
model
{
for( i in 1 : N ) {
r[i] ~ dbin(p[i],n[i])
b[i] ~ dnorm(0.0,tau)
logit(p[i]) <- alpha0 + alpha1 * x1[i] + alpha2 * x2[i] +
alpha12 * x1[i] * x2[i] + b[i]
}
alpha0 ~ dnorm(0.0, 1.0E-6)
alpha1 ~ dnorm(0.0, 1.0E-6)
alpha2 ~ dnorm(0.0, 1.0E-6)
alpha12 ~ dnorm(0.0, 1.0E-6)
tau ~ dgamma(0.001, 0.001)
sigma <- 1 / sqrt(tau)
}Modeling Language
Writing a Model in BUGS
Language References:
Implementations in C++ and R:
- JAGS and its user manual
- Nimble
Language Syntax:
Writing a Model in Julia
We provide a macro which allows users to write down model definitions using Julia:
seeds = @bugs begin
for i in 1:N
r[i] ~ dbin(p[i], n[i])
b[i] ~ dnorm(0.0, tau)
p[i] = logistic(alpha0 + alpha1 * x1[i] + alpha2 * x2[i] + alpha12 * x1[i] * x2[i] + b[i])
end
alpha0 ~ dnorm(0.0, 1.0E-6)
alpha1 ~ dnorm(0.0, 1.0E-6)
alpha2 ~ dnorm(0.0, 1.0E-6)
alpha12 ~ dnorm(0.0, 1.0E-6)
tau ~ dgamma(0.001, 0.001)
sigma = 1 / sqrt(tau)
endBUGS syntax carries over almost one-to-one to Julia, with minor exceptions. Modifications required are minor: curly braces are replaced with begin ... end blocks, and for loops do not require parentheses. In addition, Julia uses f(x) = ... as a shorthand for function definition, so BUGS' link function syntax is disallowed. Instead, user can call the inverse function of the link functions on the RHS expressions.
Support for Legacy BUGS Programs
The @bugs macro also works with original (R-like) BUGS syntax:
seeds = @bugs("""
model{
for( i in 1 : N ) {
r[i] ~ dbin(p[i],n[i])
b[i] ~ dnorm(0.0,tau)
logit(p[i]) <- alpha0 + alpha1 * x1[i] + alpha2 * x2[i] +
alpha12 * x1[i] * x2[i] + b[i]
}
alpha0 ~ dnorm(0.0,1.0E-6)
alpha1 ~ dnorm(0.0,1.0E-6)
alpha2 ~ dnorm(0.0,1.0E-6)
alpha12 ~ dnorm(0.0,1.0E-6)
tau ~ dgamma(0.001,0.001)
sigma <- 1 / sqrt(tau)
}
""", true, true)By default, @bugs will translate R-style variable names like a.b.c to a_b_c, user can pass false as the second argument to disable this. User can also pass true as the third argument if model { } enclosure is not present in the BUGS program. We still encourage users to write new programs using the Julia-native syntax, because of better debuggability and perks like syntax highlighting.
Basic Workflow
Compilation
The model definition returned by @bugs is callable: call it with the data (a NamedTuple) to construct a BUGSModel, which implements the LogDensityProblems.jl interface.
model = seeds(data)BUGSModel (parameters are in transformed (unconstrained) space, with dimension 26):
Model parameters:
alpha2
b[21], b[20], b[19], b[18], b[17], b[16], b[15], b[14], b[13], b[12], b[11], b[10], b[9], b[8], b[7], b[6], b[5], b[4], b[3], b[2], b[1]
tau
alpha12
alpha1
alpha0
Variable sizes and types:
b: size = (21,), type = Vector{Float64}
p: size = (21,), type = Vector{Float64}
n: size = (21,), type = Vector{Int64}
alpha2: type = Float64
sigma: type = Float64
alpha0: type = Float64
alpha12: type = Float64
N: type = Int64
tau: type = Float64
alpha1: type = Float64
r: size = (21,), type = Vector{Int64}
x1: size = (21,), type = Vector{Int64}
x2: size = (21,), type = Vector{Int64}Parameter values will be sampled from the prior distributions in the original space.
Calling the model definition is the supported way to construct a BUGSModel. It wraps compile, which is kept for backward compatibility (compile(seeds, data) does the same thing) but is now mostly an internal function — you shouldn't need to call it directly.
We can provide initial parameter values after construction with initialize!:
initializations = (alpha = 1, beta = 1)
initialize!(model, initializations)BUGSModel (parameters are in transformed (unconstrained) space, with dimension 26):
Model parameters:
alpha2
b[21], b[20], b[19], b[18], b[17], b[16], b[15], b[14], b[13], b[12], b[11], b[10], b[9], b[8], b[7], b[6], b[5], b[4], b[3], b[2], b[1]
tau
alpha12
alpha1
alpha0
Variable sizes and types:
b: size = (21,), type = Vector{Float64}
p: size = (21,), type = Vector{Float64}
n: size = (21,), type = Vector{Int64}
alpha2: type = Float64
sigma: type = Float64
alpha0: type = Float64
alpha12: type = Float64
N: type = Int64
tau: type = Float64
alpha1: type = Float64
r: size = (21,), type = Vector{Int64}
x1: size = (21,), type = Vector{Int64}
x2: size = (21,), type = Vector{Int64}
initialize! also accepts a flat vector. In this case, the vector should have the same length as the number of parameters, but values can be in transformed space:
initialize!(model, rand(26))BUGSModel (parameters are in transformed (unconstrained) space, with dimension 26):
Model parameters:
alpha2
b[21], b[20], b[19], b[18], b[17], b[16], b[15], b[14], b[13], b[12], b[11], b[10], b[9], b[8], b[7], b[6], b[5], b[4], b[3], b[2], b[1]
tau
alpha12
alpha1
alpha0
Variable sizes and types:
b: size = (21,), type = Vector{Float64}
p: size = (21,), type = Vector{Float64}
n: size = (21,), type = Vector{Int64}
alpha2: type = Float64
sigma: type = Float64
alpha0: type = Float64
alpha12: type = Float64
N: type = Int64
tau: type = Float64
alpha1: type = Float64
r: size = (21,), type = Vector{Int64}
x1: size = (21,), type = Vector{Int64}
x2: size = (21,), type = Vector{Int64}
Inference
For gradient-based inference, construct your model with an AD backend using the adtype keyword (see Automatic Differentiation for details). We use AdvancedHMC.jl:
# Construct with gradient support
model = seeds(data; adtype=AutoMooncake(; config=nothing))
n_samples, n_adapts = 2000, 1000
D = LogDensityProblems.dimension(model); initial_θ = rand(D)
samples_and_stats = AbstractMCMC.sample(
model,
NUTS(0.8),
n_samples;
chain_type = VNChain,
n_adapts = n_adapts,
init_params = initial_θ,
discard_initial = n_adapts,
progress = false
)
summarystats(samples_and_stats)╭─FlexiSummary (9 statistics) ─────────────────────────────────────────────────╮
│ iter collapsed │
│ chain collapsed │
│ ↓ stat = [mean, std, mcse, ess_bulk, ess_tail, rhat, q5, q50, q95] │
│ │
│ Parameters (27) ── VarName │
│ Float64 tau, alpha12, alpha2, alpha1, alpha0, b[21], b[20], b[19], b[18], │
│ b[17], b[16], b[15], b[14], b[13], b[12], b[11], b[10], b[9], │
│ b[8], b[7], b[6], b[5], b[4], b[3], b[2], b[1], sigma │
│ │
│ Extras (13) │
│ Float64 lp, n_steps, is_accept, acceptance_rate, log_density, │
│ hamiltonian_energy, hamiltonian_energy_error, │
│ max_hamiltonian_energy_error, tree_depth, numerical_error, │
│ step_size, nom_step_size, is_adapt │
│ │
│ Summary │
│ param mean std mcse ess_bulk ess_tail rhat … │
│ tau 136.4383 388.9133 67.8417 42.7743 40.8389 1.0055 … │
│ alpha12 -0.8217 0.4331 0.0170 640.2339 847.5808 1.0036 … │
│ alpha2 1.3572 0.2695 0.0107 640.8132 926.3066 1.0018 … │
│ alpha1 0.0832 0.3177 0.0135 561.3976 640.7380 1.0007 … │
│ alpha0 -0.5525 0.1958 0.0080 593.0728 828.8067 1.0016 … │
│ b[21] -0.0422 0.2842 0.0069 1808.0148 884.6912 0.9998 … │
│ b[20] 0.2188 0.2678 0.0198 192.9872 1025.6187 1.0002 … │
│ b[19] -0.0091 0.2457 0.0048 2842.2560 1417.3466 1.0044 … │
│ b[18] 0.0400 0.2378 0.0062 1590.6001 942.1665 1.0030 … │
│ b[17] -0.2121 0.3243 0.0175 323.4617 834.3455 1.0013 … │
│ b[16] -0.1405 0.3232 0.0142 696.0796 436.3219 1.0014 … │
│ b[15] 0.2305 0.2770 0.0209 175.9375 492.7498 1.0007 … │
│ b[14] -0.1334 0.2666 0.0113 697.0344 758.1380 1.0089 … │
│ b[13] -0.0638 0.2547 0.0066 1574.0950 831.5875 1.0136 … │
│ b[12] 0.1198 0.2757 0.0133 608.1638 498.9922 1.0005 … │
│ b[11] 0.0774 0.2765 0.0082 1275.8069 913.0056 1.0001 … │
│ b[10] -0.2502 0.2454 0.0219 124.7840 1151.6049 1.0038 … │
│ b[9] -0.1324 0.2347 0.0120 492.5755 977.4851 1.0017 … │
│ b[8] 0.1700 0.2327 0.0145 285.5426 1115.8088 1.0024 … │
│ b[7] 0.0536 0.2118 0.0058 1426.2754 1077.6915 1.0025 … │
│ b[6] 0.0738 0.2965 0.0079 1921.4423 883.4450 1.0003 … │
│ b[5] 0.1085 0.2430 0.0117 460.6033 702.8310 1.0061 … │
│ b[4] 0.2616 0.2691 0.0253 114.5194 756.5463 1.0073 … │
│ b[3] -0.1907 0.2306 0.0145 272.7104 936.3670 1.0009 … │
│ b[2] 0.0057 0.2186 0.0066 1101.6833 929.4083 1.0016 … │
│ b[1] -0.1848 0.2636 0.0140 384.3690 963.1904 1.0017 … │
│ sigma 0.2772 0.1559 0.0230 42.7743 40.8389 1.0055 … │
╰──────────────────────────────────────────────────────────────────────────────╯This is consistent with the result in the OpenBUGS seeds example.
Here chain_type = VNChain collects the samples into a FlexiChains.FlexiChain keyed by variable name. MCMCChains is also still supported: load it and pass chain_type = MCMCChains.Chains instead (or convert an existing chain with MCMCChains.Chains(samples_and_stats)).
Next Steps
- Automatic Differentiation - AD backends and configuration
- Evaluation Modes - Different log density computation modes
- Auto-Marginalization - Gradient-based inference with discrete variables
- Parallel Sampling - Multi-threaded and distributed sampling
More Examples
We have transcribed all the examples from the first volume of the BUGS Examples (original and transcribed). All programs and data are included, and can be compiled using the steps described in the tutorial above.
More worked Julia scripts are available in the examples directory, including SIR, Gaussian process, and Bayesian neural network examples using Mooncake-backed gradient sampling.