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


Gaussian Mixture without Conjugacy

This example is part of the Universal Inference section, which runs inference in a broad class of models by approximating every continuous latent variable with a Gaussian. Models often contain other kinds of variables, and a Gaussian mixture has two of them. The component assignments $z_i$ are discrete, with a finite number of values. They need no approximation: their beliefs are normalised exactly, and expectations over them are exact sums. The component precisions are constrained to be positive. Here we make them Gaussian in an unconstrained space by modelling the log-precisions $s_k$, so that the precision $e^{s_k}$ is positive for every value of $s_k$. (The Constrained Variables example of this section shows that the fallback can also do this itself, from the support of a prior.)

The model is

\[\begin{aligned} \pi &\sim \mathrm{Dirichlet}(1, \ldots, 1),\\ m &\sim \mathcal{N}(0, 100 I),\qquad s \sim \mathcal{N}(0, 4 I),\\ z_i &\sim \mathrm{Categorical}(\pi),\\ y_i &\sim \mathcal{N}\left(m_{z_i}, e^{-s_{z_i}}\right). \end{aligned}\]

The Dirichlet-Categorical pair is conjugate, so RxInfer uses its exact rules. fallback = LocalLaplace() handles the rest: Laplace approximations for $m$ and $s$, exact beliefs for the $z_i$, and variational messages computed as expectations of the log-density of the likelihood over the beliefs of the other variables. We compare the result with RxInfer's hand-derived conjugate solution for a similar model.

using RxInfer, BayesBase, Distributions, LinearAlgebra
using StatsFuns, StableRNGs, Plots, PrettyTables

The likelihood node

The mixture likelihood is a custom node with the interfaces out, z, m and s, and no message update rules. Its logpdf accepts the assignment either as a component index or as a vector of weights. The vector form is used only for a comparison at the end.

struct LogPrecisionMixture{Z, M, S} <: ContinuousUnivariateDistribution
    z::Z
    m::M
    s::S
end

component_weights(z::Integer, K) = (1:K) .== z
component_weights(z::AbstractVector, K) = z

function BayesBase.logpdf(d::LogPrecisionMixture, y)
    w = component_weights(d.z, length(d.m))
    return sum(w[k] * (d.s[k] - log2π - exp(d.s[k]) * (y - d.m[k])^2) / 2 for k in eachindex(d.m))
end
BayesBase.insupport(::LogPrecisionMixture, y) = true

@define_factor_node(node = LogPrecisionMixture, type = Stochastic, interfaces = [:out, :z, :m, :s])

Data

rng = StableRNG(42)
N, K = 300, 2
true_weights, true_means, true_sds = [0.4, 0.6], [-2.0, 2.0], [0.5, 1.0]
z_true = rand(rng, Categorical(true_weights), N)
y = [rand(rng, Normal(true_means[z], true_sds[z])) for z in z_true]

histogram(y; bins = 40, normalize = :pdf, color = :gray, alpha = 0.5, label = "data", xlabel = "y")

Inference

The model is written with vectors $m$ and $s$ of length $K$, so the same code works for any number of components. Mean-field inference is iterative and needs a starting point. The fallback initialises each variable from its prior unless we set an initialisation ourselves. The prior of $m$ is symmetric in the components, so, as in any variational treatment of mixtures, we give the components of $m$ different initial means to break the symmetry.

@model function laplace_mixture(y, K)
    π ~ Dirichlet(ones(K))
    m ~ MvNormalMeanCovariance(zeros(K), 100.0 * diageye(K))
    s ~ MvNormalMeanCovariance(zeros(K), 4.0 * diageye(K))
    for i in eachindex(y)
        z[i] ~ Categorical(π)
        y[i] ~ LogPrecisionMixture(z[i], m, s)
    end
end

mean_field = @constraints begin
    q(π, m, s, z) = q(π)q(m)q(s)q(z)
end

# The initial means differ to break the symmetry between the components; the priors start the rest
initial_means = @initialization begin
    q(m) = MvNormalMeanCovariance([-1.0, 1.0], diageye(K))
end

