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


Stochastic Volatility

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. The Bioassay Logistic Regression example introduces the keyword fallback = LocalLaplace(). Here we apply it to a time series and then compare it with two cavity schemes, Laplace propagation and expectation propagation.

The stochastic volatility model is a standard benchmark for approximate inference in nonlinear state-space models (see Durbin and Koopman, Time Series Analysis by State Space Methods, and Martino et al., 2011, who use it to evaluate INLA). The log-variance of a series of returns follows a hidden autoregressive process:

\[\begin{aligned} x_1 &\sim \mathcal{N}\left(0, \frac{\sigma^2}{1-\varphi^2}\right),\\ x_t &\sim \mathcal{N}\left(\varphi x_{t-1}, \sigma^2\right),\\ y_t &\sim \mathcal{N}\left(0, \exp(\mu + x_t)\right). \end{aligned}\]

The transition is linear and Gaussian, so RxInfer handles it with exact rules. The observation is not: the latent variable enters the variance through an exponential, and there is no conjugate rule. We give the observation a custom node with a logpdf, and the fallback handles the rest. It turns the log-density of the node into messages and projects each product of messages on the chain onto a Gaussian by the Laplace method, at its own mode. This is a local Laplace approximation. The result is a Laplace version of the Kalman smoother, obtained without deriving any update rule.

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

Data

We simulate $T = 200$ returns with a persistent volatility process. The parameters $\mu$, $\varphi$ and $\sigma$ are known in this example; only the volatility path $x_{1:T}$ is inferred.

rng = StableRNG(1234)
T, μ, φ, σ = 200, -1.0, 0.95, 0.3

x_true = zeros(T)
x_true[1] = rand(rng, Normal(0, σ / sqrt(1 - φ^2)))
for t in 2:T
    x_true[t] = φ * x_true[t-1] + σ * randn(rng)
end
y = [exp((μ + x_true[t]) / 2) * randn(rng) for t in 1:T]

p1 = plot(y; label = "returns yₜ", color = :gray, xlabel = "t")
p2 = plot(x_true; label = "log-volatility xₜ", color = :black, xlabel = "t")
plot(p1, p2; layout = (2, 1), size = (800, 450))

The model

The observation node evaluates $\log \mathcal{N}(y_t \mid 0, e^{\mu + x_t})$. Its interfaces are the observation out, the latent x and the constant μ.

struct SVObservation{X, M} <: ContinuousUnivariateDistribution
    x::X
    μ::M
end

BayesBase.logpdf(d::SVObservation, y) = (v = d.μ + d.x; -(log2π + v + y^2 * exp(-v)) / 2)
BayesBase.insupport(::SVObservation, y) = true

@define_factor_node(node = SVObservation, type = Stochastic, interfaces = [:out, :x, :μ])
@model function stochastic_volatility(y, μ, φ, σ)
    x[1] ~ NormalMeanVariance(0.0, σ^2 / (1 - φ^2))
    y[1] ~ SVObservation(x[1], μ)
    for t in 2:length(y)
        x[t] ~ NormalMeanVariance(φ * x[t-1], σ^2)
        y[t] ~ SVObservation(x[t], μ)
    end
end

Under belief propagation, a message that leaves $x_t$ along the chain is the product of the message from the other side of the chain and the observation message. That product is not Gaussian. The fallback projects it, and every marginal, onto a Gaussian, so the transition nodes always receive Gaussian messages, for which exact rules exist.

result = infer(
    model = stochastic_volatility(μ = μ, φ = φ, σ = σ),
    data = (y = y,),
    fallback = LocalLaplace(),
    free_energy = true,
    report = true,
)

