Model Diagnostic

The BF class can compute model diagnostics for a given model.

Lets consider the following model for a linear regression:

Y_i \sim \text{Normal}(\alpha + \beta X_i, \sigma)

\alpha \sim \text{Normal}(0, 1)

\beta \sim \text{Normal}(0, 1)

\sigma \sim \text{Uniform}(0, 50)

Code
from BayesForge import bf
import jax.numpy as jnp

# setup platform------------------------------------------------
m = bf(platform="cpu")

# import data ------------------------------------------------
data_path = m.load.howell1(only_path=True)
m.data(data_path, sep=";")
m.df = m.df[m.df.age > 18]
m.scale(data=["weight"])


# define model ------------------------------------------------
def model(weight, height):
    a = m.dist.normal(178, 20, name="a")
    b = m.dist.log_normal(0, 1, name="b")
    s = m.dist.uniform(0, 50, name="s")
    m.dist.normal(a + b * weight, s, obs=height, shape=(weight.shape[0],))


# Run sampler ------------------------------------------------
m.fit(model, num_samples=500, num_chains=4)
m.summary()
An NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is not installed. Falling back to cpu.
bf v 0.0.60 package loaded
jax.local_device_count(cpu) = 32
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
a 154.65 0.28 154.20 155.07 1561.15 1439.28 1.01 0.01 0.01
b 5.80 0.28 5.34 6.25 2220.67 1468.34 1.00 0.01 0.01
s 5.15 0.19 4.86 5.46 2053.77 1589.55 1.00 0.00 0.00
library(BayesForge)

# setup platform------------------------------------------------
m <- importBF(platform = "cpu")

# import data ------------------------------------------------
data_path <- m$load$howell1(only_path = TRUE)
m$data(data_path, sep = ";")
m$df <- m$df[m$df$age > 18, ]
m$scale(list("weight"))
m$data_to_model(list("weight", "height"))

# define model ------------------------------------------------
model <- function(weight, height) {
    a <- bf.dist.normal(178, 20, name = "a")
    b <- bf.dist.log_normal(0, 1, name = "b")
    s <- bf.dist.uniform(0, 50, name = "s")
    bf.dist.normal(a + b * weight, s, obs = height, name = "height")
}

# Run sampler ------------------------------------------------
m$fit(model, num_samples = 500, num_chains = 4)
m$summary()
using PyBayesForge

# setup platform------------------------------------------------
m = importBF(platform = "cpu")

# import data ------------------------------------------------
data_path = m.load.howell1(only_path = true)
m.data(data_path, sep = ";")
m.df = m.df[m.df.age > 18]
m.scale(["weight"])

# define model ------------------------------------------------
@BF function model(weight, height)
    a = m.dist.normal(178, 20, name = "a")
    b = m.dist.log_normal(0, 1, name = "b")
    s = m.dist.uniform(0, 50, name = "s")
    m.dist.normal(a + b * weight, s, obs = height)
end

# Run sampler ------------------------------------------------
m.fit(model, num_samples = 500, num_chains = 4)
m.summary()

For additional documentation check the diagnostics API reference

Every plot takes x_label= and y_label= to replace the axis titles (title= for the plot title). A string sets the title of every panel; a list sets one per panel, in order (None keeps a panel’s own title), for example m.diag.posterior(x_label=["intercept", "slope", "sigma"]).

Predictions from model based on specific data value

By default (posterior=True, samples=None), m.sample(...) evaluates the predictive distribution across all posterior MCMC draws (here 500 \times 4 = 2000 draws). To obtain a single predicted value instead of the full posterior predictive vector, you can draw a single sample (samples=1), take the posterior predictive mean, or evaluate at fixed parameter values (posterior=...):

Code
m.sample()  # Predictions from model based on data in data_on_model
pred = m.sample(data=dict(weight=jnp.array([0.4])), remove_obs=False)  # Full posterior predictive (2000 draws)

# 1. Single random predictive draw from the posterior
m.sample(data=dict(weight=jnp.array([0.4])), remove_obs=False, samples=1)

# 2. Posterior predictive mean across all 2000 draws
jnp.mean(pred["height"])

# 3. Single draw at fixed parameter values
m.sample(
    data=dict(weight=jnp.array([0.4])),
    posterior=dict(a=154.6, b=5.8, s=5.1),
    remove_obs=False,
)
{'height': Array([[149.99351347]], dtype=float64)}
m$sample() # Predictions from model based on data in data_on_model
pred <- m$sample(data = list(weight = jnp$array(c(0.4))), remove_obs = FALSE) # Full posterior predictive (2000 draws)

