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! 💪
Tracking with a Squared-Distance Sensor
This example is part of the Universal Inference section, which runs inference in a broad class of models by approximating what has no closed form. An object moves along a line, and a sensor reports its squared distance to a reference point. The squared distance is a plain Julia function with no message update rules, and the precisions of the motion and of the sensor are unknown. We run inference with fallback = NaturalGradientPropagation(), natural-gradient message passing (Lukashchuk et al., 2026), and compare its posteriors with the exact ones, computed on a grid.
Natural-gradient propagation keeps one site per edge of every random variable, in the family of the belief of that variable: a Gaussian for a location, a Gamma for a precision. A message that has a closed form in that family is its own site. For any other message, such as a log-density pulled back through a function, the site moves at each iteration by a damped step towards its target, the natural gradient of the expected log-density of the message under the marginal of the variable. At the fixed point, each site equals its target, and each marginal is a stationary point of the variational free energy over its family. Where the sites are Gaussian, this is the fixed point of conjugate-computation variational inference (Khan and Lin, 2017).
using RxInfer, BayesBase, Distributions, LinearAlgebra, StableRNGs
using Plots, PrettyTables, Printf
The experiment
A group of researchers tracks an object moving along a one-dimensional trajectory at about one centimetre per second. They cannot observe its position $z_t$. Instead, a sensor reports the squared distance $y_t$ between the object and a reference point $s$, and both the servo that moves the object and the sensor are noisy. The researchers model the motion as a random walk with a drift of one, and give the precisions of the motion and of the sensor, $\tau$ and $\gamma$, vague priors:
\[\begin{aligned} \tau &\sim \Gamma(0.01, 0.01), \qquad \gamma \sim \Gamma(0.01, 0.01),\\ z_1 &\sim \mathcal{N}(0, \tau^{-1}), \qquad z_t \sim \mathcal{N}(z_{t - 1} + 1, \tau^{-1}),\\ y_t &\sim \mathcal{N}\big((z_t - s)^2, \gamma^{-1}\big), \end{aligned}\]
where $\Gamma(a, b)$ is the Gamma distribution with shape $a$ and rate $b$. We simulate 50 seconds from this model, with $\tau = 1$ and a sensor noise with standard deviation 100 cm². The reference point, at 80 cm, lies beyond the end of the path, so only one root of each squared distance lies on the side of the object.
nr_observations = 50
reference_point = 80
τ_true, γ_true = 1.0, 1 / 100^2
rng = StableRNG(42)
hidden_location = zeros(nr_observations)
hidden_location[1] = randn(rng) / sqrt(τ_true)
for t in 2:nr_observations
hidden_location[t] = hidden_location[t - 1] + 1 + randn(rng) / sqrt(τ_true)
end
measurements = (hidden_location .- reference_point) .^ 2 .+ randn(rng, nr_observations) ./ sqrt(γ_true);
p1 = plot(1:nr_observations, hidden_location; linewidth = 3, legend = :topleft, label = "hidden location")
hline!(p1, [reference_point]; linewidth = 3, label = "reference point")
xlabel!(p1, "time [sec]"); ylabel!(p1, "location [cm]")
p2 = scatter(1:nr_observations, measurements; label = "measurements")
plot!(p2, 1:nr_observations, (hidden_location .- reference_point) .^ 2; color = :black, label = "true squared distance")
xlabel!(p2, "time [sec]"); ylabel!(p2, "squared distance [cm²]")
plot(p1, p2; size = (1200, 500))
![]()
The model
The squared distance is a plain function, and μ[t] := compute_squared_distance(z[t]) makes it a deterministic node. No rule is written for it, and no approximation method is chosen for it.
compute_squared_distance(z) = (z - reference_point)^2
@model function measurement_model(y)
τ ~ Gamma(shape = 0.01, rate = 0.01)
γ ~ Gamma(shape = 0.01, rate = 0.01)
z[1] ~ Normal(mean = 0, precision = τ)
μ[1] := compute_squared_distance(z[1])
y[1] ~ Normal(mean = μ[1], precision = γ)
for t in 2:length(y)
z[t] ~ Normal(mean = z[t - 1] + 1, precision = τ)
μ[t] := compute_squared_distance(z[t])
y[t] ~ Normal(mean = μ[t], precision = γ)
end
end
Inference under mean field
We factorise the posterior as $q(z, \mu)\,q(\tau)\,q(\gamma)$: the path and the squared distances keep their joint distribution, and each precision has its own marginal. Under this factorisation the precisions are conjugate. The Normal nodes send them messages in the Gamma family with their own rules, which take the expectations under $q(z, \mu)$. Each posterior is then a Gamma distribution, the prior times those messages, as in variational message passing. The fallback handles the path:
- Towards $\mu_t$, the deterministic node sends the message of $z_t$ pushed forward through the squared distance, and towards $z_t$ it sends the message on $\mu_t$ pulled back through it. Neither message is Gaussian, so each has a Gaussian site, which takes a natural-gradient step at each iteration.
- The transitions and the
Normalobservation nodes keep their exact rules, which use the Gaussian sites directly.
A site takes one step per iteration, with the default step size alpha = 0.5 and momentum beta = 0.2, so we run 300 iterations. Mean field needs initial values for $q(\tau)$ and $q(\gamma)$. For the sensor, we start near a plausible noise level, a standard deviation of about 100 cm², $\mathbb{E}[\gamma] = 10^{-4}$. The section on the starting point shows why.
mean_field = @constraints begin
q(z, μ, τ, γ) = q(z, μ)q(τ)q(γ)
end
initialization = @initialization begin
q(τ) = GammaShapeRate(1.0, 1.0)
q(γ) = GammaShapeRate(1.0, 1.0e4)
end
results = infer(
model = measurement_model(),
data = (y = measurements,),
constraints = mean_field,
initialization = initialization,
iterations = 300,
fallback = NaturalGradientPropagation(),
free_energy = true,
report = true,
returnvars = (z = KeepLast(), τ = KeepLast(), γ = KeepLast()),
)
Inference results:
Posteriors | available for (γ, τ, z)
Free Energy: | [328.515, 328.082, 329.516, 330.556, 330.925, 330.872, 330.678, 330.5, 330.389, 330.337 … 330.226, 330.226, 330.226, 330.226, 330.226, 330.226, 330.226, 330.226, 330.226, 330.226]What was approximated
The report lists the approximated posteriors: each $z_t$ and each $\mu_t$, with their natural-gradient sites, the messages that formed them, and whether every site had settled at the last iteration. The precisions are not listed, because their posteriors are exact products of Gamma messages.
results.report.approximations
Approximations: 100 of 103 posteriors approximated (exact rules on approximated inputs: · (anonymous), γ, τ), no warnings
Approximated posteriors
╭──────────────────────────────────────────────┬─────────┬───────┬──────────┬────────────────────────────────────────────────────────────────────────────────╮
│ Messages from │ towards │ exact │ fallback │ expectations │
├──────────────────────────────────────────────┴─────────┴───────┴──────────┴────────────────────────────────────────────────────────────────────────────────┤
│ z[1]: natural-gradient propagation, 1 site, 300 steps │
├──────────────────────────────────────────────┬─────────┬───────┬──────────┬────────────────────────────────────────────────────────────────────────────────┤
│ z[1] ~ NormalMeanPrecision(0.0, τ) │ out │ 301 │ 0 │ │
│ · := +(z[1], 1.0) │ in[1] │ 300 │ 0 │ │
│ μ[1] := compute_squared_distance(z[1]) │ in[1] │ 0 │ 300 │ │
├──────────────────────────────────────────────┴─────────┴───────┴──────────┴────────────────────────────────────────────────────────────────────────────────┤
│ z[2:49]: natural-gradient propagation, 48 sites, 14400 steps │
├──────────────────────────────────────────────┬─────────┬───────┬──────────┬────────────────────────────────────────────────────────────────────────────────┤
│ z[2:49] ~ NormalMeanPrecision(·, τ) │ out │ 14400 │ 0 │ │
│ · := +(z[2:49], 1.0) │ in[1] │ 14400 │ 0 │ │
│ μ[2:49] := compute_squared_distance(z[2:49]) │ in[1] │ 0 │ 14400 │ │
├──────────────────────────────────────────────┴─────────┴───────┴──────────┴────────────────────────────────────────────────────────────────────────────────┤
│ z[50]: natural-gradient propagation, 1 site, 300 steps │
├──────────────────────────────────────────────┬─────────┬───────┬──────────┬────────────────────────────────────────────────────────────────────────────────┤
│ z[50] ~ NormalMeanPrecision(·, τ) │ out │ 300 │ 0 │ │
│ μ[50] := compute_squared_distance(z[50]) │ in[1] │ 0 │ 300 │ │
├──────────────────────────────────────────────┴─────────┴───────┴──────────┴────────────────────────────────────────────────────────────────────────────────┤
│ μ[1:50]: natural-gradient propagation, 50 sites, 14999 steps │
├──────────────────────────────────────────────┬─────────┬───────┬──────────┬────────────────────────────────────────────────────────────────────────────────┤
│ y[1:50] ~ NormalMeanPrecision(μ[1:50], γ) │ μ │ 15000 │ 0 │ │
│ μ[1:50] := compute_squared_distance(z[1:50]) │ out │ 0 │ 15000 │ NormalMeanPrecision → GaussHermite, NormalWeightedMeanPrecision → GaussHermite │
╰──────────────────────────────────────────────┴─────────┴───────┴──────────┴────────────────────────────────────────────────────────────────────────────────╯
Joints and energies by the fallback
╭──────────────────────────────────────────────┬───────────────┬───────┬──────────────────────────╮
│ Node │ computed │ times │ how │
├──────────────────────────────────────────────┼───────────────┼───────┼──────────────────────────┤
│ μ[1:50] := compute_squared_distance(z[1:50]) │ joint of (in) │ 15000 │ joint Laplace, converged │
╰──────────────────────────────────────────────┴───────────────┴───────┴──────────────────────────╯
Expectations: ExactSum, GaussHermite, UnconstrainedLegendre, QuantileLegendreThe exact posterior
The posterior has 52 dimensions, but given the two precisions the path is a one-dimensional hidden Markov model. We compute it on a grid:
- For the path: for each $y_t$ and a precision $\gamma$, the likelihood is negligible except where $(z_t - s)^2$ is within nine standard deviations of $y_t$, which gives two short intervals on either side of $s$. With a grid of 100 points on each interval, the transition is a matrix. The forward pass gives $\log p(y \mid \tau, \gamma)$, and the backward pass gives the smoothing distributions of $z_t$.
- For the precisions: on a grid of $(\log\tau, \log\gamma)$, first a coarse grid to locate the posterior and then a fine grid of 41 × 41 points around it, the prior times $p(y \mid \tau, \gamma)$ gives the joint posterior of the precisions and the evidence $p(y)$. The posterior of $z_t$ is the mixture of the smoothing distributions over the grid.
# The points where the likelihood of yₜ is not negligible under a precision γ: (z - s)² within
# nine standard deviations of yₜ, on both sides of the reference point
function location_grid(yt, γ; points = 100, k = 9)
lo, hi = yt - k / sqrt(γ), max(yt + k / sqrt(γ), k / sqrt(γ))
if lo <= 0
r = sqrt(hi); h = 2r / points
return collect(range(reference_point - r + h / 2, reference_point + r - h / 2, length = points)), h
end
a, b = sqrt(lo), sqrt(hi); h = (b - a) / points
right = collect(range(a + h / 2, b - h / 2, length = points))
return vcat(reference_point .- reverse(right), reference_point .+ right), h
end
# The forward pass, log p(y | τ, γ), and with `smooth = true` the backward pass too: the smoothing
# means and variances of z
function hidden_markov(y, τ, γ; smooth = false)
T = length(y)
grids = [location_grid(y[t], γ) for t in 1:T]
likelihood(t) = [pdf(Normal(compute_squared_distance(z), 1 / sqrt(γ)), y[t]) for z in grids[t][1]]
transition(t) = [pdf(Normal(u + 1, 1 / sqrt(τ)), v) for u in grids[t - 1][1], v in grids[t][1]]
α, c, K = Vector{Vector{Float64}}(undef, T), zeros(T), Vector{Matrix{Float64}}(undef, T)
a = pdf.(Normal(0, 1 / sqrt(τ)), grids[1][1]) .* likelihood(1)
c[1] = sum(a) * grids[1][2]; α[1] = a ./ c[1]
for t in 2:T
K[t] = transition(t)
a = (K[t]' * α[t - 1]) .* grids[t - 1][2] .* likelihood(t)
c[t] = sum(a) * grids[t][2]; α[t] = a ./ c[t]
end
smooth || return sum(log, c)
β = Vector{Vector{Float64}}(undef, T); β[T] = ones(length(α[T]))
for t in (T - 1):-1:1
β[t] = K[t + 1] * (likelihood(t + 1) .* β[t + 1]) .* grids[t + 1][2] ./ c[t + 1]
end
p = [α[t] .* β[t] ./ sum(α[t] .* β[t]) for t in 1:T]
m = [sum(p[t] .* grids[t][1]) for t in 1:T]
return sum(log, c), m, [sum(p[t] .* (grids[t][1] .- m[t]) .^ 2) for t in 1:T]
end
prior_τ, prior_γ = Gamma(0.01, 1 / 0.01), Gamma(0.01, 1 / 0.01)
# The joint posterior of (log τ, log γ) on a grid, with the Jacobian of the logarithms
function precision_grid(y, (u_lo, u_hi), (v_lo, v_hi); n)
us, vs = range(u_lo, u_hi, length = n), range(v_lo, v_hi, length = n)
L = [hidden_markov(y, exp(u), exp(v)) + logpdf(prior_τ, exp(u)) + logpdf(prior_γ, exp(v)) + u + v for u in us, v in vs]
P = exp.(L .- maximum(L))
return (; us, vs, L, P = P ./ sum(P))
end
function exact_posterior(y)
coarse = precision_grid(y, (log(0.05), log(20.0)), (log(1.0e-6), log(1.0e-2)); n = 25)
mu, mv = sum(coarse.P .* coarse.us), sum(coarse.P .* coarse.vs')
su, sv = sqrt(sum(coarse.P .* (coarse.us .- mu) .^ 2)), sqrt(sum(coarse.P .* (coarse.vs' .- mv) .^ 2))
fine = precision_grid(y, (mu - 6su, mu + 6su), (mv - 6sv, mv + 6sv); n = 41)
# the path, mixed over the grid points that hold the mass
keep = findall(>(1.0e-6 * maximum(fine.P)), fine.P)
weights = fine.P[keep] ./ sum(fine.P[keep])
m, m2 = zeros(length(y)), zeros(length(y))
for (w, I) in zip(weights, keep)
_, mk, vk = hidden_markov(y, exp(fine.us[I[1]]), exp(fine.vs[I[2]]); smooth = true)
m .+= w .* mk; m2 .+= w .* (vk .+ mk .^ 2)
end
logevidence = maximum(fine.L) + log(sum(exp.(fine.L .- maximum(fine.L))) * step(fine.us) * step(fine.vs))
τs, γs = exp.(fine.us), exp.(fine.vs)
Pτ, Pγ = vec(sum(fine.P; dims = 2)), vec(sum(fine.P; dims = 1))
return (;
z_mean = m, z_sd = sqrt.(m2 .- m .^ 2), logevidence,
τ = (values = τs, density = Pτ ./ (step(fine.us) .* τs), mean = sum(Pτ .* τs), sd = sqrt(sum(Pτ .* τs .^ 2) - sum(Pτ .* τs)^2)),
γ = (values = γs, density = Pγ ./ (step(fine.vs) .* γs), mean = sum(Pγ .* γs), sd = sqrt(sum(Pγ .* γs .^ 2) - sum(Pγ .* γs)^2)),
)
end
exact = exact_posterior(measurements);
Results
rms(a) = sqrt(sum(abs2, a) / length(a))
summary_row(name, r) = [name mean(r.posteriors[:τ]) std(r.posteriors[:τ]) 1.0e4 * mean(r.posteriors[:γ]) 1.0e4 * std(r.posteriors[:γ]) rms(mean.(r.posteriors[:z]) - exact.z_mean) maximum(abs, std.(r.posteriors[:z]) ./ exact.z_sd .- 1) last(r.free_energy)]
exact_row = ["exact" exact.τ.mean exact.τ.sd 1.0e4 * exact.γ.mean 1.0e4 * exact.γ.sd 0.0 0.0 -exact.logevidence]
columns = ["", "E[τ]", "sd(τ)", "E[γ] × 10⁴", "sd(γ) × 10⁴", "RMS of E[z] - exact", "max |sd(z) / exact - 1|", "free energy"]
show_rows(rows) = pretty_table(rows; column_labels = columns, formatters = [fmt__printf("%.3f", 2:8)], fit_table_in_display_horizontally = false)
qτ, qγ = results.posteriors[:τ], results.posteriors[:γ]
F_mean_field = last(results.free_energy)
@printf("posterior of τ: mean %.3f, sd %.3f (exact %.3f, %.3f)\n", mean(qτ), std(qτ), exact.τ.mean, exact.τ.sd)
@printf("posterior of γ: mean %.3e, sd %.3e (exact %.3e, %.3e)\n", mean(qγ), std(qγ), exact.γ.mean, exact.γ.sd)
show_rows([summary_row("mean field", results); exact_row])
posterior of τ: mean 2.472, sd 0.494 (exact 2.655, 1.581)
posterior of γ: mean 9.046e-05, sd 1.809e-05 (exact 1.026e-04, 4.586e-05)
┌────────────┬───────┬───────┬────────────┬─────────────┬─────────────────────┬─────────────────────────┬─────────────┐
│ │ E[τ] │ sd(τ) │ E[γ] × 10⁴ │ sd(γ) × 10⁴ │ RMS of E[z] - exact │ max |sd(z) / exact - 1| │ free energy │
├────────────┼───────┼───────┼────────────┼─────────────┼─────────────────────┼─────────────────────────┼─────────────┤
│ mean field │ 2.472 │ 0.494 │ 0.905 │ 0.181 │ 0.045 │ 0.157 │ 330.226 │
│ exact │ 2.655 │ 1.581 │ 1.026 │ 0.459 │ 0.000 │ 0.000 │ 328.834 │
└────────────┴───────┴───────┴────────────┴─────────────┴─────────────────────┴─────────────────────────┴─────────────┘The path is accurate: the posterior means of the locations are within 0.15 cm of the exact ones (0.05 cm RMS), and their standard deviations are within 17% of the exact ones. The plot shows the posterior of the path and the exact one, which are hard to tell apart.
m_z, s_z = mean.(results.posteriors[:z]), std.(results.posteriors[:z])
plot(1:nr_observations, exact.z_mean; ribbon = 2exact.z_sd, fillalpha = 0.3, color = :gray, label = "exact (±2 sd)", legend = :topleft, size = (900, 450))
plot!(1:nr_observations, m_z; ribbon = 2s_z, fillalpha = 0.2, color = :orange, linewidth = 2, label = "natural-gradient propagation, mean field (±2 sd)")
scatter!(1:nr_observations, hidden_location; color = :red, markersize = 3, label = "hidden location")
xlabel!("time [sec]"); ylabel!("location [cm]")
![]()
The precisions show the effect of the factorisation. Both posterior means are close to the exact ones, but the posteriors are too narrow: the standard deviation of $\tau$ is about a third of the exact one, and that of $\gamma$ is under 40% of it. Mean field treats the path and the precisions as independent, but a rougher path with a noisier motion explains the same measurements, and so does a smoother path with a noisier sensor. Here the free energy lies above $-\log p(y)$, as a bound would, but it is not guaranteed to: the squared distance is a deterministic node between $z_t$ and the measurement, and with sites in the path the free energy of natural-gradient propagation is an estimate of $-\log p(y)$ rather than a bound.
p_τ = plot(exact.τ.values, exact.τ.density; color = :black, linewidth = 2, label = "exact", xlabel = "τ", ylabel = "density", xlims = (0, 6))
plot!(p_τ, range(0.01, 6, length = 400), x -> pdf(qτ, x); color = :orange, linewidth = 2, label = "mean field")
vline!(p_τ, [τ_true]; color = :gray, linestyle = :dot, label = "true τ")
p_γ = plot(1.0e4 .* exact.γ.values, exact.γ.density ./ 1.0e4; color = :black, linewidth = 2, label = "exact", xlabel = "γ × 10⁴", ylabel = "density", xlims = (0, 4))
plot!(p_γ, range(0.001, 4, length = 400), x -> pdf(qγ, x / 1.0e4) / 1.0e4; color = :orange, linewidth = 2, label = "mean field")
vline!(p_γ, [1.0e4 * γ_true]; color = :gray, linestyle = :dot, label = "true γ")
plot(p_τ, p_γ; size = (1000, 400), bottom_margin = 5Plots.mm, left_margin = 5Plots.mm)
![]()
The starting point matters under mean field
The fixed point of variational message passing under mean field depends on where it starts. Started from $q(\gamma)$ with mean 1, which corresponds to a sensor noise of 1 cm², the iterations settle in a different fixed point: the path follows every measurement, the motion absorbs the noise, and the free energy is higher.
start_sharp = @initialization begin
q(τ) = GammaShapeRate(1.0, 1.0)
q(γ) = GammaShapeRate(1.0, 1.0)
end
results_sharp = infer(
model = measurement_model(), data = (y = measurements,), constraints = mean_field, initialization = start_sharp,
iterations = 300, fallback = NaturalGradientPropagation(), free_energy = true, returnvars = (z = KeepLast(), τ = KeepLast(), γ = KeepLast()),
)
@printf("E[γ] = %.3f, E[τ] = %.3f, free energy %.2f (from E[γ] = 10⁻⁴ at the start: %.2f)\n", mean(results_sharp.posteriors[:γ]), mean(results_sharp.posteriors[:τ]), last(results_sharp.free_energy), F_mean_field)
E[γ] = 0.979, E[τ] = 0.380, free energy 338.71 (from E[γ] = 10⁻⁴ at the start: 330.23)The free energy distinguishes the two fixed points without the exact answer: the start with a noisy sensor gives the lower free energy. The next section removes the factorisation between the path and the precision of the sensor, and starts from the sharp sensor.
The sensor precision without mean field
Without mean field between the path and $\gamma$, the message of an observation towards $\gamma$ is the belief propagation message, the likelihood integrated against the message of $z_t$:
\[\ell_t(\gamma) = \log \int \mathcal{N}\big(y_t \mid (z - s)^2, \gamma^{-1}\big)\, m_{z_t}(z)\, dz.\]
This is not in the Gamma family. Natural-gradient propagation gives each such message a Gamma site, which moves towards its target $\eta^\star = G(q)^{-1}\mathrm{Cov}_q[T(\gamma), \ell_t(\gamma)]$, where $T(\gamma) = (\log\gamma, \gamma)$ is the sufficient statistic of the Gamma and $G$ its Fisher information. The expectations are computed by quadrature in $\log\gamma$. The posterior of $\gamma$ is the prior times the 50 sites, a Gamma distribution.
To compute this integral, the squared distance and the sensor noise are combined into one node, written with its log-density. With μ[t] := compute_squared_distance(z[t]) in between, the integral would be against the message of $\mu_t$, whose Gaussian site can have a negative precision, and then the integral is not defined.
struct SquaredDistanceSensor{Z, G} <: ContinuousUnivariateDistribution
z::Z
γ::G
end
BayesBase.logpdf(d::SquaredDistanceSensor, y) = logpdf(Normal(compute_squared_distance(d.z), 1 / sqrt(d.γ)), y)
BayesBase.insupport(::SquaredDistanceSensor, y) = true
@define_factor_node(node = SquaredDistanceSensor, type = Stochastic, interfaces = [:out, :z, :γ])
@model function sensor_model(y)
τ ~ Gamma(shape = 0.01, rate = 0.01)
γ ~ Gamma(shape = 0.01, rate = 0.01)
z[1] ~ Normal(mean = 0, precision = τ)
y[1] ~ SquaredDistanceSensor(z[1], γ)
for t in 2:length(y)
z[t] ~ Normal(mean = z[t - 1] + 1, precision = τ)
y[t] ~ SquaredDistanceSensor(z[t], γ)
end
end
The path and $\gamma$ now form a loop through the 50 observations, so belief propagation starts from initial messages for $\gamma$ and for the locations. We start $\gamma$ from the sharp sensor, with mean 1, which misled mean field above. The precision of the motion stays under mean field: under belief propagation, the message of a transition towards a location would average over the message of its neighbour, which can be an improper Gaussian, and that expectation is not defined. With 50 Gamma sites and 50 Gaussian sites, we again run 300 iterations.
path_and_sensor = @constraints begin
q(z, τ, γ) = q(z, γ)q(τ)
end
initialization_bp = @initialization begin
q(τ) = GammaShapeRate(1.0, 1.0)
μ(γ) = GammaShapeRate(1.0, 1.0)
μ(z) = NormalMeanVariance(0.0, 100.0)
end
results_bp = infer(
model = sensor_model(),
data = (y = measurements,),
constraints = path_and_sensor,
initialization = initialization_bp,
iterations = 300,
fallback = NaturalGradientPropagation(),
free_energy = true,
report = true,
returnvars = (z = KeepLast(), τ = KeepLast(), γ = KeepLast()),
)
Inference results:
Posteriors | available for (γ, τ, z)
Free Energy: | [-670.935, 351.303, 387.837, 424.69, 398.985, 431.054, 397.105, 403.123, 370.522, 310.269 … 327.9, 327.9, 327.9, 327.9, 327.9, 327.9, 327.9, 327.9, 327.9, 327.9]The report now lists $\gamma$ among the approximated posteriors, with its 50 Gamma sites, all settled. It also warns about the messages towards the locations: the message of $\gamma$ is a Gamma distribution, and the fallback cannot integrate the likelihood against it, so it averages the log-likelihood over it, as variational message passing does.
records_bp = results_bp.report.approximations
records_bp
Approximations: 51 of 53 posteriors approximated (exact rules on approximated inputs: · (anonymous), τ), 1 warning
Diagnostics
╭─────────┬─────────────────────────────────────────────┬─────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ │ where │ what │
├─────────┼─────────────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ warning │ y[1:50] ~ SquaredDistanceSensor(z[1:50], γ) │ under BP, the messages towards z average over another variable's message: variational, not exact BP │
╰─────────┴─────────────────────────────────────────────┴─────────────────────────────────────────────────────────────────────────────────────────────────────╯
Approximated posteriors
╭─────────────────────────────────────────────┬─────────┬───────┬──────────┬────────────────────────────────────────────────────────────────────────────────╮
│ Messages from │ towards │ exact │ fallback │ expectations │
├─────────────────────────────────────────────┴─────────┴───────┴──────────┴────────────────────────────────────────────────────────────────────────────────┤
│ z[1]: natural-gradient propagation, 1 site, 300 steps │
├─────────────────────────────────────────────┬─────────┬───────┬──────────┬────────────────────────────────────────────────────────────────────────────────┤
│ z[1] ~ NormalMeanPrecision(0.0, τ) │ out │ 302 │ 0 │ │
│ · := +(z[1], 1.0) │ in[1] │ 301 │ 0 │ │
│ y[1] ~ SquaredDistanceSensor(z[1], γ) │ z │ 0 │ 300 │ GammaShapeRate → UnconstrainedLegendre │
├─────────────────────────────────────────────┴─────────┴───────┴──────────┴────────────────────────────────────────────────────────────────────────────────┤
│ z[2:49]: natural-gradient propagation, 48 sites, 14400 steps │
├─────────────────────────────────────────────┬─────────┬───────┬──────────┬────────────────────────────────────────────────────────────────────────────────┤
│ z[2:49] ~ NormalMeanPrecision(·, τ) │ out │ 14448 │ 0 │ │
│ · := +(z[2:49], 1.0) │ in[1] │ 14448 │ 0 │ │
│ y[2:49] ~ SquaredDistanceSensor(z[2:49], γ) │ z │ 0 │ 14400 │ GammaShapeRate → UnconstrainedLegendre │
├─────────────────────────────────────────────┴─────────┴───────┴──────────┴────────────────────────────────────────────────────────────────────────────────┤
│ z[50]: natural-gradient propagation, 1 site, 300 steps │
├─────────────────────────────────────────────┬─────────┬───────┬──────────┬────────────────────────────────────────────────────────────────────────────────┤
│ z[50] ~ NormalMeanPrecision(·, τ) │ out │ 301 │ 0 │ │
│ y[50] ~ SquaredDistanceSensor(z[50], γ) │ z │ 0 │ 300 │ GammaShapeRate → UnconstrainedLegendre │
├─────────────────────────────────────────────┴─────────┴───────┴──────────┴────────────────────────────────────────────────────────────────────────────────┤
│ γ: natural-gradient propagation, 50 sites, 15000 steps │
├─────────────────────────────────────────────┬─────────┬───────┬──────────┬────────────────────────────────────────────────────────────────────────────────┤
│ γ ~ GammaShapeRate(0.01, 0.01) │ out │ 1 │ 0 │ │
│ y[1:50] ~ SquaredDistanceSensor(z[1:50], γ) │ γ │ 0 │ 15000 │ NormalMeanPrecision → GaussHermite, NormalWeightedMeanPrecision → GaussHermite │
╰─────────────────────────────────────────────┴─────────┴───────┴──────────┴────────────────────────────────────────────────────────────────────────────────╯
Joints and energies by the fallback
╭─────────────────────────────────────────────┬─────────────────┬───────┬──────────────────────────╮
│ Node │ computed │ times │ how │
├─────────────────────────────────────────────┼─────────────────┼───────┼──────────────────────────┤
│ y[1:50] ~ SquaredDistanceSensor(z[1:50], γ) │ average energy │ 15000 │ expectation │
│ y[1:50] ~ SquaredDistanceSensor(z[1:50], γ) │ joint of (z, γ) │ 15000 │ joint Laplace, converged │
╰─────────────────────────────────────────────┴─────────────────┴───────┴──────────────────────────╯
Expectations: ExactSum, GaussHermite, UnconstrainedLegendre, QuantileLegendreqγ_bp, qτ_bp = results_bp.posteriors[:γ], results_bp.posteriors[:τ]
F_bp = last(results_bp.free_energy)
show_rows([summary_row("mean field", results); summary_row("q(z, γ) q(τ)", results_bp); exact_row])
┌──────────────┬───────┬───────┬────────────┬─────────────┬─────────────────────┬─────────────────────────┬─────────────┐
│ │ E[τ] │ sd(τ) │ E[γ] × 10⁴ │ sd(γ) × 10⁴ │ RMS of E[z] - exact │ max |sd(z) / exact - 1| │ free energy │
├──────────────┼───────┼───────┼────────────┼─────────────┼─────────────────────┼─────────────────────────┼─────────────┤
│ mean field │ 2.472 │ 0.494 │ 0.905 │ 0.181 │ 0.045 │ 0.157 │ 330.226 │
│ q(z, γ) q(τ) │ 2.082 │ 0.416 │ 0.991 │ 0.295 │ 0.035 │ 0.158 │ 327.900 │
│ exact │ 2.655 │ 1.581 │ 1.026 │ 0.459 │ 0.000 │ 0.000 │ 328.834 │
└──────────────┴───────┴───────┴────────────┴─────────────┴─────────────────────┴─────────────────────────┴─────────────┘From the sharp start, the iterations find the noisy sensor. With the path and the sensor precision kept together, the posterior of $\gamma$ is closer to the exact one in both mean and spread: its standard deviation is about two thirds of the exact one, compared with under 40% under mean field. The precision of the motion, still under mean field, is as narrow as before and further from the exact mean. The path is as accurate as before.
The free energy is now below $-\log p(y)$. With a loop through the observations it is the Bethe free energy, with the average energies of the nodes without rules. It is a diagnostic of the fixed point and not a bound, so it cannot rank this run against the mean-field run.
p_γ_bp = plot(1.0e4 .* exact.γ.values, exact.γ.density ./ 1.0e4; color = :black, linewidth = 2, label = "exact", xlabel = "γ × 10⁴", ylabel = "density", xlims = (0, 4))
plot!(p_γ_bp, range(0.001, 4, length = 400), x -> pdf(qγ, x / 1.0e4) / 1.0e4; color = :orange, linewidth = 2, label = "mean field")
plot!(p_γ_bp, range(0.001, 4, length = 400), x -> pdf(qγ_bp, x / 1.0e4) / 1.0e4; color = :blue, linewidth = 2, label = "q(z, γ) q(τ)")
vline!(p_γ_bp, [1.0e4 * γ_true]; color = :gray, linestyle = :dot, label = "true γ")
plot!(p_γ_bp; size = (700, 400), bottom_margin = 5Plots.mm, left_margin = 5Plots.mm)
![]()
Summary
- The squared distance is a plain Julia function, and
fallback = NaturalGradientPropagation()runs the model without a rule, approximation method or form constraint for it. The report shows that the path was approximated with natural-gradient sites. - Under mean field, both precisions get Gamma messages from the rules of the
Normalnodes and have exact Gamma posteriors, and the sites are only on the path. Without mean field between the path and $\gamma$, the messages to $\gamma$ are belief propagation messages, which are not in the Gamma family, and its posterior is the prior times 50 Gamma sites. - The path matches the exact posterior to a few hundredths of a centimetre. Mean field makes both precisions too narrow; keeping $\gamma$ together with the path widens its posterior to two thirds of the exact standard deviation.
References
- M. Lukashchuk, K. Yemets, A. Ledbetter and İ. Şenöz (2026). Information geometry of message passing. arXiv:2608.15922.
- M. E. Khan and W. Lin (2017). Conjugate-computation variational inference: converting variational inference in non-conjugate models to inferences in conjugate models. AISTATS.
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! 💪
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
[91a5bcdd] Plots v1.41.10
[08abe8d2] PrettyTables v3.5.1
[86711068] RxInfer v6.2.0
[860ef19b] StableRNGs v1.1.0
[37e2e46d] LinearAlgebra v1.13.0
[de0858da] Printf v1.11.0
Info Packages marked with ⌃ have new versions available and may be upgradable.