q_x = result.posteriors[:x]
m_mp, s_mp = mean.(q_x), std.(q_x)
([-0.7984963759118981, -0.8014046592109351, -0.7627102739886604, -0.9445767616095926, -1.0102714169762705, -1.1075740743276823, -1.1197896988877232, -1.1552749368830761, -1.1394473318553329, -1.0849589271368436  …  -0.34356918480453524, -0.2189451575980114, -0.06931228429740784, 0.231152307466788, 0.2241497507450097, 0.2290273305807287, 0.27866873112761287, 0.3465094784185114, 0.2968127120489616, 0.3284812049558919], [0.549835563173767, 0.4909692799974011, 0.41419241583848526, 0.4994101558963673, 0.5392532512987279, 0.5438360896740514, 0.5545737435595485, 0.5574592676062875, 0.5406736184749857, 0.5128662722991598  …  0.5417348238556107, 0.5242008829722106, 0.49737904432450386, 0.402342449296878, 0.4326506251641707, 0.45246016482195256, 0.44744451226214643, 0.4186690390676089, 0.46569607596889295, 0.5521443160067527])

What was approximated

report = true recorded what the fallback did. The posteriors of the volatility path are grouped into three rows:

  • the first, $x_1$, whose prior is the stationary distribution;
  • the last, $x_T$, which has no successor;
  • all the others.

For each of them, the messages of the transitions come from their exact rules and the message of the observation from the rule fallback. The expectations of the observation are exact, because its other inputs are the data and the constant $\mu$, so under belief propagation its message is exact.

result.report.approximations
  Approximations: 200 of 201 posteriors approximated (exact rules on approximated inputs: · (anonymous)), no warnings
                                Approximated posteriors
╭──────────────────────────────────────────┬─────────┬───────┬──────────┬──────────────╮
│ Messages from                            │ towards │ exact │ fallback │ expectations │
├──────────────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ x[1]: Laplace, converged in 4 iterations, log Z = -0.1372                            │
├──────────────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ x[1] ~ NormalMeanVariance(0.0, 0.9231)   │ out     │ 1     │ 0        │              │
│ · := *(0.95, x[1])                       │ in      │ 1     │ 0        │              │
│ y[1] ~ SVObservation(x[1], -1.0)         │ x       │ 0     │ 1        │ exact        │
├──────────────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ x[2:199]: Laplace, 198 of 198 converged, 3 to 5 iterations                           │
├──────────────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ x[2:199] ~ NormalMeanVariance(·, 0.09)   │ out     │ 198   │ 0        │              │
│ · := *(0.95, x[2:199])                   │ in      │ 198   │ 0        │              │
│ y[2:199] ~ SVObservation(x[2:199], -1.0) │ x       │ 0     │ 198      │ exact        │
├──────────────────────────────────────────┴─────────┴───────┴──────────┴──────────────┤
│ x[200]: Laplace, converged in 4 iterations, log Z = -0.7139                          │
├──────────────────────────────────────────┬─────────┬───────┬──────────┬──────────────┤
│ x[200] ~ NormalMeanVariance(·, 0.09)     │ out     │ 1     │ 0        │              │
│ y[200] ~ SVObservation(x[200], -1.0)     │ x       │ 0     │ 1        │ exact        │
╰──────────────────────────────────────────┴─────────┴───────┴──────────┴──────────────╯

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

    Expectations: ExactSum, GaussHermite, UnconstrainedLegendre, QuantileLegendre

Sanity check: a linear-Gaussian observation

If the observation is Gaussian, $y_t \sim \mathcal{N}(x_t, r)$, every product is Gaussian and the Laplace approximation is exact. The same method should then reproduce the Kalman smoother that RxInfer computes with its exact rules, together with its free energy, which here is the exact $-\log p(y)$. We write the Gaussian observation as a custom node, so that it goes through the fallback like the stochastic volatility observation.

struct GaussianObservation{X, R} <: ContinuousUnivariateDistribution
    x::X
    r::R
end

BayesBase.logpdf(d::GaussianObservation, y) = -(log2π + log(d.r) + (y - d.x)^2 / d.r) / 2
BayesBase.insupport(::GaussianObservation, y) = true

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

