Plotting analytical posterior alongside sampled posterior

Hi!

I have defined a simple Bayesian linear model from which I have created a trace using pm.sample (NUTS). I have also calculated the analytical posterior. The trace can be plotted using Arviz’ plot_dist, and I have successfully added the analytical posterior to the plot by calling plot on the return value of pc.get_viz. This works fine, but the analytical posterior is not added to the legend and there is also a color conflict. Sure, this could be adjusted manually, but I also want to do other things, like calculate the Wasserstein distance between them, and then they need to be in the same format.

The issue seems to be that the trace created by PyMC is an xarray.DataTree, whose posterior group is used by plot_dist. The group contains the chain of samples, whereas the analytical posterior contains y-values that correspond to an array of x-values.

I tried creating a DataTree out of the analytical posterior as follows:

reference = xr.DataTree.from_dict({
    "posterior": xr.Dataset(
        data_vars={
            "intercept": (("chain","draw"), intercept_analytical),
            "slope": (("chain", "draw"), slope_analytical)
        }
    )
})

but it doesn’t work. I honestly wouldn’t really expect it to, but I also don’t know how to fix it.

Do I need to somehow sample from the analytical solution? Is there another way of doing this?

Thank you to whomever takes the time reading this!

cc @aloctavodia

Have you tried?
az.from_dict({“posterior”: {“intercept”: intercept_analytical,
“slope”: slope_analytical}})
Can you post a minimal reproducible example?

I tried it just now, but it complained about dimensions.

I adapted the code to this:

import arviz as az
import numpy as np
import matplotlib.pyplot as plt
import math

size = 1000
x = np.linspace(0, 2*math.pi, size)
y = np.sin(x)

# Plotting this way works as expected
plt.plot(x, y)
plt.show()

# But this gives an error
dt = az.from_dict({
    "posterior": {
        "some_var_name": y,
    }
})

# So I'm unable to do this
pc = az.plot_dist(dt)
pc.show()

I’m not saying it should work, for example, dt has no information about x. But the code shows the gist of what I want to achieve. I want to plot x and y arrays similar to this, alongside a trace created by pm.sample().

I add the real code in case the above is not enough for debugging (I tried making it as short as possible):

# Based on https://www.pymc.io/projects/docs/en/stable/learn/core_notebooks/GLM_linear.html

import arviz as az
import numpy as np
inv = np.linalg.inv
import pymc as pm
from pymc import Model, Normal
import scipy
import matplotlib.pyplot as plt

RANDOM_SEED = 8927
rng = np.random.default_rng(RANDOM_SEED)

# Generating data
size = 1000
intercept_true = 1
slope_true = 2

x = np.linspace(0, 1, size)

# Line from which we generate data
regression_line = intercept_true + slope_true * x

# Simulate data by adding noise
sigma_epsilon = 0.5
epsilon = rng.normal(0, sigma_epsilon, size)
y = regression_line + epsilon

# Prior parameters
mu_0 = np.array([[0],[0]])
Sigma_0 = np.diag(np.array([10, 10]))

# Model definition
with Model() as model:
    # Priors
    sigma = 0.5
    intercept = Normal("intercept", mu_0[0], Sigma_0[0][0])
    slope = Normal("slope", mu_0[1], Sigma_0[1][1])

    likelihood = Normal("y", mu=intercept + slope * x, sigma=sigma, observed=y)

# Sampling a trace using NUTS
with model:
    trace = pm.sample()

# Analytical posterior
# https://statproofbook.github.io/P/blrkc-post.html, eqs 1--4
X = np.matrix([np.ones(size), x]).T # size×2
beta = np.matrix([intercept_true, slope_true]).T # 2×1
Sigma = np.identity(size) * sigma_epsilon

Sigma_n = inv(
    X.T @ inv(Sigma) @ X + inv(Sigma_0)
)
mu_n = Sigma_n @ (X.T @ inv(Sigma) @ np.matrix(y).T + inv(Sigma_0) @ mu_0)

# We need a bigger range than [0, 1] as intercept and slope are 1 and 2 respectively
x1 = np.linspace(0,3,size)

analytical = scipy.stats.multivariate_normal(np.ravel(mu_n), Sigma_n)
intercept_analytical = analytical.marginal(0).pdf(x1)
slope_analytical = analytical.marginal(1).pdf(x1)

# We can plot the analytical posteriors normally using matplotlib's `plot`
plt.subplot(1,2,1)
plt.plot(x1, intercept_analytical)
plt.subplot(1,2,2)
plt.plot(x1, slope_analytical)
plt.show()

# Gives error
reference = az.from_dict({
    "posterior": {
        "intercept": intercept_analytical,
        "slope": slope_analytical
    }
})

# Things I want to do
# Plotting
pc = az.plot_dist(
    {
        "Reference": reference,
        "NUTS": trace,
    },
)
pc.add_legend("model")
pc.show()

# Measuring Wasserstein distance
d = az.wasserstein(trace, reference)

intercept_analytical and slope_analytical are like y from the previous example, arrays of values corresponding to an array of x-values. This is in contrast to trace.posterior.intercept, holding an array of samples.

Hmm, could you elaborate?

plot_posterior is deprecated in favor of plot_dist, right? What ax object are you referring to? I don’t see any function taking a density parameter, and plot_dist doesn’t accept ax.