# 1. Single random predictive draw from the posterior
m$sample(data = list(weight = jnp$array(c(0.4))), remove_obs = FALSE, samples = 1L)

# 2. Posterior predictive mean across all 2000 draws
jnp$mean(pred$height)

# 3. Single draw at fixed parameter values
m$sample(
    data = list(weight = jnp$array(c(0.4))),
    posterior = list(a = 154.6, b = 5.8, s = 5.1),
    remove_obs = FALSE
)
m.sample() # Predictions from model based on data in data_on_model
pred = m.sample(data = pydict(weight = jnp.array([0.4])), remove_obs = false) # Full posterior predictive (2000 draws)

# 1. Single random predictive draw from the posterior
m.sample(data = pydict(weight = jnp.array([0.4])), remove_obs = false, samples = 1)

# 2. Posterior predictive mean across all 2000 draws
jnp.mean(pred["height"])

# 3. Single draw at fixed parameter values
m.sample(
    data = pydict(weight = jnp.array([0.4])),
    posterior = pydict(a = 154.6, b = 5.8, s = 5.1),
    remove_obs = false
)

Forest plot of estimated values

Code
m.diag.forest()
m$diag$forest()
@pyplot m.diag.forest()

See m.diag.forest for further information regarding the list of arguments.

Density plots of the posterior distribution

Code
m.diag.density()
m$diag$density()
@pyplot m.diag.density()

See m.diag.density for further information regarding the list of arguments.

Posterior distribution plots

Code
m.diag.posterior()
m$diag$posterior()
@pyplot m.diag.posterior()

See m.diag.posterior for further information regarding the list of arguments.

Trace plots for MCMC chains

Code
m.diag.plot_trace()
m$diag$plot_trace()
@pyplot m.diag.plot_trace()

See m.diag.plot_trace for further information regarding the list of arguments.

Pairwise plots of the posterior distribution

Code
m.diag.pair()
m$diag$pair()
@pyplot m.diag.pair()

See m.diag.pair for further information regarding the list of arguments.

Plot autocorrelation of MCMC chains

Code
m.diag.autocor()
m$diag$autocor()
@pyplot m.diag.autocor()

See m.diag.autocor for further information regarding the list of arguments.

Create rank plots for MCMC chains

Code
m.diag.rank()
m$diag$rank()
@pyplot m.diag.rank()

See m.diag.rank for further information regarding the list of arguments.

Evolution of effective sample size across iterations

Code
m.diag.plot_ess()
m$diag$plot_ess()
@pyplot m.diag.plot_ess()

See m.diag.plot_ess for further information regarding the list of arguments.

Posterior predictive checks

All posterior predictive checks compare the observed outcome with predictions: datasets of the outcome simulated by the fitted model, one per posterior draw (m.diag.get_yrep()). Both are taken from the fitted model automatically, and the plots are labelled with the name of the observed site (here height, from obs=height). With several observed sites, each function returns one figure per site; pass site= to choose one. The idea is always the same: if the model is good, the data it simulates should look like the real data. For count or categorical outcomes, m.diag.ppc_bars() and m.diag.ppc_rootogram() instead compare observed counts with predicted counts per category.

Which check for which model. The model pages show the checks that matter for each kind of model:

Density overlay

Overlays the density of the observed data (black) with the densities of n predicted datasets (blue). The black curve should look like one more blue curve; a different shape (two modes, skewness, mass below 0 for a positive outcome) points to a missing group or a wrong likelihood.

Code
m.diag.ppc_density()
/home/sosa/work/BF/BayesForge/Diagnostic/ppc.py:82: RuntimeWarning: ⚠️This function is still in development. Use it with caution. ⚠️
  warn_dev("ppc")
m$diag$ppc_density()
@pyplot m.diag.ppc_density()

See m.diag.ppc_density for further information regarding the list of arguments.

Test statistic

Each predicted dataset is summarised by one number T (the curve is the distribution of T over the predictions) and T of the observed data is marked by the vertical line. The title gives the Bayesian p-value P(T(predicted) ≥ T(observed)) and its two-sided version: around 0.5 is fine, a two-sided value below 0.05 means the model does not reproduce this aspect of the data.