@model function linear_gaussian(y, r, φ, σ, observation)
    x[1] ~ NormalMeanVariance(0.0, σ^2 / (1 - φ^2))
    y[1] ~ observation(x[1], r)
    for t in 2:length(y)
        x[t] ~ NormalMeanVariance(φ * x[t-1], σ^2)
        y[t] ~ observation(x[t], r)
    end
end

y_linear = x_true .+ sqrt(0.5) .* randn(rng, T)

result_fallback = infer(
    model = linear_gaussian(r = 0.5, φ = φ, σ = σ, observation = GaussianObservation),
    data = (y = y_linear,),
    fallback = LocalLaplace(),
    free_energy = true,
)
result_exact = infer(model = linear_gaussian(r = 0.5, φ = φ, σ = σ, observation = NormalMeanVariance), data = (y = y_linear,), free_energy = true)

println("max |mean difference|     = ", maximum(abs, mean.(result_fallback.posteriors[:x]) - mean.(result_exact.posteriors[:x])))
println("max |variance difference| = ", maximum(abs, var.(result_fallback.posteriors[:x]) - var.(result_exact.posteriors[:x])))
println("free energy: fallback = ", only(result_fallback.free_energy), ",  exact = ", only(result_exact.free_energy))
max |mean difference|     = 4.440892098500626e-16
max |variance difference| = 8.326672684688674e-17
free energy: fallback = 248.78081853574156,  exact = 248.78081853574162

References for the nonlinear model

We compare the message passing result with two references:

  1. The global Laplace approximation: the Laplace approximation of the joint posterior $p(x_{1:T} \mid y_{1:T})$, computed directly by Newton's method on the full $T$-dimensional log-density with laplace from ExpectationApproximations.jl. Its marginals are what an INLA-style Gaussian approximation reports. LocalLaplace() projects each product of messages separately, so the two can differ.
  2. Elliptical slice sampling (Murray, Adams and MacKay, 2010), a simple MCMC method that applies when the prior is Gaussian, as it is here. A long run gives the "exact" posterior marginals.
function logprior(x)
    s = logpdf(Normal(0, σ / sqrt(1 - φ^2)), x[1])
    for t in 2:T
        s += logpdf(Normal(φ * x[t-1], σ), x[t])
    end
    return s
end

loglikelihood(x) = sum(logpdf(SVObservation(x[t], μ), y[t]) for t in 1:T)

q_global = EA.laplace(x -> logprior(x) + loglikelihood(x), zeros(T)).distribution
m_global, s_global = mean(q_global), sqrt.(diag(cov(q_global)))
([-0.6777383638200141, -0.6725867724159073, -0.6261263448447068, -0.7672699056058516, -0.8963135759211895, -0.9957143623609719, -1.0511321520214718, -1.0897279926384744, -1.0840741467645474, -1.038679321559837  …  -0.2398463436213893, -0.10568811026754954, 0.06563166627859283, 0.28161777887713574, 0.28352259755552434, 0.2995293849933844, 0.3580941686033491, 0.4295960508476985, 0.39646896787861696, 0.33969560688550376], [0.5825034119471812, 0.5294475458033964, 0.4646911047199608, 0.4893537429114193, 0.5125396255247294, 0.528276587672646, 0.5304993928992799, 0.5339484773741374, 0.5241153108528847, 0.5025062969268822  …  0.5196325464548772, 0.49881759527057606, 0.4660868030483018, 0.41336446806000027, 0.441604450412543, 0.4599955705245213, 0.4589137322824751, 0.4522040216189891, 0.49312335960014536, 0.5524958202272967])
function prior_draw(rng)
    x = zeros(T)
    x[1] = σ / sqrt(1 - φ^2) * randn(rng)
    for t in 2:T
        x[t] = φ * x[t-1] + σ * randn(rng)
    end
    return x
end