It’s probably a bot account

1 Like

I cleaned it up

1 Like

You want something like this

dt = az.from_dict({"posterior": {"some_var_name": y}},
     sample_dims=("draw",) ) # or some other name

or

dt = az.from_dict({"posterior":{"some_var_name":np.atleast_2d(y)}})

by default arviz assumes sample_dims to be (“chain”, “draw”)

This gives me a plot, but not exactly what I’m after: here, y is treated as a series of samples, not as the actual height of the posterior for every value of x. So when plotting dt with plot_dist(), we don’t get a sinus curve. I basically want plt.plot(x, y) to give the same plot as az.plot_dist(dt).

In the case of the linear regression, intercept_analytical and slope_analytical are arrays with the true, analytical posteriors. The question is basically: do I have to sample from them in order to plot them alongside a trace created from pm.sample() (and in that case, how?), or is it possible to plot an array with the actual posterior height (not samples from one) with plot_dist()?

Does that make sense?

Thank you for your patience, I really appreciate it.

Most functions in arviz assumes you have something generated from an MCMC run. So, for example, plot_dist() expects samples and then internally approximates a density using some algorithm like a KDE, histogram, etc. So if you want to plug in some analytical computation, you are going to need samples from that analytical result, which I think you do not want. Alternatively, you can try to combine plots and do something like this, but not sure you want arviz for this.

from scipy.stats import norm
from matplotlib.lines import Line2D

x = np.linspace(-5, 5, 200)
y = norm(0, 1).pdf(x)

draws = norm(0, 1).rvs(size=(1, 1000))
dt = az.from_dict({"posterior": {"x": draws}})

_, ax = plt.subplots()

ax.plot(x, y, color="C1", label="Analytical PDF")

az.plot_dist(dt, axes=ax)

handles, labels = ax.get_legend_handles_labels()
handles.append(Line2D([], [], color="C0", label="Sampled posterior"))
ax.legend(handles=handles)

az.wasserstein also expects draws from a distribution and not density values. The support for axes in arviz_plots functions is not yet released so if you want to do something like this you will need to install it from main.

1 Like

Okay, this explains it clearly. Many thanks!

Yes! Rather than wrestling with ArviZ to do something it’s not set up to do, I would suggest just extracting the draws and the analytic posterior and plotting directly. You can do this easily in either matplotlib or plotnine. For example, here’s matplotlib where I simulated draws from normal(1, 2) and then displayed normal(0, 1) as the analytic target.

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

draws = np.random.default_rng(1234).normal(loc=1, scale=2, size=1000)
grid = np.linspace(draws.min(), draws.max(), 500)

fig, ax = plt.subplots(figsize=(6, 4), layout="constrained")
ax.hist(draws, bins=40, density=True, color="0.7", label="draws ~ normal(1, 2)")
ax.plot(grid, norm.pdf(grid, 0, 1), color="C3", lw=2, label="normal(0, 1) density")
ax.set_xlabel("θ"); ax.set_ylabel("density"); ax.legend(frameon=False)
fig.savefig("hist_vs_density.png", dpi=150)

And here’s what it looks like:

I basically just ask Claude to write all my plotting code. It’s easy enough to understand when it’s done.

Oops. I just realized your question was about a 2D example. Here’s what Claude came up with:

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

def std_normal_2d_hpd_levels(masses):
    # radius^2 ~ chi2(2) so density at mass-m HPD boundary is (1 - m) / (2 pi)
    return sorted((1 - m) / (2 * np.pi) for m in masses)

def plot_bounds(draws, target_halfwidth=4):
    lo = np.minimum(draws.min(axis=1), -target_halfwidth)
    hi = np.maximum(draws.max(axis=1), target_halfwidth)
    return lo, hi

mu = np.array([1.0, 1.0])
Sigma = np.array([[2.0, 0.5], [0.5, 1.0]])
draws = np.random.default_rng(1234).multivariate_normal(mu, Sigma, size=1000).T  # 2 x N

lo, hi = plot_bounds(draws)
x, y = np.linspace(lo[0], hi[0], 400), np.linspace(lo[1], hi[1], 400)
X, Y = np.meshgrid(x, y)
dens = norm.pdf(X) * norm.pdf(Y)

fig, axes = plt.subplots(1, 3, figsize=(13, 4), layout="constrained")
for d, (ax, grid) in enumerate(zip(axes, (x, y))):
    ax.hist(draws[d], bins=40, density=True, color="0.7", label="draws")
    ax.plot(grid, norm.pdf(grid), color="C3", lw=2, label="normal(0, 1)")
    ax.set_xlabel(f"θ{d + 1}")
axes[0].legend(frameon=False)

ax = axes[2]
ax.scatter(draws[0], draws[1], s=4, color="0.4", alpha=0.5)
ax.contour(X, Y, dens, levels=std_normal_2d_hpd_levels((0.5, 0.9, 0.99)), colors="C3")
ax.set_xlabel("θ1"); ax.set_ylabel("θ2"); ax.set_aspect("equal")
ax.set_title("draws vs. normal(0, I) 50/90/99% HPD", fontsize=10)
fig.savefig("hist_vs_density_2d.png", dpi=150)

and it produces this for a normal(0, I) analytic vs. normal([1, 1], [[2, 0.5], [0.5, 1]]) draws: