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 Regression (Doctor Visits)
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. It fits a Poisson regression to a real data set, the doctor visits of 5190 adults in the 1977–1978 Australian Health Survey, with the Poisson model of Cameron and Trivedi, Regression Analysis of Count Data (1998, Table 3.3). The example comes from the documentation of NaturalGradientMessagePassingRules.jl by Mykola Lukashchuk, which writes the model with a dedicated node for a Poisson count with a log-rate. Here the rate is exp of the linear predictor, a plain Julia function, and no rule is written for it. Inference uses fallback = NaturalGradientPropagation(), natural-gradient message passing (Lukashchuk et al., 2026). We check the posterior against self-normalised importance sampling from the joint Laplace approximation.
using RxInfer, BayesBase, Distributions, LinearAlgebra, StableRNGs
using Downloads, Plots, PrettyTables, Printf
import ExpectationApproximations as EA
Data
The data come with the R package AER (data("DoctorVisits"); source: the Journal of Applied Econometrics data archive, Mullahy 1997). We download them from the Rdatasets mirror the first time the example runs, from a fixed commit of it, so that the numbers below stay the same. Each row is one adult, with the columns visits, the number of visits to a doctor in the past two weeks; gender; age in years divided by 100; income in tens of thousands of dollars; illness, the number of illnesses in the past two weeks; reduced, the days of reduced activity in the past two weeks; health, a general health questionnaire score; and the yes/no indicators private (private insurance), freepoor (free insurance due to low income), freerepat (free insurance due to age or disability), nchronic and lchronic (a chronic condition not limiting and limiting activity). The factors become indicators, and age enters with its square:
data_url = "https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/1dcc2bf5f955cc1224a3e1307256e1fe86b68dae/csv/AER/DoctorVisits.csv"
data_file = joinpath("data", "DoctorVisits.csv")
if !isfile(data_file)
mkpath(dirname(data_file))
Downloads.download(data_url, data_file)
end
lines = readlines(data_file)
header = split(first(lines), ",")
column(name) = findfirst(==(name), header)
records = [split(line, ",") for line in lines[2:end]]
number(row, name) = parse(Float64, row[column(name)])
indicator(row, name, level) = row[column(name)] == level ? 1.0 : 0.0
names = ["intercept", "female", "age", "age²", "income", "illness", "reduced", "health", "private", "freepoor", "freerepat", "nchronic", "lchronic"]
X = map(records) do row
age = number(row, "age")
[
1.0, indicator(row, "gender", "female"), age, age^2, number(row, "income"), number(row, "illness"),
number(row, "reduced"), number(row, "health"), indicator(row, "private", "yes"), indicator(row, "freepoor", "yes"),
indicator(row, "freerepat", "yes"), indicator(row, "nchronic", "yes"), indicator(row, "lchronic", "yes"),
]
end
y = [round(Int, number(row, "visits")) for row in records]
N, d = length(y), length(names)
(adults = N, coefficients = d, zero_counts = round(count(iszero, y) / N; digits = 3), largest_count = maximum(y))
(adults = 5190, coefficients = 13, zero_counts = 0.798, largest_count = 9)The model
\[\beta \sim \mathcal{N}(0, I), \qquad y_i \sim \mathrm{Poisson}\big(\exp(x_i^\top \beta)\big),\]
with $x_i$ the intercept and the twelve covariates of adult $i$, so there are 13 coefficients. The linear predictor is RxInfer's dot node, and the rate is a deterministic node of exp:
@model function doctor_visits(y, X, d)
β ~ MvNormalMeanCovariance(zeros(d), diageye(d))
for i in eachindex(y)
z[i] := dot(X[i], β)
λ[i] := exp(z[i])
y[i] ~ Poisson(λ[i])
end
end
exp has no rules. Under fallback = NaturalGradientPropagation(), inference works as follows:
- The
Poissonnode sends its own message towards the rate, $\Gamma(\lambda_i \mid y_i + 1, 1)$, and the fallback pulls it back throughexptowards $z_i$. The result is exact: $\log m(z_i) = y_i z_i - e^{z_i}$, the Poisson log-likelihood of the log-rate. - This message is not Gaussian, so $z_i$ keeps a Gaussian site for it. At each iteration the site moves by a damped step towards its target, the natural gradient of the expected log-likelihood under the marginal of $z_i$.
dotpasses the sites to $\beta$ with its exact rules, and the posterior of $\beta$ is the prior times 5190 Gaussian messages, computed exactly.
At the fixed point, each site of $z_i$ is the Gaussian of conjugate-computation variational inference. With one latent vector, $\beta$, the posterior is the variational Gaussian of the joint, the one that minimises $\mathrm{KL}(q \,\|\, p(\beta \mid y))$.
Each $z_i$ has two edges, towards dot and towards exp. The site on the second edge needs the message on the first, which needs the message from $\beta$, which needs every other site. Without an initial message, the messages through exp pass as they are in the first sweep, until the sites have formed. Inference then reaches the same posterior of $\beta$, to four digits here, but not all of its sites have settled after 30 iterations. As in the original example, we start each $z_i$ at $\log(y_i + 1)$ instead, so that every site forms in the first sweep, and the first step is a weighted regression of the log-counts. The fixed point does not depend on this choice.
We keep the posteriors of the $z_i$, which give the predicted rates below. The free energy would need the marginal of every rate $\lambda_i$ and a Gamma site for each, which costs much more than the inference itself, so we do not compute it.
seconds = @elapsed result = infer(
model = doctor_visits(X = X, d = d),
data = (y = y,),
initialization = @initialization(begin
μ(z) = NormalMeanVariance.(log.(y .+ 1), 1.0)
end),
iterations = 30,
fallback = NaturalGradientPropagation(),
returnvars = (β = KeepLast(), z = KeepLast()),
report = true,
)
q_β = result.posteriors[:β]
@printf("%.1f seconds, compilation included\n", seconds)
1759.0 seconds, compilation includedThe report shows the 5190 sites of $z$, formed from the messages of the fallback through exp, and shows that every site had settled at the last of the 30 iterations. The posterior of $\beta$ is computed by the exact rules of dot from these sites: it is the prior times 5190 Gaussian messages, as good as the sites are. The report also lists the 5190 rates $\lambda_i$ as approximated: the fallback sends the pushforward of each $z_i$ through exp towards $\lambda_i$, which the Poisson nodes do not use, and the marginals of the rates are never requested.
result.report.approximations
Approximations: 10380 of 10381 posteriors approximated (exact rules on approximated inputs: β), no warnings
Approximated posteriors
╭────────────────────────────────┬─────────┬────────┬──────────┬───────────────────────────────────╮
│ Messages from │ towards │ exact │ fallback │ expectations │
├────────────────────────────────┴─────────┴────────┴──────────┴───────────────────────────────────┤
│ z[1:5190]: natural-gradient propagation, 5190 sites, 155700 steps │
├────────────────────────────────┬─────────┬────────┬──────────┬───────────────────────────────────┤
│ z[1:5190] := dot(const, β) │ out │ 160890 │ 0 │ │
│ λ[1:5190] := exp(z[1:5190]) │ in[1] │ 0 │ 155700 │ │
├────────────────────────────────┴─────────┴────────┴──────────┴───────────────────────────────────┤
│ λ[1:5190]: VariationalForm on its messages only │
├────────────────────────────────┬─────────┬────────┬──────────┬───────────────────────────────────┤
│ y[1:5190] ~ Poisson(λ[1:5190]) │ l │ 155700 │ 0 │ │
│ λ[1:5190] := exp(z[1:5190]) │ out │ 0 │ 5190 │ NormalMeanVariance → GaussHermite │
╰────────────────────────────────┴─────────┴────────┴──────────┴───────────────────────────────────╯
Expectations: ExactSum, GaussHermite, UnconstrainedLegendre, QuantileLegendreThe reference: importance sampling
The log-posterior of $\beta$ is concave, and the joint Laplace approximation, a Gaussian at its mode with the inverse Hessian as covariance, is close to the posterior. Self-normalised importance sampling corrects the remaining error: it draws from the Laplace Gaussian and weights each draw by the ratio of the posterior to the proposal. ExpectationApproximations.jl has both, laplace and the SNIS backend, which takes a target with a log-density.
struct Posterior <: ContinuousMultivariateDistribution end
Base.length(::Posterior) = d
Distributions.logpdf(::Posterior, β::AbstractVector) = -sum(abs2, β) / 2 + sum(y[i] * dot(X[i], β) - exp(dot(X[i], β)) for i in eachindex(y))
laplace = EA.laplace(β -> logpdf(Posterior(), β), zeros(d))
proposal = MvNormal(laplace.mode, Symmetric(cov(laplace.distribution)))
draws = BayesBase.prepare_expectation(EA.SNIS(proposal, 20_000, StableRNG(1)), Posterior())
m_ref = BayesBase.expectation(draws, identity)
Σ_ref = BayesBase.expectation(draws, β -> (β - m_ref) * (β - m_ref)')
s_ref = sqrt.(diag(Σ_ref))
ess = EA.effective_sample_size(draws)
@printf("Laplace converged: %s; effective sample size %.0f of 20000\n", laplace.converged, ess)
Laplace converged: true; effective sample size 19254 of 20000The weights are nearly uniform: the effective sample size is above 15 000 of the 20 000 draws, so the Laplace Gaussian is close to the posterior, and the Monte Carlo standard error of each posterior mean is below 1% of its posterior standard deviation.
The coefficients
m, s = mean(q_β), sqrt.(diag(cov(q_β)))
gap(a) = abs.(a .- m_ref) ./ s_ref
rows = hcat(names, m, s, m_ref, s_ref, gap(m), gap(laplace.mode))
pretty_table(rows; column_labels = ["coefficient", "NGMP mean", "NGMP sd", "SNIS mean", "SNIS sd", "|NGMP - SNIS| / sd", "|Laplace - SNIS| / sd"], formatters = [fmt__printf("%.4f", 2:5), fmt__printf("%.3f", 6:7)], fit_table_in_display_horizontally = false)
┌─────────────┬───────────┬─────────┬───────────┬─────────┬────────────────────┬───────────────────────┐
│ coefficient │ NGMP mean │ NGMP sd │ SNIS mean │ SNIS sd │ |NGMP - SNIS| / sd │ |Laplace - SNIS| / sd │
├─────────────┼───────────┼─────────┼───────────┼─────────┼────────────────────┼───────────────────────┤
│ intercept │ -2.0895 │ 0.1317 │ -2.0896 │ 0.1305 │ 0.001 │ 0.024 │
│ female │ 0.1536 │ 0.0559 │ 0.1533 │ 0.0560 │ 0.005 │ 0.000 │
│ age │ 0.3178 │ 0.5667 │ 0.3199 │ 0.5656 │ 0.004 │ 0.003 │
│ age² │ -0.0664 │ 0.6097 │ -0.0668 │ 0.6124 │ 0.001 │ 0.000 │
│ income │ -0.1997 │ 0.0861 │ -0.1995 │ 0.0868 │ 0.002 │ 0.005 │
│ illness │ 0.1857 │ 0.0183 │ 0.1855 │ 0.0183 │ 0.011 │ 0.011 │
│ reduced │ 0.1268 │ 0.0050 │ 0.1267 │ 0.0050 │ 0.002 │ 0.010 │
│ health │ 0.0303 │ 0.0101 │ 0.0304 │ 0.0101 │ 0.011 │ 0.003 │
│ private │ 0.1256 │ 0.0709 │ 0.1252 │ 0.0704 │ 0.005 │ 0.002 │
│ freepoor │ -0.4470 │ 0.1758 │ -0.4448 │ 0.1763 │ 0.012 │ 0.055 │
│ freerepat │ 0.0853 │ 0.0911 │ 0.0849 │ 0.0901 │ 0.004 │ 0.005 │
│ nchronic │ 0.1158 │ 0.0662 │ 0.1155 │ 0.0662 │ 0.004 │ 0.004 │
│ lchronic │ 0.1474 │ 0.0820 │ 0.1473 │ 0.0823 │ 0.001 │ 0.008 │
└─────────────┴───────────┴─────────┴───────────┴─────────┴────────────────────┴───────────────────────┘Natural-gradient propagation agrees with importance sampling: every posterior mean is within 0.02 posterior standard deviations of the sampled one, which is about the Monte Carlo error, and every standard deviation is within 1.5%. The Laplace mean, the mode, is at most about 0.05 standard deviations away, more than three times further. With 5190 counts the posterior is nearly Gaussian, and the variational Gaussian follows the little skew that is left.
plt = scatter(m, 1:d; xerror = 2s, yticks = (1:d, names), yflip = true, color = :blue, markersize = 4, label = "posterior mean ± 2 sd", xlabel = "coefficient (log-rate scale)", legend = :topright, size = (720, 440))
vline!(plt, [0.0]; color = :black, alpha = 0.3, label = "")

Illnesses, days of reduced activity and the health score raise the visit rate, and women visit more often. Income and free insurance for the poor lower it. Each of these effects is more than two posterior standard deviations from zero. Age and its square are nearly collinear in this sample: ages range from 19 to 72, so age in hundreds lies in $[0.19, 0.72]$. The data determine only a combination of the two, so their coefficients are strongly anti-correlated, and each has a wide posterior.
lower, upper = m .- 2s, m .+ 2s
coefficient(name) = findfirst(==(name), names)
correlation = cov(q_β)[3, 4] / (s[3] * s[4])
@printf("correlation of the age and age² coefficients: %.3f\n", correlation)
correlation of the age and age² coefficients: -0.958A posterior predictive check
The plot compares the observed distribution of the counts with the predicted one. The rate of each adult is $e^{z_i}$, and its posterior mean is the mean of a log-normal, $\exp(m_i + v_i / 2)$, where $m_i$ and $v_i$ are the mean and variance of the posterior of $z_i$. These equal the mean and variance of $x_i^\top \beta$ under the posterior of $\beta$, up to the convergence of the iterations. The predicted frequency of each count is the average of the Poisson probabilities over the adults.
q_z = result.posteriors[:z]
rates = [exp(mean(q) + var(q) / 2) for q in q_z]
predicted = [sum(pdf(Poisson(λ), k) for λ in rates) / N for k in 0:maximum(y)]
observed = [count(==(k), y) / N for k in 0:maximum(y)]
tail_observed, tail_predicted = 1 - sum(observed[1:3]), 1 - sum(predicted[1:3])
pretty_table(hcat(0:4, observed[1:5], predicted[1:5]); column_labels = ["visits", "observed frequency", "predicted frequency"], formatters = [fmt__printf("%.4f", 2:3)], fit_table_in_display_horizontally = false)
@printf("three visits or more: observed %.4f, predicted %.4f\n", tail_observed, tail_predicted)
┌────────┬────────────────────┬─────────────────────┐
│ visits │ observed frequency │ predicted frequency │
├────────┼────────────────────┼─────────────────────┤
│ 0.0 │ 0.7979 │ 0.7730 │
│ 1.0 │ 0.1507 │ 0.1792 │
│ 2.0 │ 0.0335 │ 0.0324 │
│ 3.0 │ 0.0058 │ 0.0088 │
│ 4.0 │ 0.0046 │ 0.0036 │
└────────┴────────────────────┴─────────────────────┘
three visits or more: observed 0.0179, predicted 0.0154The model follows the shape of the data, but predicts too few adults with no visit, too many with one, and too few with three or more. The counts are overdispersed relative to a Poisson distribution, as Cameron and Trivedi discuss, and a negative binomial likelihood would account for this. This is a property of the Poisson model, not of the inference.
Summary
- The model is written with
expas a plain function between the linear predictor and RxInfer'sPoissonnode.fallback = NaturalGradientPropagation()fits it without a rule forexp, with one Gaussian site per log-rate and 30 iterations. - The posterior agrees with importance sampling to within 0.02 standard deviations in every mean and 1.5% in every standard deviation. The Laplace mode is further off.
References
- A. C. Cameron and P. K. Trivedi (1998). Regression Analysis of Count Data. Cambridge University Press.
- J. Mullahy (1997). Heterogeneity, excess zeros, and the structure of count data models. Journal of Applied Econometrics 12(3).
- M. Lukashchuk, K. Yemets, A. Ledbetter and İ. Şenöz (2026). Information geometry of message passing. arXiv:2608.15922.
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
[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
[f43a241f] Downloads v1.7.0
[37e2e46d] LinearAlgebra v1.13.0
[de0858da] Printf v1.11.0
Info Packages marked with ⌃ have new versions available and may be upgradable.