function elliptical_slice_sampling(rng, x0; nsamples, burnin)
    x, ℓ = copy(x0), loglikelihood(x0)
    s1, s2 = zeros(T), zeros(T)
    for iteration in 1:(nsamples + burnin)
        ν = prior_draw(rng)
        threshold = ℓ + log(rand(rng))
        θ = 2π * rand(rng)
        lo, hi = θ - 2π, θ
        while true
            proposal = x .* cos(θ) .+ ν .* sin(θ)
            ℓproposal = loglikelihood(proposal)
            if ℓproposal > threshold
                x, ℓ = proposal, ℓproposal
                break
            end
            θ < 0 ? (lo = θ) : (hi = θ)
            θ = lo + (hi - lo) * rand(rng)
        end
        if iteration > burnin
            s1 .+= x
            s2 .+= x .^ 2
        end
    end
    m = s1 ./ nsamples
    return m, sqrt.(s2 ./ nsamples .- m .^ 2)
end

m_ess, s_ess = elliptical_slice_sampling(StableRNG(7), m_global; nsamples = 50_000, burnin = 5_000)
([-0.6014859926153528, -0.5857282716740281, -0.5439995694867062, -0.6700777760866219, -0.7898895479305479, -0.8899156050364339, -0.9349265514571699, -0.9770398723487574, -0.9785376677737012, -0.9443566235576261  …  -0.17004590424401067, -0.005238936770917057, 0.1541932865001329, 0.368670169708874, 0.37100946968082427, 0.3843639858464803, 0.45848503931530665, 0.5513449220057411, 0.5239347259556597, 0.448454926719571], [0.5875986318863196, 0.535273450070301, 0.47626898581691235, 0.49120425636352805, 0.5247819281880398, 0.5547023958517426, 0.5357844832583767, 0.5388695340204197, 0.5281799022765964, 0.5183245844160954  …  0.5177746151326672, 0.4822394688267211, 0.4680201026035678, 0.4304816615030795, 0.44750586598013203, 0.4783906713386294, 0.4706126392738671, 0.4745239261277753, 0.5000365709329375, 0.5584366494310808])

Results

ts = 1:T
plt = plot(ts, m_ess; ribbon = 2s_ess, fillalpha = 0.25, color = :gray, label = "slice sampler (±2 sd)", xlabel = "t", ylabel = "xₜ", size = (900, 500), legend = :outerbottom, legendcolumns = 2)
plot!(plt, ts, m_global; color = :blue, label = "global Laplace")
plot!(plt, ts, m_mp; ribbon = 2s_mp, fillalpha = 0.15, color = :red, linestyle = :dash, label = "LocalLaplace() (±2 sd)")
plot!(plt, ts, x_true; color = :black, linewidth = 1, label = "true xₜ")

rmse(a, b) = sqrt(sum(abs2, a - b) / length(a))

println(rpad("", 26), rpad("RMSE of means", 16), "RMSE of sds")
println(rpad("LocalLaplace() vs ESS", 26), rpad(round(rmse(m_mp, m_ess); digits = 3), 16), round(rmse(s_mp, s_ess); digits = 3))
println(rpad("global Laplace vs ESS", 26), rpad(round(rmse(m_global, m_ess); digits = 3), 16), round(rmse(s_global, s_ess); digits = 3))
println(rpad("LocalLaplace() vs global", 26), rpad(round(rmse(m_mp, m_global); digits = 3), 16), round(rmse(s_mp, s_global); digits = 3))
println()
println("average posterior sd: LocalLaplace() = ", round(sum(s_mp) / T; digits = 3), ", global Laplace = ", round(sum(s_global) / T; digits = 3), ", ESS = ", round(sum(s_ess) / T; digits = 3))
                          RMSE of means   RMSE of sds
LocalLaplace() vs ESS     0.177           0.019
global Laplace vs ESS     0.1             0.011
LocalLaplace() vs global  0.085           0.016

average posterior sd: LocalLaplace() = 0.475, global Laplace = 0.474, ESS = 0.481

Laplace propagation and expectation propagation

