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! 💪


Poisson Count Series

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. The Stochastic Volatility example smooths a latent autoregressive process observed through a nonlinear node. Here the observations are counts, and we compare the Gaussian approximations of the fallback with the exact posterior. LocalLaplace() projects each product of messages separately. Three other schemes, ExpectationPropagation(), LaplacePropagation() and NaturalGradientPropagation(), keep a site per edge so that the beliefs agree with each other.

A latent log-rate follows an autoregressive process, and each count is Poisson with rate $e^{x_t}$:

\[\begin{aligned} x_1 &\sim \mathcal{N}(0.5, 1),\\ x_t &\sim \mathcal{N}(\varphi x_{t-1}, \sigma^2),\\ y_t &\sim \mathrm{Poisson}(e^{x_t}). \end{aligned}\]

The state is one-dimensional, so the exact posterior can be computed: on a fine grid of $x$, the model is a hidden Markov model, and the forward-backward algorithm gives the exact smoothing marginals and the exact evidence $p(y)$.

using RxInfer, BayesBase, Distributions, SpecialFunctions, StableRNGs
using Plots, PrettyTables, Printf

The observation node

The count is a custom node, defined only by its log-density. Writing it as y[t] ~ Poisson(exp(x[t])) would put a deterministic node exp before RxInfer's Poisson node. Inference works that way too, as in the Doctor Visits example: the fallback pulls the Poisson node's message back through exp, exactly. The free energy is another matter: the term of the Poisson node needs $\mathrm{E}[\log \lambda]$ under the marginal of each rate, one more variable and one more approximation per count. A node that takes the log-rate directly has no rate variable, and its free energy term is an expectation under the Gaussian of $x_t$.

struct LogPoisson{X} <: DiscreteUnivariateDistribution
    x::X
end

BayesBase.logpdf(d::LogPoisson, k) = k * d.x - exp(d.x) - loggamma(k + 1)
BayesBase.insupport(::LogPoisson, k) = true

@define_factor_node(node = LogPoisson, type = Stochastic, interfaces = [:out, :x])

Data

φ, σ², T = 0.9, 0.1, 150
rng = StableRNG(42)

x_true = zeros(T)
x_true[1] = rand(rng, Normal(0.5, 1.0))
for t in 2:T
    x_true[t] = φ * x_true[t - 1] + rand(rng, Normal(0.0, sqrt(σ²)))
end
y = [rand(rng, Poisson(exp(x))) for x in x_true]

bar(y; color = :gray, label = "counts yₜ", xlabel = "t", size = (800, 300))

Inference

@model function count_series(y, φ, σ²)
    x[1] ~ NormalMeanVariance(0.5, 1.0)
    y[1] ~ LogPoisson(x[1])
    for t in 2:length(y)
        x[t] ~ NormalMeanVariance(φ * x[t - 1], σ²)
        y[t] ~ LogPoisson(x[t])
    end
end

laplace = infer(
    model = count_series(φ = φ, σ² = σ²), data = (y = y,),
    fallback = LocalLaplace(), free_energy = true, report = true,
)
Inference results:
  Posteriors       | available for (x)
  Free Energy:     | [207.346]

Under belief propagation, the transitions keep their exact rules. Each product of messages on the chain, a marginal or a message leaving $x_t$, is projected onto a Gaussian by the Laplace method, at its mode and with the curvature there. The report shows this:

laplace.report.approximations
  Approximations: 150 of 151 posteriors approximated (exact rules on approximated inputs: · (anonymous)), no warnings
                               Approximated posteriors