Choose the statistic with stat=: "mean" (default), "median", "sd", "var", "min", "max", "q25", "q75", "skew", "n_zero", "n_pos", or (Python) any function of a 1D array, for example stat=lambda v: np.percentile(v, 90). The mean is almost always reproduced because the model has a parameter for it; statistics the model does not fit directly ("sd" for over-dispersion, "max"/"min" for the tails, "skew", "n_zero" for counts) are more informative.

Code
m.diag.ppc_stat(stat="sd")
m$diag$ppc_stat(stat = "sd")
@pyplot m.diag.ppc_stat(stat = "sd")

See m.diag.ppc_stat for further information regarding the list of arguments.

Sensitivity

Prior sensitivity

Overlays the posteriors from models fitted with different priors to assess how much the conclusions change when the priors vary.

Code
# Refit the same model with a tighter prior on b
posteriors_weak = m.posteriors

def model_strong(weight, height):
    a = m.dist.normal(178, 20, name="a")
    b = m.dist.log_normal(0, 0.1, name="b")
    s = m.dist.uniform(0, 50, name="s")
    m.dist.normal(a + b * weight, s, obs=height, shape=(weight.shape[0],))

m.fit(model_strong, num_samples=500, num_chains=4)

m.diag.prior_sensitivity([posteriors_weak, m.posteriors],
                         labels=["weak prior", "strong prior"])
# Refit the same model with a tighter prior on b
posteriors_weak <- m$posteriors

model_strong <- function(weight, height) {
    a <- bf.dist.normal(178, 20, name = "a")
    b <- bf.dist.log_normal(0, 0.1, name = "b")
    s <- bf.dist.uniform(0, 50, name = "s")
    bf.dist.normal(a + b * weight, s, obs = height)
}

m$fit(model_strong, num_samples = 500, num_chains = 4)

m$diag$prior_sensitivity(list(posteriors_weak, m$posteriors),
                         labels = list("weak prior", "strong prior"))
# Refit the same model with a tighter prior on b
posteriors_weak = m.posteriors

@BF function model_strong(weight, height)
    a = m.dist.normal(178, 20, name = "a")
    b = m.dist.log_normal(0, 0.1, name = "b")
    s = m.dist.uniform(0, 50, name = "s")
    m.dist.normal(a + b * weight, s, obs = height)
end

m.fit(model_strong, num_samples = 500, num_chains = 4)

@pyplot m.diag.prior_sensitivity([posteriors_weak, m.posteriors],
                                 labels = ["weak prior", "strong prior"])

Declaring the prior variations (parallel)

Instead of refitting by hand, declare which priors vary. The model takes the bf instance m first, then the data, then the prior hyper-parameters (their defaults are the baseline). prior_sensitivity fits the baseline plus one variation at a time (each prior moved alone, the others at baseline) in parallel, through run_simulations, and plots the results.

Code
def model_decl(m, weight, height, a_sd=20.0, b_sd=1.0):
    a = m.dist.normal(178, a_sd, name="a")
    b = m.dist.log_normal(0, b_sd, name="b")
    s = m.dist.uniform(0, 50, name="s")
    m.dist.normal(a + b * weight, s, obs=height, shape=(weight.shape[0],))

fig, table = m.diag.prior_sensitivity(
    model_decl,
    priors={"b_sd": [0.1, 0.5, 2.0], "a_sd": [5, 50]},   # 1 + 5 = 6 fits
    obs=dict(weight=m.df.weight.to_numpy(dtype="float32"),
             height=m.df.height.to_numpy(dtype="float32")),
    fit_kwargs=dict(num_samples=500, num_chains=1),
    progress=False,
    return_results=True)       # table: mean, sd, HDI and shift_sd vs baseline
fig
An NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is not installed. Falling back to cpu.
An NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is not installed. Falling back to cpu.
An NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is not installed. Falling back to cpu.
An NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is not installed. Falling back to cpu.
An NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is not installed. Falling back to cpu.
An NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is not installed. Falling back to cpu.
model <- function(m, weight, height, a_sd = 20, b_sd = 1) {
    a <- m$dist$normal(178, a_sd, name = "a")
    b <- m$dist$log_normal(0, b_sd, name = "b")
    s <- m$dist$uniform(0, 50, name = "s")
    m$dist$normal(a + b * weight, s, obs = height, name = "height")
}

out <- m$diag$prior_sensitivity(
    model,
    priors = list(b_sd = list(0.1, 0.5, 2.0), a_sd = list(5, 50)),   # 1 + 5 = 6 fits
    obs = list(weight = weight, height = height),
    fit_kwargs = list(num_samples = 500L, num_chains = 1L),
    return_results = TRUE)     # out[[1]]: figure, out[[2]]: table