LocalLaplace() projects each product of messages separately, at the mode of a local product, and computes it once. Laplace propagation (Eskin, Smola and Vishwanathan, 2003) instead keeps one Gaussian site per edge of each $x_t$. The beliefs of $x_t$ 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 of the observation, a log-density, is multiplied by its cavity, the messages of the two transitions, and projected, and then the cavity is divided out again. The result is the site of the observation. The sites depend on each other through the chain, and the iterations update them until they reach a fixed point. This fixed point is the mode of the whole posterior with the curvature there, which is the global Laplace approximation. fallback = LaplacePropagation() runs this scheme. fallback = ExpectationPropagation() runs the same scheme but computes each site from the moments of its tilted belief, the message times its cavity, instead of its mode.

propagate(fallback) = infer(
    model = stochastic_volatility(μ = μ, φ = φ, σ = σ), data = (y = y,), iterations = 10,
    fallback = fallback, free_energy = true, returnvars = (x = KeepLast(),),
)

lp = propagate(LaplacePropagation())
ep = propagate(ExpectationPropagation())
m_lp, s_lp = mean.(lp.posteriors[:x]), std.(lp.posteriors[:x])
m_ep, s_ep = mean.(ep.posteriors[:x]), std.(ep.posteriors[:x])

println("Laplace propagation vs global Laplace: max |mean difference| = ", maximum(abs, m_lp - m_global), ", max |sd difference| = ", maximum(abs, s_lp - s_global))
Laplace propagation vs global Laplace: max |mean difference| = 2.6756814541784024e-9, max |sd difference| = 2.1742274647351678e-10
plt = plot(ts, m_ess; ribbon = 2s_ess, fillalpha = 0.25, color = :gray, label = "slice sampler (±2 sd)", xlabel = "t", ylabel = "xₜ", size = (900, 500), legend = :outerbottom, legendcolumns = 2)
plot!(plt, ts, m_lp; color = :blue, label = "LaplacePropagation() = global Laplace")
plot!(plt, ts, m_ep; ribbon = 2s_ep, fillalpha = 0.15, color = :red, linestyle = :dash, label = "ExpectationPropagation() (±2 sd)")
plot!(plt, ts, x_true; color = :black, linewidth = 1, label = "true xₜ")

println(rpad("", 34), rpad("RMSE of means", 16), "RMSE of sds")
for (name, m, s) in (("LocalLaplace()", m_mp, s_mp), ("LaplacePropagation()", m_lp, s_lp), ("ExpectationPropagation()", m_ep, s_ep))
    println(rpad(name * " vs ESS", 34), rpad(round(rmse(m, m_ess); digits = 3), 16), round(rmse(s, s_ess); digits = 3))
end
                                  RMSE of means   RMSE of sds
LocalLaplace() vs ESS             0.177           0.019
LaplacePropagation() vs ESS       0.1             0.011
ExpectationPropagation() vs ESS   0.016           0.01

Summary

With one keyword, RxInfer runs a nonlinear state-space smoother, and the report says which messages were exact and which were approximated. On a linear-Gaussian model the same method reproduces RxInfer's exact Kalman smoother and its free energy up to rounding error, so nothing is lost where exact inference is possible.

The posterior standard deviations of LocalLaplace() are close to those of the sampler. Its means follow the sampler less closely than the global Laplace approximation does. Each message is projected onto a Gaussian separately, at the mode of a local product, so errors made early in the forward pass are not corrected later. Both Laplace approximations are also slightly below the mean of the sampler throughout: the posterior of the log-volatility is skewed, and a Laplace approximation reports its mode, which differs from its mean.

LaplacePropagation() corrects the early messages with the later observations, because its sites iterate to the global Laplace approximation. ExpectationPropagation() matches the moments of each tilted belief instead of its mode, and its means follow the sampler more closely than either Laplace approximation, including the effect of the skew.

The parameters $\mu$, $\varphi$ and $\sigma$ are fixed here. Learning them would put a constrained variable, $\sigma$, in every transition; the Constrained Variables example covers such variables.


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