╭───────────────────────────────────────┬─────────┬───────┬──────────┬──────────────╮
│ Messages from                         │ towards │ exact │ fallback │ expectations │
├───────────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ x[1]: Laplace, converged in 5 iterations, log Z = -1.41                           │
├───────────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ x[1] ~ NormalMeanVariance(0.5, 1.0)   │ out     │ 1     │ 0        │              │
│ · := *(0.9, x[1])                     │ in      │ 1     │ 0        │              │
│ y[1] ~ LogPoisson(x[1])               │ x       │ 0     │ 1        │ exact        │
├───────────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ x[2:149]: Laplace, 148 of 148 converged, 3 to 5 iterations                        │
├───────────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ x[2:149] ~ NormalMeanVariance(·, 0.1) │ out     │ 148   │ 0        │              │
│ · := *(0.9, x[2:149])                 │ in      │ 148   │ 0        │              │
│ y[2:149] ~ LogPoisson(x[2:149])       │ x       │ 0     │ 148      │ exact        │
├───────────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ x[150]: Laplace, converged in 4 iterations, log Z = -1.183                        │
├───────────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ x[150] ~ NormalMeanVariance(·, 0.1)   │ out     │ 1     │ 0        │              │
│ y[150] ~ LogPoisson(x[150])           │ x       │ 0     │ 1        │ exact        │
╰───────────────────────────────────────┴─────────┴───────┴──────────┴──────────────╯

                   Joints and energies by the fallback
╭─────────────────────────────────┬────────────────┬───────┬─────────────╮
│ Node                            │ computed       │ times │ how         │
├─────────────────────────────────┼────────────────┼───────┼─────────────┤
│ y[1:150] ~ LogPoisson(x[1:150]) │ average energy │ 150   │ expectation │
╰─────────────────────────────────┴────────────────┴───────┴─────────────╯

    Expectations: ExactSum, GaussHermite, UnconstrainedLegendre, QuantileLegendre

The exact smoother

On a grid of 801 points for $x$, the transition is a matrix and each count is a vector of likelihoods. A forward pass gives the filtering distributions and the evidence, and a backward pass gives the smoothing distributions.