@sim function model(m, weight, height; a_sd = 20.0, b_sd = 1.0)
    a = m.dist.normal(178, a_sd, name = "a")
    b = m.dist.log_normal(0, b_sd, name = "b")
    s = m.dist.uniform(0, 50, name = "s")
    m.dist.normal(a + b * weight, s, obs = height, name = "height")
end

fig, table = m.diag.prior_sensitivity(
    model,
    priors = Dict("b_sd" => [0.1, 0.5, 2.0], "a_sd" => [5, 50]),   # 1 + 5 = 6 fits
    obs = Dict("weight" => weight, "height" => height),
    fit_kwargs = Dict("num_samples" => 500, "num_chains" => 1),
    return_results = true)

The default plot (plot="by_prior") has one row per varied prior and one column per parameter: each cell shows the baseline posterior (grey, dashed) and the posteriors when that prior alone is varied. plot="shift" gives a dot plot of the posterior-mean shift (in baseline sd) per variation, and plot="overlay" puts every fit in one panel per parameter.

mode="grid" crosses all the lists instead (captures interactions, but the number of fits is the product of the list lengths); joint={"all tighter": {"a_sd": 5, "b_sd": 0.1}} adds scenarios where several priors move together. shift_sd is the change of the posterior mean from the baseline, in baseline posterior sd.

See m.diag.prior_sensitivity for further information regarding the list of arguments.

Pareto-smoothed

Code
m.diag.loo()
Computed from 2000 posterior samples and 346 observations log-likelihood matrix.

         Estimate       SE
elpd_loo -1140.68    11.95
p_loo        2.40        -
m$diag$loo()
m.diag.loo()

See m.diag.loo for further information regarding the list of arguments.

Widely applicable information criterion

Code
m.diag.WAIC()
elpd_waic       -1140.67425
se                11.935867
p_waic             2.393211
n_samples              2000
n_data_points           346
scale                   log
dtype: object
m$diag$WAIC()
m.diag.WAIC()

See m.diag.WAIC for further information regarding the list of arguments.

Experimental features

The functions below are still in development: they run, but their output and arguments may change. Use them with caution.

HMC diagnostics: divergences and energy

Warning

⚠️This function is still in development. Use it with caution. ⚠️

Check this plot first: if the sampler failed, the other diagnostics are not meaningful.

  • Top row, one panel per chain: the distribution of the energy E around its mean (blue, marginal energy) and of its change between two successive iterations, ΔE (orange, energy transition). When the two histograms have about the same width, the sampler can cross the whole posterior from one iteration to the next. When ΔE is much narrower than E, it explores the tails badly (typical of a hierarchical “funnel”). The panel title gives E-BFMI = Σ ΔE² / Σ (E − Ē)²; values below 0.3 are flagged with ⚠.
  • Bottom row: the number of divergent transitions per chain (ideal: 0). A divergence means that the integrator failed in a region of strong curvature, which is then under-explored. With a few divergences, raise target_accept (0.95–0.99); with many, reparametrise (for example a non-centred random effect).
Code
m.diag.divergence_energy()
m$diag$divergence_energy()
@pyplot m.diag.divergence_energy()

See m.diag.divergence_energy for further information regarding the list of arguments.

Histogram small multiples

Warning

⚠️This function is still in development. Use it with caution. ⚠️

The histogram of the observed data (first panel, black) next to the histograms of n predicted datasets (“Prediction 1”, “Prediction 2”, …). The observed histogram should not stand out among the predictions; look at the number of modes, the skewness, the range and the number of zeros.

Code
m.diag.ppc_hist()
/home/sosa/work/BF/BayesForge/Diagnostic/ppc.py:82: RuntimeWarning: ⚠️This function is still in development. Use it with caution. ⚠️
  warn_dev("ppc")
m$diag$ppc_hist()
@pyplot m.diag.ppc_hist()

See m.diag.ppc_hist for further information regarding the list of arguments.

Boxplots

Warning

⚠️This function is still in development. Use it with caution. ⚠️

The box of the observed data (left, black) next to the boxes of n predicted datasets (“pred 1”, “pred 2”, …): median, quartiles, whiskers and extreme points. The observed box should look like the others; an observed box that is systematically higher, wider or narrower, or extreme values that the predictions never produce (tails too light: try a Student-t likelihood), signal misfit.

Code
m.diag.ppc_boxplot()
m$diag$ppc_boxplot()
@pyplot m.diag.ppc_boxplot()