n_iterations = 30

result = infer(
    model = laplace_mixture(K = K),
    data = (y = y,),
    constraints = mean_field,
    initialization = initial_means,
    iterations = n_iterations,
    returnvars = (m = KeepEach(), s = KeepEach(), π = KeepLast()),
    fallback = LocalLaplace(),
    free_energy = true,
    report = true,
)

q_m, q_s, q_π = result.posteriors[:m][end], result.posteriors[:s][end], result.posteriors[:π]
(MvNormalMeanCovariance([-1.975973965712442, 1.9777560048828344], [0.0030957630392286044 0.0; 0.0 0.003972740672401174]), MvNormalMeanCovariance([0.9502102072067694, 0.35149369407301634], [0.016139856455108386 0.0; 0.0 0.011335792265488264]), Dirichlet([124.89194449719459, 177.10805550280548]))

We monitor convergence with the free energy and with the posterior means of the components. The free energy is the sum of the average energies of the nodes, with those of the likelihood computed by the fallback, minus the entropies of the beliefs. It falls by more than a hundred nats in the first iterations and then settles. A Laplace projection is not an exact coordinate update of mean-field inference, so after it settles the free energy may rise by a few millionths of a nat.

p1 = plot(1:n_iterations, result.free_energy; label = "free energy", xlabel = "iteration", ylabel = "free energy", marker = :circle)
p2 = plot(1:n_iterations, reduce(hcat, mean.(result.posteriors[:m]))'; label = ["E[m₁]" "E[m₂]"], xlabel = "iteration", ylabel = "posterior mean", marker = :circle)
plot(p1, p2; layout = (1, 2), size = (900, 350))

What was approximated

report = true recorded what the fallback did:

  • \[m\]

    and $s$ are projected by Laplace's method in every iteration. Their messages from the likelihood are variational messages, expectations over the other beliefs.
  • The assignments $z_i$ are normalised exactly over their components. Their messages come from the same likelihood and from the exact rule of the categorical prior.
  • \[\pi\]

    is not among the approximated posteriors. Its Dirichlet posterior comes from the exact rules of the conjugate pair.

The expectations over the categorical beliefs are exact sums, and those over the Gaussian beliefs of $m$ and $s$ use quadrature.

result.report.approximations
  Approximations: 302 of 303 posteriors approximated (exact rules on approximated inputs: π), no warnings
                                                Approximated posteriors
╭────────────────────────────────────────────────┬─────────┬───────┬──────────┬───────────────────────────────────────╮
│ Messages from                                  │ towards │ exact │ fallback │ expectations                          │
├────────────────────────────────────────────────┴─────────┴───────┴──────────┴───────────────────────────────────────┤
│ m: Laplace, converged in 1 iteration, log Z = -345.8                                                                │
├────────────────────────────────────────────────┬─────────┬───────┬──────────┬───────────────────────────────────────┤
│ m ~ MvNormalMeanCovariance([0.0, 0.0], const)  │ out     │ 1     │ 0        │                                       │
│ y[1:300] ~ LogPrecisionMixture(z[1:300], m, s) │ m       │ 0     │ 9000     │ MvNormalMeanCovariance → GaussHermite │
├────────────────────────────────────────────────┴─────────┴───────┴──────────┴───────────────────────────────────────┤
│ s: Laplace, converged in 1 iteration, log Z = -341.4                                                                │
├────────────────────────────────────────────────┬─────────┬───────┬──────────┬───────────────────────────────────────┤
│ s ~ MvNormalMeanCovariance([0.0, 0.0], const)  │ out     │ 1     │ 0        │                                       │
│ y[1:300] ~ LogPrecisionMixture(z[1:300], m, s) │ s       │ 0     │ 9000     │ MvNormalMeanCovariance → GaussHermite │
├────────────────────────────────────────────────┴─────────┴───────┴──────────┴───────────────────────────────────────┤
│ z[1:300]: normalized exactly                                                                                        │
├────────────────────────────────────────────────┬─────────┬───────┬──────────┬───────────────────────────────────────┤
│ z[1:300] ~ Categorical(π)                      │ out     │ 9000  │ 0        │                                       │
│ y[1:300] ~ LogPrecisionMixture(z[1:300], m, s) │ z       │ 0     │ 9000     │ MvNormalMeanCovariance → GaussHermite │
╰────────────────────────────────────────────────┴─────────┴───────┴──────────┴───────────────────────────────────────╯

                           Joints and energies by the fallback
╭────────────────────────────────────────────────┬────────────────┬───────┬─────────────╮
│ Node                                           │ computed       │ times │ how         │
├────────────────────────────────────────────────┼────────────────┼───────┼─────────────┤
│ y[1:300] ~ LogPrecisionMixture(z[1:300], m, s) │ average energy │ 9000  │ expectation │
╰────────────────────────────────────────────────┴────────────────┴───────┴─────────────╯

    Expectations: ExactSum, GaussHermite, UnconstrainedLegendre, QuantileLegendre

Reference: the conjugate model

RxInfer has exact variational rules for a Gaussian mixture with Gamma-distributed precisions, in the NormalMixture node. Its priors differ slightly from ours (a Gamma prior on the precision, where we use a Gaussian prior on the log-precision), so we expect close but not identical results.

@model function conjugate_mixture(y, K)
    local m
    local w
    π ~ Dirichlet(ones(K))
    for k in 1:K
        m[k] ~ NormalMeanVariance(0.0, 100.0)
        w[k] ~ GammaShapeRate(1.0, 1.0)
    end
    for i in eachindex(y)
        z[i] ~ Categorical(π)
        y[i] ~ NormalMixture(switch = z[i], m = m, p = w)
    end
end

conjugate_initialization = @initialization begin
    q(π) = Dirichlet(ones(K))
    q(m) = [NormalMeanVariance(-1.0, 1.0), NormalMeanVariance(1.0, 1.0)]
    q(w) = [GammaShapeRate(1.0, 1.0), GammaShapeRate(1.0, 1.0)]
end

result_conjugate = infer(
    model = conjugate_mixture(K = K),
    data = (y = y,),
    constraints = MeanField(),
    initialization = conjugate_initialization,
    iterations = n_iterations,
    returnvars = KeepLast(),
)
Inference results:
  Posteriors       | available for (m, π, w, z)

We report the component standard deviation at the posterior mean of the log-precision, $e^{-\mathbb{E}[s_k]/2}$, and for the conjugate model at the posterior mean of the precision, $\mathbb{E}[w_k]^{-1/2}$.

row(name, means, sds, component_sds, weights) = println(rpad(name, 22),
    "m = ", round.(means; digits = 3), "  sd(m) = ", round.(sds; digits = 3),
    "  component sd = ", round.(component_sds; digits = 3), "  π = ", round.(weights; digits = 3))

laplace_sds = exp.(-mean(q_s) ./ 2)
conjugate_means = mean.(result_conjugate.posteriors[:m])
conjugate_sds = 1 ./ sqrt.(mean.(result_conjugate.posteriors[:w]))

row("truth", true_means, [0.0, 0.0], true_sds, true_weights)
row("empirical (true z)", [sum(y[z_true .== k]) / count(z_true .== k) for k in 1:K], [0.0, 0.0], [std(y[z_true .== k]) for k in 1:K], [count(z_true .== k) / N for k in 1:K])
row("Laplace + exact z", mean(q_m), sqrt.(diag(cov(q_m))), laplace_sds, mean(q_π))
row("conjugate VMP", conjugate_means, std.(result_conjugate.posteriors[:m]), conjugate_sds, mean(result_conjugate.posteriors[:π]))
truth                 m = [-2.0, 2.0]  sd(m) = [0.0, 0.0]  component sd = [0.5, 1.0]  π = [0.4, 0.6]
empirical (true z)    m = [-2.012, 1.917]  sd(m) = [0.0, 0.0]  component sd = [0.593, 0.928]  π = [0.4, 0.6]
Laplace + exact z     m = [-1.976, 1.978]  sd(m) = [0.056, 0.063]  component sd = [0.622, 0.839]  π = [0.414, 0.586]
conjugate VMP         m = [-1.975, 1.978]  sd(m) = [0.057, 0.063]  component sd = [0.629, 0.84]  π = [0.414, 0.586]
ys = range(minimum(y) - 1, maximum(y) + 1; length = 400)
density_laplace = [sum(mean(q_π)[k] * pdf(Normal(mean(q_m)[k], laplace_sds[k]), v) for k in 1:K) for v in ys]
density_conjugate = [sum(mean(result_conjugate.posteriors[:π])[k] * pdf(Normal(conjugate_means[k], conjugate_sds[k]), v) for k in 1:K) for v in ys]

histogram(y; bins = 40, normalize = :pdf, color = :gray, alpha = 0.4, label = "data", xlabel = "y")
plot!(ys, density_laplace; color = :red, linewidth = 2, label = "Laplace + exact z")
plot!(ys, density_conjugate; color = :blue, linewidth = 2, linestyle = :dash, label = "conjugate VMP")

Plug-in vs expected messages

To see how much the expectations matter, we compare with RxInfer's built-in NodeFunctionRuleFallback. It replaces the expectation over the other variables with a plug-in estimate: it evaluates the log-density at their means. This ignores their uncertainty. With its default settings it also fails for discrete variables, because the mean of a categorical distribution over $\{1, \ldots, K\}$ is a number between $1$ and $K$, which is not a component index. To make it work, we pass it an extract function that turns a categorical distribution into its vector of probabilities.

Settings given explicitly take precedence over the keyword. We therefore keep fallback = LocalLaplace(), which still provides the Laplace projections and the initialisation, and replace only its rule fallback through options. With $N = 300$ observations, the beliefs of $m$ and $s$ are narrow and the two fallbacks agree closely. The difference grows as the data become scarcer, because the plug-in ignores the uncertainty of the other variables. In particular, it ignores $\mathrm{Var}[m_k]$ when it updates $s_k$, and so tends to underestimate the spread of the components.

plugin_extract(q) = q isa Categorical ? probs(q) : mean(q)

function component_sds(y; options = nothing)
    result = infer(
        model = laplace_mixture(K = K),
        data = (y = y,),
        constraints = mean_field,
        initialization = initial_means,
        iterations = n_iterations,
        returnvars = KeepLast(),
        fallback = LocalLaplace(),
        options = options,
    )
    return exp.(-mean(result.posteriors[:s]) ./ 2)
end

for n in (300, 40, 15)
    expected_sds = component_sds(y[1:n])
    plugin_sds = component_sds(y[1:n]; options = (rulefallback = NodeFunctionRuleFallback(plugin_extract),))
    println("N = ", lpad(n, 3), ":  component sd, expected = ", round.(expected_sds; digits = 3), ",  plug-in = ", round.(plugin_sds; digits = 3))
end
N = 300:  component sd, expected = [0.622, 0.839],  plug-in = [0.619, 0.836]
N =  40:  component sd, expected = [0.55, 0.902],  plug-in = [0.534, 0.884]
N =  15:  component sd, expected = [0.546, 1.066],  plug-in = [0.511, 1.009]

Summary

Gaussian approximations for the means, Gaussians in log-space for the positive precisions and exact beliefs for the discrete assignments recover the mixture and agree with RxInfer's hand-derived conjugate solution. No message update rule was derived by hand, and the only setting the model needed was the initial means that break the symmetry of the components.

The variational messages of the fallback are expectations: exact sums over the categorical beliefs of $z_i$ and quadrature over the Gaussian beliefs of $m$ and $s$. They account for the uncertainty that the plug-in ignores. The beliefs of the $z_i$ are normalised exactly, and the fallback computes the average energy of the likelihood, so the free energy is available.

One limitation remains. The rule fallback works from the log-density of a node, and RxInfer's mixture nodes (NormalMixture, Mixture) do not define one; they have their own rules for the conjugate case. A mixture with other kinds of components therefore needs a custom likelihood node with the assignment as an explicit variable, as in this example.


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
  [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`