Contributing

This example was automatically generated from a Jupyter notebook in the RxInferExamples.jl repository.

We welcome and encourage contributions! You can help by:

  • Improving this example
  • Creating new examples
  • Reporting issues or bugs
  • Suggesting enhancements

Visit our GitHub repository to get started. Together we can make RxInfer.jl even better! 💪


Bioassay Logistic Regression

This example opens the Universal Inference section. If every continuous latent variable is approximated by a Gaussian, every factor that has a log-density can send a message, so inference can run in almost any model, at the cost of an approximation. A common way to fit such a Gaussian is the Laplace approximation: find the mode of the local log-density and use the curvature at the mode as the precision.

In RxInfer this is the keyword fallback = LocalLaplace(). It is a local Laplace approximation: each belief is projected separately, at its own mode. RxInfer uses exact message update rules where a model has them. The keyword adds four things for the rest of the model:

  1. The rule fallback computes the missing messages, marginals and average energies from the log-densities of the nodes, as expectations over the beliefs of the other variables.
  2. A form constraint projects each belief that has no closed form onto a Gaussian with the Laplace method, in the unconstrained coordinates of its domain. The beliefs of discrete variables are normalised exactly.
  3. The expectations are computed by the backends that the loaded packages define, for example Gauss–Hermite quadrature over Gaussians or an exact sum over a categorical distribution. The backends are chosen once per call of infer.
  4. Where an iterative scheme needs a starting point, each variable is initialised from its prior.

A rule fallback, form constraint or initialisation that you set yourself takes precedence over the keyword.

We test it on the bioassay experiment from Bayesian Data Analysis (Gelman et al., 3rd ed., Section 3.7; originally Racine-Poon et al., 1986). Its exact posterior can be computed on a grid, which shows what the Laplace approximation gets right and what it misses.

using RxInfer, BayesBase, Distributions, LinearAlgebra
using SpecialFunctions, StatsFuns, StableRNGs, Plots, PrettyTables
import ExpectationApproximations as EA

The bioassay experiment

Four groups of five animals received a dose $x_i$ (in log g/ml) of a compound, and $y_i$ animals died in group $i$:

x = [-0.86, -0.30, -0.05, 0.73]
n = [5, 5, 5, 5]
y = [0, 1, 3, 5]
4-element Vector{Int64}:
 0
 1
 3
 5

The model is a logistic regression with a Gaussian prior on $\theta = (\alpha, \beta)$:

\[\begin{aligned} \theta &\sim \mathcal{N}\left(0, \mathrm{diag}(4^2, 20^2)\right),\\ y_i &\sim \mathrm{Binomial}\left(n_i, \sigma(\alpha + \beta x_i)\right), \end{aligned}\]

where $\sigma$ is the logistic function. RxInfer has no conjugate update rules for a binomial likelihood with a logistic link. We write the likelihood as a single stochastic node, BinomialLogistic, a small distribution type that only evaluates the log-likelihood, and we write no message update rules for it. The node has the interfaces out (the count), θ, and the constants x and n.

logbinomial(n, k) = loggamma(n + 1) - loggamma(k + 1) - loggamma(n - k + 1)

struct BinomialLogistic{T, X, N} <: DiscreteUnivariateDistribution
    θ::T
    x::X
    n::N
end

function BayesBase.logpdf(d::BinomialLogistic, y)
    η = d.θ[1] + d.θ[2] * d.x
    return -y * log1pexp(-η) - (d.n - y) * log1pexp(η) + logbinomial(d.n, y)
end
BayesBase.insupport(::BinomialLogistic, y) = true

@define_factor_node(node = BinomialLogistic, type = Stochastic, interfaces = [:out, :θ, :x, :n])
prior_θ = MvNormalMeanCovariance(zeros(2), diagm([4.0^2, 20.0^2]))

@model function bioassay(y, x, n, prior)
    θ ~ prior
    for i in eachindex(y)
        y[i] ~ BinomialLogistic(θ, x[i], n[i])
    end
end

Compared with a plain infer call, the call below adds only the keyword fallback. It specifies no rules, constraints, initialisation or iterations. The posterior of $\theta$ is the Gaussian prior times four messages from the likelihood nodes. These messages are log-densities with no closed form, and the Laplace projection turns their product with the prior into a Gaussian.