function exact_smoother(y; grid = range(-5, 5, length = 801))
    h = step(grid)
    K = [pdf(Normal(φ * u, sqrt(σ²)), v) * h for u in grid, v in grid]
    likelihood(t) = [exp(logpdf(LogPoisson(u), y[t])) for u in grid]
    α, c = zeros(length(grid), T), zeros(T)
    a = [pdf(Normal(0.5, 1.0), u) * h for u in grid] .* likelihood(1)
    c[1] = sum(a); α[:, 1] = a ./ c[1]
    for t in 2:T
        a = (K' * α[:, t - 1]) .* likelihood(t)
        c[t] = sum(a); α[:, t] = a ./ c[t]
    end
    β = ones(length(grid), T)
    for t in (T - 1):-1:1
        β[:, t] = K * (likelihood(t + 1) .* β[:, t + 1]) ./ c[t + 1]
    end
    P = α .* β
    P ./= sum(P; dims = 1)
    m = [sum(P[:, t] .* grid) for t in 1:T]
    s = [sqrt(sum(P[:, t] .* (grid .- m[t]) .^ 2)) for t in 1:T]
    return (; mean = m, sd = s, logevidence = sum(log, c))
end

exact = exact_smoother(y)
(mean = [-0.03125371625340313, 0.034604757879788964, 0.11629371324881263, 0.22352203364366585, 0.26041990461735814, 0.4544086560521611, 0.617493947451982, 0.6725180277967269, 0.6319955802735508, 0.7084595278943623  …  -0.7163488609860189, -0.7412923701120528, -0.7158393180478806, -0.749268495031027, -0.7327829405487398, -0.665211793185547, -0.6527540149122809, -0.583280931266537, -0.5623117325051551, -0.4765871198652444], sd = [0.5035244561285054, 0.44348918402174126, 0.4074700655095431, 0.3848109203201839, 0.369856253558755, 0.3555732184339496, 0.34415365879260107, 0.3382395974199377, 0.3368911273960451, 0.335508155441134  …  0.4535205249050106, 0.4561730147629808, 0.45766204969956137, 0.45910283398699386, 0.45998528921638004, 0.4609697092401565, 0.4641794526654264, 0.4708194467335931, 0.48480986469798476, 0.5105585987735831], logevidence = -206.6352370871191)

Results

m_laplace, s_laplace = mean.(laplace.posteriors[:x]), std.(laplace.posteriors[:x])

plt = plot(exact.mean; ribbon = 2exact.sd, fillalpha = 0.2, color = :gray, label = "exact (±2 sd)", xlabel = "t", ylabel = "log-rate xₜ", size = (900, 450), legend = :outerbottom, legendcolumns = 3)
plot!(plt, m_laplace; color = :blue, label = "LocalLaplace()")
plot!(plt, x_true; color = :black, linewidth = 1, label = "true xₜ")

rms(a) = sqrt(sum(abs2, a) / length(a))
F_laplace = only(laplace.free_energy)
rows = [
    "LocalLaplace()" rms(m_laplace - exact.mean) maximum(abs, m_laplace - exact.mean) maximum(abs, s_laplace - exact.sd) F_laplace;
    "exact" 0.0 0.0 0.0 -exact.logevidence
]
pretty_table(rows; column_labels = ["", "RMS of mean - exact", "max |mean - exact|", "max |sd - exact|", "free energy"], formatters = [fmt__printf("%.4f", 2:5)], fit_table_in_display_horizontally = false)
┌────────────────┬─────────────────────┬────────────────────┬──────────────────┬─────────────┐
│                │ RMS of mean - exact │ max |mean - exact| │ max |sd - exact| │ free energy │
├────────────────┼─────────────────────┼────────────────────┼──────────────────┼─────────────┤
│ LocalLaplace() │              0.1125 │             0.2075 │           0.0208 │    207.3459 │
│          exact │              0.0000 │             0.0000 │           0.0000 │    206.6352 │
└────────────────┴─────────────────────┴────────────────────┴──────────────────┴─────────────┘

The means of LocalLaplace() are about 0.1 from those of the exact smoother. A count of zero, or a count far from the rate, makes the posterior of $x_t$ skewed, and the Laplace method places its Gaussian at the mode. The spreads are close to the exact ones.

The free energy exceeds $-\log p(y)$ by about 0.7. Under belief propagation, a projected marginal and the joints of the transition nodes next to it are computed from different messages, so they do not agree exactly. The free energy of such beliefs is then an estimate of $-\log p(y)$ and not a bound, so a lower value does not mean a better fit. The schemes of the next section make the beliefs agree.

Cavity propagation

Under fallback = ExpectationPropagation(), each $x_t$ keeps one Gaussian site per edge, and its beliefs are products of sites. Its marginal is the product of all its sites, and the message it sends on an edge is the product of the sites of its other edges, called the cavity of that edge. The message from the count is a log-density. It is multiplied by its cavity, the messages of the two transitions, and projected by moment matching, and then the cavity is divided out again. The result is the site of the count. The marginal and the messages to the transitions are then built from the same sites, so the joints of the transitions agree with the marginals. Each site depends on the sites of its neighbours along the chain, and the iterations update the sites until they reach a fixed point. LaplacePropagation() does the same with the Laplace method, using the mode and curvature of each tilted belief, the message times its cavity.

NaturalGradientPropagation() keeps the same sites, but moves each one by a step instead of projecting it (Lukashchuk et al., Information Geometry of Message Passing). The site of the count on $x_t$ is a Gaussian, from the family of its cavity. At each iteration it moves towards its target $\eta^\star = G(q)^{-1}\,\mathrm{Cov}_q[T(x_t), \ell(x_t)]$, the natural gradient of $\mathbb{E}_q[\ell]$, where $\ell$ is the log-density of the count, $q$ the marginal of $x_t$, and $T$ and $G$ the sufficient statistic and the Fisher information of the Gaussian. The move is a damped heavy-ball step in natural parameters, $v \leftarrow \beta v + \alpha(\eta^\star - \eta)$ and $\eta \leftarrow \eta + v$, with the step size alpha = 0.5 and the momentum beta = 0.2 by default. At the fixed point each site equals its target. The chain is then a Gaussian tree whose only non-conjugate factors, the counts, are leaves. The beliefs form the Gaussian over the whole path that is closest to the posterior in $\mathrm{KL}(q \,\|\, p)$, and the free energy is its negative evidence lower bound, an upper bound on $-\log p(y)$. Conjugate-computation variational inference reaches the same fixed point.

Natural-gradient steps need more iterations than projections: with thirty iterations, every site settles to the tolerance of the scheme, tol = 1e-8 relative.

propagate(fallback) = infer(
    model = count_series(φ = φ, σ² = σ²), data = (y = y,), iterations = 30,
    fallback = fallback, free_energy = true, returnvars = (x = KeepLast(),), report = true,
)

ep = propagate(ExpectationPropagation())
lp = propagate(LaplacePropagation())
ngmp = propagate(NaturalGradientPropagation())
Inference results:
  Posteriors       | available for (x)
  Free Energy:     | [209.682, 207.012, 206.764, 206.744, 206.739, 206.737, 206.737, 206.737, 206.737, 206.737  …  206.737, 206.737, 206.737, 206.737, 206.737, 206.737, 206.737, 206.737, 206.737, 206.737]

The report lists the sites, one per edge of each $x_t$, and how many projections were made over the thirty iterations, here for expectation propagation. Under NaturalGradientPropagation(), it counts the steps of the site of each count instead and says whether each site has settled at its target:

ep.report.approximations
  Approximations: 150 of 151 posteriors approximated (exact rules on approximated inputs: · (anonymous)), no warnings
                               Approximated posteriors
╭───────────────────────────────────────┬─────────┬───────┬──────────┬──────────────╮
│ Messages from                         │ towards │ exact │ fallback │ expectations │
├───────────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ x[1]: expectation propagation, 30 sites                                           │
├───────────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ x[1] ~ NormalMeanVariance(0.5, 1.0)   │ out     │ 1     │ 0        │              │
│ · := *(0.9, x[1])                     │ in      │ 30    │ 0        │              │
│ y[1] ~ LogPoisson(x[1])               │ x       │ 0     │ 30       │ exact        │
├───────────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ x[2:149]: expectation propagation, 4440 sites                                     │
├───────────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ x[2:149] ~ NormalMeanVariance(·, 0.1) │ out     │ 4440  │ 0        │              │
│ · := *(0.9, x[2:149])                 │ in      │ 4440  │ 0        │              │
│ y[2:149] ~ LogPoisson(x[2:149])       │ x       │ 0     │ 4440     │ exact        │
├───────────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ x[150]: expectation propagation, 30 sites                                         │
├───────────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ x[150] ~ NormalMeanVariance(·, 0.1)   │ out     │ 30    │ 0        │              │
│ y[150] ~ LogPoisson(x[150])           │ x       │ 0     │ 30       │ exact        │
╰───────────────────────────────────────┴─────────┴───────┴──────────┴──────────────╯

                           Joints and energies by the fallback
╭─────────────────────────────────┬────────────────┬───────┬────────────────────────────╮
│ Node                            │ computed       │ times │ how                        │
├─────────────────────────────────┼────────────────┼───────┼────────────────────────────┤
│ y[1:150] ~ LogPoisson(x[1:150]) │ average energy │ 4500  │ moment_matching, converged │
╰─────────────────────────────────┴────────────────┴───────┴────────────────────────────╯

    Expectations: ExactSum, GaussHermite, UnconstrainedLegendre, QuantileLegendre
m_ep, s_ep = mean.(ep.posteriors[:x]), std.(ep.posteriors[:x])
m_lp, s_lp = mean.(lp.posteriors[:x]), std.(lp.posteriors[:x])
m_ngmp, s_ngmp = mean.(ngmp.posteriors[:x]), std.(ngmp.posteriors[:x])
F_ep, F_lp, F_ngmp = last(ep.free_energy), last(lp.free_energy), last(ngmp.free_energy)
rows = [
    "LocalLaplace()" rms(m_laplace - exact.mean) maximum(abs, m_laplace - exact.mean) maximum(abs, s_laplace - exact.sd) F_laplace;
    "LaplacePropagation()" rms(m_lp - exact.mean) maximum(abs, m_lp - exact.mean) maximum(abs, s_lp - exact.sd) F_lp;
    "ExpectationPropagation()" rms(m_ep - exact.mean) maximum(abs, m_ep - exact.mean) maximum(abs, s_ep - exact.sd) F_ep;
    "NaturalGradientPropagation()" rms(m_ngmp - exact.mean) maximum(abs, m_ngmp - exact.mean) maximum(abs, s_ngmp - exact.sd) F_ngmp;
    "exact" 0.0 0.0 0.0 -exact.logevidence
]
pretty_table(rows; column_labels = ["", "RMS of mean - exact", "max |mean - exact|", "max |sd - exact|", "free energy"], formatters = [fmt__printf("%.4f", 2:5)], fit_table_in_display_horizontally = false)
┌──────────────────────────────┬─────────────────────┬────────────────────┬──────────────────┬─────────────┐
│                              │ RMS of mean - exact │ max |mean - exact| │ max |sd - exact| │ free energy │
├──────────────────────────────┼─────────────────────┼────────────────────┼──────────────────┼─────────────┤
│               LocalLaplace() │              0.1125 │             0.2075 │           0.0208 │    207.3459 │
│         LaplacePropagation() │              0.0728 │             0.0841 │           0.0038 │    206.6841 │
│     ExpectationPropagation() │              0.0000 │             0.0001 │           0.0033 │    206.6861 │
│ NaturalGradientPropagation() │              0.0002 │             0.0004 │           0.0064 │    206.7365 │
│                        exact │              0.0000 │             0.0000 │           0.0000 │    206.6352 │
└──────────────────────────────┴─────────────────────┴────────────────────┴──────────────────┴─────────────┘

The means from expectation propagation match those of the exact smoother to about $10^{-4}$, and its spreads to within a few thousandths. The means from natural-gradient propagation are nearly as close, to a few $10^{-4}$, and its spreads are a little smaller than the exact ones, as is usual for a variational Gaussian: $\mathrm{KL}(q \,\|\, p)$ penalises mass where the posterior has little. Laplace propagation reaches the global Laplace approximation, the mode of the whole posterior and the curvature there. Its spreads are as close as those of EP. Its means are the modes of skewed marginals: closer to the exact means than those of LocalLaplace(), but about 0.07 away.

Every belief is now built from the same sites, so the joints of the transitions agree with the marginals. The free energies of the three schemes mean two different things. For expectation and Laplace propagation, it is the free energy of expectation propagation: each node without rules takes its term from its cavities, the other terms are the Bethe terms, and at the fixed point it estimates $-\log p(y)$, here to within 0.06, but it is not a bound. For natural-gradient propagation, it is the Bethe free energy with the average energies of the counts under the marginals. This is the negative evidence lower bound, about 0.1 above $-\log p(y)$, and it cannot go below $-\log p(y)$; the gap is the divergence of the Gaussian path from the posterior. Each free energy is computed once per iteration and settles within a few iterations:

plot(ep.free_energy; marker = :circle, color = :red, label = "ExpectationPropagation()", xlabel = "iteration", ylabel = "free energy", size = (800, 350))
plot!(lp.free_energy; marker = :circle, color = :blue, label = "LaplacePropagation()")
plot!(ngmp.free_energy; marker = :circle, color = :green, label = "NaturalGradientPropagation()")
hline!([-exact.logevidence]; color = :black, linestyle = :dot, label = "-log p(y), exact")

Learning the transition precision

Now the precision of the transition, $\tau = 1/\sigma^2$, is unknown, with a $\mathrm{Gamma}(2, 0.2)$ prior, and we factorise $q(x, \tau) = q(x)\,q(\tau)$. The chain keeps belief propagation, and the update of $\tau$ is conjugate: its posterior is a Gamma distribution, which the projection of the fallback leaves unchanged. We compare LocalLaplace() with NaturalGradientPropagation(). Under mean field, the transitions send variational messages to the $x_t$. These messages are Gaussians and are their own sites, and the site of the count on each $x_t$ moves as before. Coordinate ascent between the path and its precision is slow, so both schemes run for 200 iterations.

@model function count_series_τ(y, φ)
    τ ~ Gamma(shape = 2.0, rate = 0.2)
    x[1] ~ NormalMeanVariance(0.5, 1.0)
    y[1] ~ LogPoisson(x[1])
    for t in 2:length(y)
        x[t] ~ NormalMeanPrecision(φ * x[t - 1], τ)
        y[t] ~ LogPoisson(x[t])
    end
end

separate_τ = @constraints begin
    q(x, τ) = q(x)q(τ)
end

initial_τ = @initialization begin
    q(τ) = GammaShapeRate(2.0, 0.2)
end

fit_τ(fallback) = infer(
    model = count_series_τ(φ = φ), data = (y = y,),
    constraints = separate_τ, initialization = initial_τ,
    iterations = 200, fallback = fallback, free_energy = true, report = true,
)

laplace_τ, ngmp_τ = fit_τ(LocalLaplace()), fit_τ(NaturalGradientPropagation())
(Inference results:
  Posteriors       | available for (τ, x)
  Free Energy:     | [209.113, 208.941, 208.798, 208.679, 208.58, 208.498, 208.431, 208.375, 208.328, 208.29  …  208.13, 208.13, 208.13, 208.13, 208.13, 208.13, 208.13, 208.13, 208.13, 208.13]
, Inference results:
  Posteriors       | available for (τ, x)
  Free Energy:     | [211.401, 208.613, 208.297, 208.216, 208.159, 208.112, 208.073, 208.04, 208.012, 207.988  …  207.863, 207.863, 207.863, 207.863, 207.863, 207.863, 207.863, 207.863, 207.863, 207.863]
)

The report confirms that the posterior of $\tau$ is exact and that the posterior of every $x_t$ is approximated:

records_τ = ngmp_τ.report.approximations
records_τ
  Approximations: 150 of 152 posteriors approximated (exact rules on approximated inputs: · (anonymous), τ), no warnings
                              Approximated posteriors
╭──────────────────────────────────────┬─────────┬───────┬──────────┬──────────────╮
│ Messages from                        │ towards │ exact │ fallback │ expectations │
├──────────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ x[1]: natural-gradient propagation, 1 site, 200 steps                            │
├──────────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ x[1] ~ NormalMeanVariance(0.5, 1.0)  │ out     │ 1     │ 0        │              │
│ · := *(0.9, x[1])                    │ in      │ 200   │ 0        │              │
│ y[1] ~ LogPoisson(x[1])              │ x       │ 0     │ 200      │ exact        │
├──────────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ x[2:149]: natural-gradient propagation, 148 sites, 29600 steps                   │
├──────────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ x[2:149] ~ NormalMeanPrecision(·, τ) │ out     │ 29600 │ 0        │              │
│ · := *(0.9, x[2:149])                │ in      │ 29600 │ 0        │              │
│ y[2:149] ~ LogPoisson(x[2:149])      │ x       │ 0     │ 29600    │ exact        │
├──────────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ x[150]: natural-gradient propagation, 1 site, 200 steps                          │
├──────────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ x[150] ~ NormalMeanPrecision(·, τ)   │ out     │ 200   │ 0        │              │
│ y[150] ~ LogPoisson(x[150])          │ x       │ 0     │ 200      │ exact        │
╰──────────────────────────────────────┴─────────┴───────┴──────────┴──────────────╯

                   Joints and energies by the fallback
╭─────────────────────────────────┬────────────────┬───────┬─────────────╮
│ Node                            │ computed       │ times │ how         │
├─────────────────────────────────┼────────────────┼───────┼─────────────┤
│ y[1:150] ~ LogPoisson(x[1:150]) │ average energy │ 30000 │ expectation │
╰─────────────────────────────────┴────────────────┴───────┴─────────────╯

    Expectations: ExactSum, GaussHermite, UnconstrainedLegendre, QuantileLegendre

For the exact posterior of $\tau$, the forward pass gives the evidence $p(y \mid \tau)$ on a grid of $\tau$ values (a coarser grid of $x$ is enough for this), and its integral over the prior gives the evidence $p(y)$.

function logevidence_given(τ; grid = range(-4, 4, length = 321))
    h = step(grid)
    K = [pdf(Normal(φ * u, 1 / sqrt(τ)), v) * h for u in grid, v in grid]
    a = [pdf(Normal(0.5, 1.0), u) * h for u in grid] .* [exp(logpdf(LogPoisson(u), y[1])) for u in grid]
    s = log(sum(a)); a ./= sum(a)
    for t in 2:T
        a = (K' * a) .* [exp(logpdf(LogPoisson(u), y[t])) for u in grid]
        z = sum(a); s += log(z); a ./= z
    end
    return s
end

τs = range(0.5, 60, length = 240)
logposterior_τ = [logpdf(Gamma(2.0, 1 / 0.2), τ) + logevidence_given(τ) for τ in τs]
logevidence_τ = maximum(logposterior_τ) + log(sum(exp.(logposterior_τ .- maximum(logposterior_τ))) * step(τs))
w = exp.(logposterior_τ .- maximum(logposterior_τ)); w ./= sum(w)
Eτ = sum(w .* τs); sdτ = sqrt(sum(w .* (τs .- Eτ) .^ 2))

qτ_laplace, qτ_ngmp = laplace_τ.posteriors[:τ][end], ngmp_τ.posteriors[:τ][end]
F_laplace_τ, F_ngmp_τ = last(laplace_τ.free_energy), last(ngmp_τ.free_energy)
pretty_table(
    ["exact" Eτ sdτ -logevidence_τ; "LocalLaplace()" mean(qτ_laplace) std(qτ_laplace) F_laplace_τ; "NaturalGradientPropagation()" mean(qτ_ngmp) std(qτ_ngmp) F_ngmp_τ];
    column_labels = ["", "E[τ]", "sd(τ)", "free energy"], formatters = [fmt__printf("%.2f", 2:4)], fit_table_in_display_horizontally = false,
)
┌──────────────────────────────┬───────┬───────┬─────────────┐
│                              │  E[τ] │ sd(τ) │ free energy │
├──────────────────────────────┼───────┼───────┼─────────────┤
│                        exact │ 16.91 │  6.69 │      206.57 │
│               LocalLaplace() │ 17.66 │  2.02 │      208.13 │
│ NaturalGradientPropagation() │ 16.20 │  1.85 │      207.86 │
└──────────────────────────────┴───────┴───────┴─────────────┘

The data, 150 counts of about one or two, say little about $\tau$: its exact posterior is wide, and its mean is above the true value 10. Both schemes find a mean within half a standard deviation of the exact one, and neither is clearly closer than the other: their errors differ by a small fraction of that standard deviation. Both are overconfident by a factor of three or more. This comes from the factorisation $q(x)\,q(\tau)$: the path and its precision are learned as if they were independent, while a rougher path with a lower precision explains the same counts. The free energies show this too: that of natural-gradient propagation is lower, but still more than a nat above $-\log p(y)$, which is given in the first row. The plot shows the exact posterior and the two Gamma approximations.

τplot = range(0.5, 45, length = 400)
plot(τs, w ./ step(τs); color = :black, linewidth = 2, label = "exact", xlabel = "τ", ylabel = "density", xlims = (0, 45))
plot!(τplot, pdf.(qτ_laplace, τplot); color = :blue, label = "LocalLaplace()")
plot!(τplot, pdf.(qτ_ngmp, τplot); color = :red, linestyle = :dash, label = "NaturalGradientPropagation()")
vline!([1 / σ²]; color = :gray, linestyle = :dot, label = "true τ")


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
  [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
  [de0858da] Printf v1.11.0
Info Packages marked with ⌃ have new versions available and may be upgradable.