See m.diag.ppc_boxplot for further information regarding the list of arguments.

Predictive intervals

Warning

⚠️This function is still in development. Use it with caution. ⚠️

One vertical bar per observation: the thin line is the 90% predictive interval (prob_outer), the thick line the 50% interval (prob), the white point the median prediction and the black point the observed value. About 50% of the black points should fall on the thick bars and 90% on the thin ones. Many points outside mean the model is over-confident; all points close to the median mean it is too cautious. Pass x= (a predictor) to see where the model misses; a discrete x (a few distinct levels, e.g. a normalized 1/2/3 design) gets one tick per level instead of plotly’s default ticks, which would fall between the bars. Pass group= to get one panel per level of a second variable.

Code
m.diag.ppc_intervals()
m$diag$ppc_intervals()
@pyplot m.diag.ppc_intervals()

See m.diag.ppc_intervals for further information regarding the list of arguments.

Predictive ribbon

Warning

⚠️This function is still in development. Use it with caution. ⚠️

The same intervals drawn as continuous ribbons (light: 90%, dark: 50%; line: median prediction) with the observed values as points. Easier to read than the bars when x is a continuous variable, here the predictor weight: the ribbon should follow the cloud of points over the whole range of x, without a curvature it misses.

Code
m.diag.ppc_ribbon(x=m.df.weight)
m$diag$ppc_ribbon(x = m$df$weight)
@pyplot m.diag.ppc_ribbon(x = m.df.weight)

See m.diag.ppc_ribbon for further information regarding the list of arguments.

Residuals

Warning

⚠️This function is still in development. Use it with caution. ⚠️

Histogram of the residuals r_i = observed_i − mean prediction_i. It should be centred on 0 and roughly symmetric; a shift is a systematic bias, skewness a wrong likelihood family, two modes a missing group, and long tails a few badly predicted observations (see LOO influence).

Code
m.diag.ppc_error_hist()
m$diag$ppc_error_hist()
@pyplot m.diag.ppc_error_hist()

See m.diag.ppc_error_hist for further information regarding the list of arguments.

Observed versus individual predictions

Warning

⚠️This function is still in development. Use it with caution. ⚠️

Each panel plots the observed data against one predicted dataset (not the mean), so the observation noise is included and the cloud is wider than if each observation were compared with its mean prediction. The width of the cloud around the diagonal should be similar from one panel to the next; observed values that systematically overshoot on one side mean the simulated noise is mis-calibrated.

Code
m.diag.ppc_scatter()
m$diag$ppc_scatter()
@pyplot m.diag.ppc_scatter()

See m.diag.ppc_scatter for further information regarding the list of arguments.

LOO influence

Warning

⚠️This function is still in development. Use it with caution. ⚠️

One point per observation with its Pareto k, from PSIS-LOO: how much the posterior would change if this observation were left out.

k Reading
< 0.5 fine
0.5 – 0.7 (orange line) noticeable influence, the LOO estimate is still reliable
> 0.7 (red line, red points) very influential observation; LOO is unreliable for it

A few red points are often outliers or data errors (hover to see their index and value). Many red points mean the model is misspecified or too flexible (for example one parameter per observation); try a robust likelihood (Student-t) or a more structured model. When some k exceed 0.7, model comparison with m.diag.loo() / compare is not reliable.

Code
m.diag.influence()
m$diag$influence()
@pyplot m.diag.influence()

See m.diag.influence for further information regarding the list of arguments.

Calibration

Warning

⚠️This function is still in development. Use it with caution. ⚠️

For several interval levels (50%, 60%, …, 99%), the share of observed values that actually fall inside the predictive interval of that level (y axis) against the level itself (x axis); the dashed diagonal is perfect calibration. Points below the diagonal (the “90%” interval contains only, say, 70% of the data) mean the model is over-confident, which is the most serious case; points above it mean the model is too cautious. These intervals are not leave-one-out, so a slight over-coverage is expected.

Code
m.diag.calibration()
m$diag$calibration()
@pyplot m.diag.calibration()

See m.diag.calibration for further information regarding the list of arguments.

Multimodality check

Warning

⚠️This function is still in development. Use it with caution. ⚠️

Flags parameters whose posterior density has more than one local maximum (potential multimodality) and overlays the densities of the individual chains.

Code
m.diag.multimodality()
m$diag$multimodality()
@pyplot m.diag.multimodality()

See m.diag.multimodality for further information regarding the list of arguments.