We also request the free energy, the log-normalisers of the beliefs with logscales = true (used in the section on the evidence), and a report of what the fallback approximated with report = true. With logscales = true, the posterior is returned as an RxInfer marginal. It keeps its log-normaliser and otherwise behaves like its distribution: its moments, density and samples are those of the Gaussian.

result = infer(
    model = bioassay(x = x, n = n, prior = prior_θ),
    data = (y = y,),
    fallback = LocalLaplace(),
    free_energy = true,
    logscales = true,
    report = true,
)

q_θ = result.posteriors[:θ]
Marginal(MvNormalMeanCovariance([0.741551180045927, 7.203588407762143], [0.8761115847116286 2.7148225100255066; 2.7148225100255066 18.580422580561684])) with logscale = -5.360157394069141

To check the result, we apply the Laplace method directly to the unnormalised log-posterior, written by hand, with the laplace function of ExpectationApproximations.jl, the package that the fallback uses. Message passing assembles the same density, so the two Gaussians should agree up to the tolerance of the Newton search.

logposterior(θ) = logpdf(prior_θ, θ) + sum(logpdf(BinomialLogistic(θ, x[i], n[i]), y[i]) for i in eachindex(y))

q_direct = EA.laplace(logposterior, zeros(2))

println("max |mean difference|       = ", maximum(abs, mean(q_θ) - mean(q_direct.distribution)))
println("max |covariance difference| = ", maximum(abs, cov(q_θ) - cov(q_direct.distribution)))
max |mean difference|       = 0.0
max |covariance difference| = 0.0

What was approximated

The report lists each approximated posterior, how it was projected, and the nodes that sent messages to it, with the number of messages from an exact rule and from the rule fallback. It also warns about the parts of the inference most likely to be inaccurate. With PrettyTables.jl loaded, it prints as tables.

result.report.approximations
  Approximations: 1 of 1 posteriors approximated, no warnings
                              Approximated posteriors
╭──────────────────────────────────────┬─────────┬───────┬──────────┬──────────────╮
│ Messages from                        │ towards │ exact │ fallback │ expectations │
├──────────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ θ: Laplace, converged in 10 iterations, log Z = -5.36                            │
├──────────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ θ ~ MvNormalMeanCovariance           │ out     │ 1     │ 0        │              │
│ y[1:4] ~ BinomialLogistic(θ, …, 5.0) │ θ       │ 0     │ 4        │ exact        │
╰──────────────────────────────────────┴─────────┴───────┴──────────┴──────────────╯

                      Joints and energies by the fallback
╭──────────────────────────────────────┬────────────────┬───────┬─────────────╮
│ Node                                 │ computed       │ times │ how         │
├──────────────────────────────────────┼────────────────┼───────┼─────────────┤
│ y[1:4] ~ BinomialLogistic(θ, …, 5.0) │ average energy │ 4     │ expectation │
╰──────────────────────────────────────┴────────────────┴───────┴─────────────╯

    Expectations: ExactSum, GaussHermite, UnconstrainedLegendre, QuantileLegendre

The posterior of $\theta$ is the message from the prior, computed by its exact rule, times the four likelihood messages computed by the rule fallback. The expectations in these messages are exact, because the other inputs of the likelihood are data and constants. Laplace's method converged, and the normaliser it found is the evidence used in the section below. The report raises no diagnostics. Its other section, result.report.timings, shows how the time was spent.

Exact posterior on a grid

With two parameters, the exact posterior can be evaluated on a fine grid. We use it as the ground truth.

αs = range(-4, 6; length = 400)
βs = range(-10, 40; length = 400)
logp_grid = [logposterior([α, β]) for α in αs, β in βs]
p_grid = exp.(logp_grid .- maximum(logp_grid))
p_grid ./= sum(p_grid)

A = [α for α in αs, β in βs]
B = [β for α in αs, β in βs]
grid_mean = [sum(p_grid .* A), sum(p_grid .* B)]
grid_cov = [sum(p_grid .* (A .- grid_mean[1]) .* (A .- grid_mean[1])) sum(p_grid .* (A .- grid_mean[1]) .* (B .- grid_mean[2]));
            sum(p_grid .* (A .- grid_mean[1]) .* (B .- grid_mean[2])) sum(p_grid .* (B .- grid_mean[2]) .* (B .- grid_mean[2]))]

summary_row(name, m, C) = println(rpad(name, 10),
    "E[α] = ", lpad(round(m[1]; digits = 2), 6), "   sd(α) = ", lpad(round(sqrt(C[1, 1]); digits = 2), 5),
    "   E[β] = ", lpad(round(m[2]; digits = 2), 6), "   sd(β) = ", lpad(round(sqrt(C[2, 2]); digits = 2), 5),
    "   corr = ", round(C[1, 2] / sqrt(C[1, 1] * C[2, 2]); digits = 2))

summary_row("grid", grid_mean, grid_cov)
summary_row("Laplace", mean(q_θ), cov(q_θ))
grid      E[α] =    1.1   sd(α) =  0.98   E[β] =  10.35   sd(β) =  4.87   corr = 0.61
Laplace   E[α] =   0.74   sd(α) =  0.94   E[β] =    7.2   sd(β) =  4.31   corr = 0.67

The Laplace approximation is centred at the mode. The exact posterior of $\beta$ is skewed to the right, so its mean lies above the mode, and its spread is larger than the curvature at the mode suggests. The contour plot shows the same: the Laplace ellipse (dashed) matches the core of the posterior but not the long tail towards large $\beta$. Both densities are drawn relative to their maximum, at the same levels.

p_laplace = [pdf(q_θ, [α, β]) for α in αs, β in βs]

# Both densities relative to their maximum, drawn at the same levels
levels = [0.05, 0.2, 0.4, 0.6, 0.8]
plt = contour(αs, βs, (p_grid ./ maximum(p_grid))'; levels = levels, seriescolor = :blue, colorbar = false, linewidth = 2,
    xlabel = "α", ylabel = "β", title = "Bioassay posterior", xlims = (-2, 5), ylims = (-5, 30))
contour!(plt, αs, βs, (p_laplace ./ maximum(p_laplace))'; levels = levels, seriescolor = :red, linestyle = :dash, colorbar = false, linewidth = 2)
plot!(plt, [NaN], [NaN]; color = :blue, linewidth = 2, label = "exact (grid)")
plot!(plt, [NaN], [NaN]; color = :red, linestyle = :dash, linewidth = 2, label = "Laplace")
plt

The evidence and the free energy

The grid also gives the exact log-evidence $\log p(y)$, the logarithm of the normaliser of the posterior. Message passing gives two approximations of it:

  • The log-normaliser of the posterior, which infer kept because of logscales = true. Every message from a likelihood node is exact here, so this is the Laplace approximation of the evidence, $\log p(y) \approx \ell(\hat{\theta}) + \frac{d}{2}\log 2\pi - \frac{1}{2}\log\det\left(-\nabla^2 \ell(\hat{\theta})\right)$.
  • The free energy $F[q] = -\log p(y) + \mathrm{KL}\left(q(\theta) \,\|\, p(\theta \mid y)\right)$. It is an upper bound on $-\log p(y)$ and exceeds it by the divergence of the Gaussian from the exact posterior.
logevidence_laplace = getlogscale(q_θ)
free_energy = only(result.free_energy)

cell_area = step(αs) * step(βs)
logevidence_grid = maximum(logp_grid) + log(sum(exp.(logp_grid .- maximum(logp_grid))) * cell_area)

println("-log p(y):  grid = ", round(-logevidence_grid; digits = 3), ",  Laplace = ", round(-logevidence_laplace; digits = 3), ",  free energy = ", round(free_energy; digits = 3))
println("KL(q || exact posterior) = ", round(free_energy + logevidence_grid; digits = 3))
-log p(y):  grid = 5.3,  Laplace = 5.36,  free energy = 6.407
KL(q || exact posterior) = 1.107

The Laplace evidence is close to the exact one. The free energy is about one nat above it. That gap is the divergence of the Gaussian from the exact posterior, which is not zero because the Gaussian misses the skew of the posterior.

Natural-gradient propagation

The Laplace Gaussian is centred at the mode of the posterior and uses the curvature there. Variational inference chooses a different Gaussian: the one that minimises $\mathrm{KL}(q \,\|\, p(\theta \mid y))$, or equivalently maximises the evidence lower bound. fallback = NaturalGradientPropagation() uses the same exact rules as before and finds this Gaussian by natural-gradient message passing (Lukashchuk et al., Information Geometry of Message Passing, arXiv:2608.15922):

  • Each likelihood message, a log-density $\ell_i(\theta)$, gets a site on its edge to $\theta$. A site is a Gaussian, from the same family as the prior of $\theta$. The posterior $q$ is the prior times the four sites.
  • At each iteration, each site moves towards its target. In natural parameters the target is $\eta^\star_i = G(q)^{-1}\,\mathrm{Cov}_q[T(\theta), \ell_i(\theta)]$, the natural gradient of $\mathbb{E}_q[\ell_i]$, where $T$ is the sufficient statistic of the Gaussian and $G$ its Fisher information. For a Gaussian, Stein's lemma reduces this to expectations of the values of $\ell_i$ over $q$, which are computed by Gauss–Hermite quadrature without derivatives.
  • The move is a damped heavy-ball step, $v \leftarrow \beta v + \alpha(\eta^\star_i - \eta_i)$ and $\eta_i \leftarrow \eta_i + v$, with the step size alpha = 0.5 and the momentum beta = 0.2 by default. The step is halved if it would make the posterior improper.

At the fixed point each site equals its target, and the posterior is a stationary point of the free energy over Gaussians. With one latent variable, this is the Gaussian closest to the posterior. It is also the fixed point of conjugate-computation variational inference (CVI), which this scheme replaces in RxInfer. A site moves one step per iteration, so the call sets iterations. The free energy is the Bethe free energy, with the average energies of the likelihood nodes under $q$. With one latent variable it equals the negative evidence lower bound, so the fixed point has the lowest free energy that a Gaussian can reach.

result_ngmp = infer(
    model = bioassay(x = x, n = n, prior = prior_θ),
    data = (y = y,),
    fallback = NaturalGradientPropagation(),
    iterations = 50,
    free_energy = true,
    report = true,
)
q_ngmp = last(result_ngmp.posteriors[:θ])
free_energy_ngmp = last(result_ngmp.free_energy)

summary_row("grid", grid_mean, grid_cov)
summary_row("Laplace", mean(q_θ), cov(q_θ))
summary_row("NGMP", mean(q_ngmp), cov(q_ngmp))
println("-log p(y) = ", round(-logevidence_grid; digits = 3), ";  free energy: Laplace = ", round(free_energy; digits = 3), ", NGMP = ", round(free_energy_ngmp; digits = 3))
grid      E[α] =    1.1   sd(α) =  0.98   E[β] =  10.35   sd(β) =  4.87   corr = 0.61
Laplace   E[α] =   0.74   sd(α) =  0.94   E[β] =    7.2   sd(β) =  4.31   corr = 0.67
NGMP      E[α] =   1.12   sd(α) =   0.9   E[β] =  10.29   sd(β) =  3.66   corr = 0.54
-log p(y) = 5.3;  free energy: Laplace = 6.407, NGMP = 5.436

The free energy decreases as the sites move and settles within about thirty iterations:

plot(result_ngmp.free_energy; marker = :circle, color = :red, label = "NaturalGradientPropagation()", xlabel = "iteration", ylabel = "free energy", size = (800, 350))
hline!([free_energy]; color = :blue, linestyle = :dash, label = "LocalLaplace()")
hline!([-logevidence_grid]; color = :black, linestyle = :dot, label = "-log p(y), grid")

As with the Laplace approximation, ExpectationApproximations.jl can check the result: gaussian_variational maximises the evidence lower bound of the hand-written log-posterior directly, with Newton's method over the mean of the Gaussian and the Cholesky factor of its covariance. Message passing should reach the same Gaussian, up to the quadrature error of the two methods, and its free energy should be the negative of that bound.

q_best = EA.gaussian_variational(logposterior, zeros(2))

println("max |mean difference|       = ", maximum(abs, mean(q_ngmp) - mean(q_best.distribution)))
println("max |covariance difference| = ", maximum(abs, cov(q_ngmp) - cov(q_best.distribution)))
println("free energy = ", round(free_energy_ngmp; digits = 6), ",  -ELBO of the best Gaussian = ", round(-q_best.logZ; digits = 6))
max |mean difference|       = 7.10674033097547e-5
max |covariance difference| = 0.00030326819224235635
free energy = 5.436214,  -ELBO of the best Gaussian = 5.436214

The report lists the sites and their steps, four sites over fifty iterations, and shows that every site has settled at its target:

result_ngmp.report.approximations
  Approximations: 1 of 1 posteriors approximated, no warnings
                              Approximated posteriors
╭──────────────────────────────────────┬─────────┬───────┬──────────┬──────────────╮
│ Messages from                        │ towards │ exact │ fallback │ expectations │
├──────────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ θ: natural-gradient propagation, 4 sites, 200 steps                              │
├──────────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ θ ~ MvNormalMeanCovariance           │ out     │ 1     │ 0        │              │
│ y[1:4] ~ BinomialLogistic(θ, …, 5.0) │ θ       │ 0     │ 200      │ exact        │
╰──────────────────────────────────────┴─────────┴───────┴──────────┴──────────────╯

                      Joints and energies by the fallback
╭──────────────────────────────────────┬────────────────┬───────┬─────────────╮
│ Node                                 │ computed       │ times │ how         │
├──────────────────────────────────────┼────────────────┼───────┼─────────────┤
│ y[1:4] ~ BinomialLogistic(θ, …, 5.0) │ average energy │ 200   │ expectation │
╰──────────────────────────────────────┴────────────────┴───────┴─────────────╯

    Expectations: ExactSum, GaussHermite, UnconstrainedLegendre, QuantileLegendre

The variational Gaussian moves towards the heavier tail of the posterior of $\beta$. Its mean is close to the exact one, while the Laplace mean is about a third too low, and its free energy is within about 0.14 nat of $-\log p(y)$, compared with one nat for Laplace. Its spread is smaller than the exact one. This is a known property of $\mathrm{KL}(q \,\|\, p)$, which penalises mass where the posterior has little. The approximation is still a symmetric Gaussian, so it cannot represent the skew.

A derived quantity: the LD50

The quantity of interest in the original study is the LD50, the dose at which the probability of death is 50%, $\mathrm{LD50} = -\alpha / \beta$. It is a nonlinear function of $\theta$, so we compare its distribution under the exact posterior (sampled from the grid) and under the Laplace approximation, keeping only samples with $\beta > 0$ as in the book.

rng = StableRNG(42)
nsamples = 10_000
idx = rand(rng, Categorical(vec(p_grid)), nsamples)
ld50_grid = [-A[i] / B[i] for i in idx if B[i] > 0]
ld50_laplace = [-θ[1] / θ[2] for θ in eachcol(rand(rng, q_θ, nsamples)) if θ[2] > 0]

histogram(ld50_grid; bins = range(-0.6, 0.6; length = 61), normalize = :pdf, alpha = 0.5, label = "exact (grid)", xlabel = "LD50", title = "Posterior of the LD50")
histogram!(ld50_laplace; bins = range(-0.6, 0.6; length = 61), normalize = :pdf, alpha = 0.5, label = "Laplace")

p_positive_laplace = 1 - cdf(Normal(mean(q_θ)[2], sqrt(cov(q_θ)[2, 2])), 0)
interval_grid, interval_laplace = quantile(ld50_grid, [0.05, 0.95]), quantile(ld50_laplace, [0.05, 0.95])
println("P(β > 0):  grid = ", round(sum(p_grid[B .> 0]); digits = 4), ",  Laplace = ", round(p_positive_laplace; digits = 4))
println("LD50 median:  grid = ", round(median(ld50_grid); digits = 3), ",  Laplace = ", round(median(ld50_laplace); digits = 3))
println("LD50 90% interval:  grid = ", round.(interval_grid; digits = 3), ",  Laplace = ", round.(interval_laplace; digits = 3))
P(β > 0):  grid = 1.0,  Laplace = 0.9527
LD50 median:  grid = -0.105,  Laplace = -0.105
LD50 90% interval:  grid = [-0.246, 0.065],  Laplace = [-0.292, 0.203]

The medians agree, but the Laplace interval for the LD50 is wider than the exact one. The Gaussian is symmetric around the mode of $\beta$, so it puts a few percent of its mass near and below $\beta = 0$, a region that the data rule out, and dividing by small values of $\beta$ spreads the LD50 out.

Another model: Poisson regression

The fallback does not depend on the model being a logistic regression. As a second model, we fit a Poisson regression with a log link, $y_i \sim \mathrm{Poisson}(\exp(a + b t_i))$, on simulated counts. The only new code is the likelihood node.

struct PoissonLogLinear{T, X} <: DiscreteUnivariateDistribution
    θ::T
    t::X
end

BayesBase.logpdf(d::PoissonLogLinear, y) = (η = d.θ[1] + d.θ[2] * d.t; y * η - exp(η) - loggamma(y + 1))
BayesBase.insupport(::PoissonLogLinear, y) = true

@define_factor_node(node = PoissonLogLinear, type = Stochastic, interfaces = [:out, :θ, :t])

@model function poisson_regression(y, t, prior)
    θ ~ prior
    for i in eachindex(y)
        y[i] ~ PoissonLogLinear(θ, t[i])
    end
end

θ_true = [0.5, 1.2]
t = collect(range(-1, 1.5; length = 30))
counts = [rand(rng, Poisson(exp(θ_true[1] + θ_true[2] * ti))) for ti in t]

result_poisson = infer(
    model = poisson_regression(t = t, prior = MvNormalMeanCovariance(zeros(2), diagm([10.0, 10.0]))),
    data = (y = counts,),
    fallback = LocalLaplace(),
)

q_poisson = result_poisson.posteriors[:θ]
println("true θ = ", θ_true, ",  posterior mean = ", round.(mean(q_poisson); digits = 3), ",  posterior sd = ", round.(sqrt.(diag(cov(q_poisson))); digits = 3))
true θ = [0.5, 1.2],  posterior mean = [0.307, 1.411],  posterior sd = [0.192, 0.18]
ts = range(-1, 1.5; length = 100)
draws = rand(rng, q_poisson, 200)
rates = [exp(θ[1] + θ[2] * τ) for τ in ts, θ in eachcol(draws)]
lower, upper = [quantile(r, 0.05) for r in eachrow(rates)], [quantile(r, 0.95) for r in eachrow(rates)]
middle = [exp(mean(q_poisson)[1] + mean(q_poisson)[2] * τ) for τ in ts]

plot(ts, middle; ribbon = (middle .- lower, upper .- middle), fillalpha = 0.3, label = "posterior rate (90%)", xlabel = "t", ylabel = "count")
plot!(ts, exp.(θ_true[1] .+ θ_true[2] .* ts); color = :black, linestyle = :dash, label = "true rate")
scatter!(t, counts; label = "observed counts", color = :gray)

The model with deterministic nodes

The BinomialLogistic node combines the logistic function and the binomial. The model can also be written as it is on paper, with the probability of death a deterministic function of $\theta$, $p = \sigma(\alpha + \beta x)$. RxInfer has no binomial node, so each group of five animals becomes five Bernoulli trials. This gives the same posterior, because the binomial coefficient does not depend on $\theta$.

Two deterministic nodes are now between $\theta$ and the data: RxInfer's dot node for the linear predictor, and a Delta node for logistic, a function that no package declares as a node. Both use the same rule fallback, which propagates the message from the observation back through their functions. dot still uses its exact rules where its messages are Gaussian, as in the direction from $\theta$ towards the data. The posterior should equal the one from BinomialLogistic.

doses = reduce(vcat, [fill(x[i], n[i]) for i in eachindex(x)])
deaths = reduce(vcat, [[ones(y[i]); zeros(n[i] - y[i])] for i in eachindex(x)])

@model function bioassay_trials(y, doses, prior)
    θ ~ prior
    for j in eachindex(y)
        p[j] := logistic(dot([1.0, doses[j]], θ))
        y[j] ~ Bernoulli(p[j])
    end
end

result_trials = infer(
    model = bioassay_trials(doses = doses, prior = prior_θ),
    data = (y = deaths,),
    fallback = LocalLaplace(),
    free_energy = true,
    report = true,
)

q_trials = result_trials.posteriors[:θ]
println("max |mean difference to the fused node|       = ", maximum(abs, mean(q_trials) - mean(q_θ)))
println("max |covariance difference to the fused node| = ", maximum(abs, cov(q_trials) - cov(q_θ)))
max |mean difference to the fused node|       = 4.063782199636989e-9
max |covariance difference to the fused node| = 2.536334875458124e-8

The report of this model shows how the two deterministic nodes were handled:

  • Towards its output, dot uses its exact rule, because its input there is the Gaussian message from $\theta$.
  • Towards $\theta$, the rule fallback runs. The message there comes from logistic and is a log-density.

The note in the report says why that message was not projected: the likelihood of a single Bernoulli observation has no mode.

The header of $\theta$ gives a log-normaliser, log Z, of about 4.59, which is not the log-evidence of these trials. Each message towards $\theta$ is the message of a Bernoulli node towards $p$, the density $\mathrm{Beta}(2, 1)$ or $\mathrm{Beta}(1, 2)$, pulled back through logistic, and keeps the normalising constant of that Beta, a factor of 2. Laplace's normaliser includes these 20 factors: it is the Laplace evidence of the trials, about $-9.27$ (the $-5.36$ of the first model without the binomial coefficients, $\log 50$), plus $20 \log 2 \approx 13.86$.

result_trials.report.approximations
  Approximations: 22 of 22 posteriors approximated, no warnings, 1 note
                                                 Diagnostics
╭──────┬───────────────┬─────────────────────────────────────────────────────────────────────────────────────╮
│      │ where         │ what                                                                                │
├──────┼───────────────┼─────────────────────────────────────────────────────────────────────────────────────┤
│ note │ · (anonymous) │ 20 messages had no mode and stayed log-densities, pulled back through the next node │
╰──────┴───────────────┴─────────────────────────────────────────────────────────────────────────────────────╯

                                     Approximated posteriors
╭──────────────────────────────┬─────────┬───────┬──────────┬───────────────────────────────────╮
│ Messages from                │ towards │ exact │ fallback │ expectations                      │
├──────────────────────────────┴─────────┴───────┴──────────┴───────────────────────────────────┤
│ · (anonymous): Laplace, converged in 3 iterations, log Z = 0.6723                             │
├──────────────────────────────┬─────────┬───────┬──────────┬───────────────────────────────────┤
│ · := dot(…, θ)               │ out     │ 20    │ 0        │                                   │
│ p[1:20] := logistic(·)       │ in[1]   │ 0     │ 20       │                                   │
├──────────────────────────────┴─────────┴───────┴──────────┴───────────────────────────────────┤
│ p[1:20]: Laplace, 20 of 20 converged, 4 to 9 iterations                                       │
├──────────────────────────────┬─────────┬───────┬──────────┬───────────────────────────────────┤
│ y[1:20] ~ Bernoulli(p[1:20]) │ p       │ 20    │ 0        │                                   │
│ p[1:20] := logistic(·)       │ out     │ 0     │ 20       │ NormalMeanVariance → GaussHermite │
├──────────────────────────────┴─────────┴───────┴──────────┴───────────────────────────────────┤
│ θ: Laplace, converged in 9 iterations, log Z = 4.591                                          │
├──────────────────────────────┬─────────┬───────┬──────────┬───────────────────────────────────┤
│ θ ~ MvNormalMeanCovariance   │ out     │ 2     │ 0        │                                   │
│ · := dot(…, θ)               │ in2     │ 0     │ 20       │ exact                             │
╰──────────────────────────────┴─────────┴───────┴──────────┴───────────────────────────────────╯

                        Joints and energies by the fallback
╭────────────────────────┬─────────────────────┬───────┬──────────────────────────╮
│ Node                   │ computed            │ times │ how                      │
├────────────────────────┼─────────────────────┼───────┼──────────────────────────┤
│ p[1:20] := logistic(·) │ joint of (in)       │ 20    │ joint Laplace, converged │
│ · := dot(…, θ)         │ joint of (in1, in2) │ 20    │ joint Laplace, converged │
╰────────────────────────┴─────────────────────┴───────┴──────────────────────────╯

    Expectations: ExactSum, GaussHermite, UnconstrainedLegendre, QuantileLegendre

This version of the model also has a free energy. The belief of each $p_j$ is a product of the Gaussian that the Delta node sends and the Beta that the Bernoulli node sends, and its domain is the narrower of the two, the interval $(0, 1)$, so its Laplace approximation is a logit-normal and the average energy of the Bernoulli node, which needs $\mathbb{E}[\log p]$, is defined. The trials leave out the binomial coefficients of the first model, $\log 50$ in total, so the two free energies are comparable once those are added:

free_energy_trials = last(result_trials.free_energy)
println("free energy: trials = ", round(free_energy_trials; digits = 3), ",  first model + log 50 = ", round(free_energy + log(50); digits = 3))
free energy: trials = 11.384,  first model + log 50 = 10.319

The free energy of the trials is about one nat higher. It is a Bethe free energy over $\theta$ and over the 20 probabilities and linear predictors, whose beliefs LocalLaplace() projects one at a time, so they need not agree with the belief of $\theta$. In the first model, $\theta$ is the only latent variable, and the free energy is that of its Gaussian alone.

Summary

With one keyword, RxInfer ran a Laplace approximation in two non-conjugate models without hand-written message update rules, constraints or initialisation, and report = true showed what was approximated. The result agrees with a Laplace approximation of the hand-written posterior to numerical precision, and the log-normaliser of the posterior is the Laplace approximation of the evidence. With fallback = NaturalGradientPropagation(), the result is the variational Gaussian that gaussian_variational finds by hand, which has a lower free energy.

The Laplace approximation is centred at the mode and uses the local curvature, so it misses the skew of the posterior in $\beta$. It underestimates the posterior mean of $\beta$ by about a third, and its free energy is about one nat above the exact $-\log p(y)$. Because a Gaussian is symmetric, it also puts a few percent of its mass on $\beta < 0$, which the data rule out, and this widens the interval of the LD50. The variational Gaussian from NaturalGradientPropagation() moves the mean of $\beta$ close to the exact one. Expectation propagation, fallback = ExpectationPropagation(), matches the moments of each likelihood message against the rest of the posterior; the Poisson Count Series and Stochastic Volatility examples use it.

Two limitations remain:

  • In the model written with deterministic nodes, the free energy is a Bethe free energy over beliefs projected one at a time, about one nat above that of the first model. RxInfer also has no Binomial node, so the trials are observed one by one.
  • \[\theta\]

    is a single two-dimensional variable. With separate scalar variables $\alpha$ and $\beta$, the graph would have loops, and the messages between them would not carry their strong posterior correlation.

Contributing

This example was automatically generated from a Jupyter notebook in the RxInferExamples.jl repository.

We welcome and encourage contributions! You can help by:

  • Improving this example
  • Creating new examples
  • Reporting issues or bugs
  • Suggesting enhancements

Visit our GitHub repository to get started. Together we can make RxInfer.jl even better! 💪


Environment

This example was executed in a clean, isolated environment. Below are the exact package versions used:

For reproducibility:

  • Use the same package versions when running locally
  • Report any issues with package compatibility
Status `/tmp/jl_kQqZki/Project.toml`
  [b4ee3484] BayesBase v1.7.0
⌃ [31c24e10] Distributions v0.25.134
  [9cdca625] ExpectationApproximations v1.0.0
  [91a5bcdd] Plots v1.41.10
  [08abe8d2] PrettyTables v3.5.1
  [86711068] RxInfer v6.2.0
  [276daf66] SpecialFunctions v2.9.2
  [860ef19b] StableRNGs v1.1.0
⌅ [4c63d2b9] StatsFuns v1.5.3
  [37e2e46d] LinearAlgebra v1.13.0
Info Packages marked with ⌃ and ⌅ have new versions available. Those with ⌃ may be upgradable, but those with ⌅ are restricted by compatibility constraints from upgrading. To see why use `status --outdated`