Diagnostics (m.diag)

Convergence diagnostics, model comparison and posterior predictive checks. Available after m.fit().

m.diag.WAIC

m.diag.WAIC(log_likelihood=None, pointwise=False, scale='log', var_name=None)

Widely applicable information criterion (WAIC).

Argument Type Description
log_likelihood array Pointwise log-likelihood (chains, draws, observations). Computed from the model by default.
pointwise bool Also return per-observation values. Defaults to False.
scale str "log" (default), "negative_log" or "deviance".
var_name str Observed variable to use when the model has several.

Returns

  • ELPD estimate (elpd_waic), its standard error and p_waic.

m.diag.autocor

m.diag.autocor(
    include=None,
    exclude=None,
    filtered=True,
    x_label=None,
    y_label=None,
    **kw,
)

Autocorrelation of the draws of each parameter, per chain.

Argument Type Description
include str or list of str Parameters to plot (default: all).
exclude str or list of str Parameters to leave out.
filtered bool Use m.posteriors (True, default) or every sampled site, m.posteriors_full (False).
x_label str or list of str X-axis title; a list gives one per subplot, in order. Defaults to the plot’s own labels.
y_label str or list of str Y-axis title, as x_label.
**kw Passed to the plotting function (e.g. figsize).

Returns

  • plotly.graph_objects.Figure

m.diag.calibration

m.diag.calibration(
    y=None,
    yrep=None,
    levels=None,
    title=None,
    name='y',
    x_label=None,
    y_label=None,
)

Empirical coverage vs nominal credible interval levels.

y and yrep default to the model’s observed outcome and its posterior predictive draws (m.diag.get_yrep()); name defaults to the observed site name. For ppc_loo_pit, log_likelihood is computed from the model when yrep is not given.

For each level α, computes the fraction of observed y values that fall inside the α-level predictive interval. A well-calibrated model has empirical ≈ nominal.

Argument Type Description
y Observed data, shape (n_obs,).
yrep Posterior predictive matrix, shape (n_rep, n_obs).
levels List of nominal coverage levels. Defaults to [0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99].
title Plot title. Defaults to one naming the outcome.
name Name of the outcome used in the labels.
x_label X-axis title (a list gives one per subplot, in order). Defaults to the plot’s own label.
y_label Y-axis title, as x_label.

Returns

  • plotly Figure.

m.diag.compare

m.diag.compare(
    compare_dict,
    ic=None,
    method='stacking',
    b_samples=1000,
    alpha=1,
    seed=None,
    scale=None,
    var_name=None,
)

Compare models based on their expected log pointwise predictive density (ELPD).

The ELPD is estimated either by Pareto smoothed importance sampling leave-one-out cross-validation (LOO) or using the widely applicable information criterion (WAIC). We recommend loo. Read more theory here - in a paper by some of the leading authorities on model comparison dx.doi.org/10.1111/1467-9868.00353

Argument Type Description
compare_dict A dictionary of model names and arviz.InferenceData or ELPDData.
ic Method to estimate the ELPD, available options are “loo” or “waic”. Defaults to rcParams["stats.information_criterion"].
method Method used to estimate the weights for each model. Available options are: - ‘stacking’ : stacking of predictive distributions. - ‘BB-pseudo-BMA’ : pseudo-Bayesian Model averaging using Akaike-type weighting. The weights are stabilized using the Bayesian bootstrap. - ‘pseudo-BMA’: pseudo-Bayesian Model averaging using Akaike-type weighting, without Bootstrap stabilization (not recommended). For more information read https://arxiv.org/abs/1704.02030
b_samples Number of samples taken by the Bayesian bootstrap estimation. Only useful when method = ‘BB-pseudo-BMA’. Defaults to rcParams["stats.ic_compare_method"].
alpha The shape parameter in the Dirichlet distribution used for the Bayesian bootstrap. Only useful when method = ‘BB-pseudo-BMA’. When alpha=1 (default), the distribution is uniform on the simplex. A smaller alpha will keeps the final weights more away from 0 and 1.
seed If int or RandomState, use it for seeding Bayesian bootstrap. Only useful when method = ‘BB-pseudo-BMA’. Default None the global numpy.random state is used.
scale Output scale for IC. Available options are: - log : (default) log-score (after Vehtari et al. (2017)) - negative_log : -1 * (log-score) - deviance : -2 * (log-score) A higher log-score (or a lower deviance) indicates a model with better predictive accuracy.
var_name If there is more than a single observed variable in the InferenceData, which should be used as the basis for comparison.

Returns

  • A DataFrame, ordered from best to worst model (measured by the ELPD).:
  • The index reflects the key with which the models are passed to this function. The columns are::
  • The rank-order of the models. 0 is the best.:
  • ELPD estimated either using (PSIS-LOO-CVelpd_looor WAICelpd_waic).: Higher ELPD indicates higher out-of-sample predictive fit (“better” model). If scale is deviance or negative_log smaller values indicates higher out-of-sample predictive fit (“better” model).
  • Estimated effective number of parameters.:
  • The difference in ELPD between two models.: If more than two models are compared, the difference is computed relative to the top-ranked model, that always has a elpd_diff of 0.
  • Relative weight for each model.: This can be loosely interpreted as the probability of each model (among the compared model) given the data. By default the uncertainty in the weights estimation is considered using Bayesian bootstrap.
  • Standard error of the ELPD estimate.: If method = BB-pseudo-BMA these values are estimated using Bayesian bootstrap.
  • Standard error of the difference in ELPD between each model and the top-ranked model.: It’s always 0 for the top-ranked model.
  • A value of 1 indicates that the computation of the ELPD may not be reliable.: This could be indication of WAIC/LOO starting to fail see http://arxiv.org/abs/1507.04544 for details.
  • Scale used for the ELPD.:

References

  1. Vehtari, A., Gelman, A. & Gabry, J. Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Stat Comput 27, 1413–1432 (2017) see https://doi.org/10.1007/s11222-016-9696-4

m.diag.density

m.diag.density(
    include=None,
    exclude=None,
    filtered=True,
    x_label=None,
    y_label=None,
    **kw,
)

Posterior density of each parameter, one curve per chain.

Argument Type Description
include str or list of str Parameters to plot (default: all).
exclude str or list of str Parameters to leave out.
filtered bool Use m.posteriors (True, default) or every sampled site, m.posteriors_full (False).
x_label str or list of str X-axis title; a list gives one per subplot, in order. Defaults to the plot’s own labels.
y_label str or list of str Y-axis title, as x_label.
**kw Passed to the plotting function (e.g. figsize).

Returns

  • plotly.graph_objects.Figure

m.diag.diagnose

m.diag.diagnose(
    max_treedepth: int = 10,
    ebfmi_threshold: float = 0.3,
    rhat_threshold: float = 1.01,
    ess_threshold: float = 400.0,
)

Run MCMC convergence diagnostics on a fitted BF model.

Argument Type Description
max_treedepth int Maximum tree depth used during sampling (default 10, matching BF default).
ebfmi_threshold float E-BFMI values below this trigger a warning (default 0.3).
rhat_threshold float R-hat values above this trigger a warning (default 1.01).
ess_threshold float ESS values below this trigger a warning (default 400).

Returns

  • str: Human-readable diagnostic report.

m.diag.divergence_energy

m.diag.divergence_energy(
    title='HMC Diagnostics: Energy & Divergences',
    x_label=None,
    y_label=None,
)

Plot the HMC energy diagnostic and the divergent transitions per chain.

The fitted model m is supplied automatically.

Top row, one panel per chain (as bayesplot’s mcmc_nuts_energy): the distribution of the energy E around its mean (marginal energy) and of its change between successive iterations, Delta E (energy transition). When the Delta E histogram is about as wide as the E histogram the sampler can move across the whole posterior; a much narrower Delta E histogram means it explores the tails badly. The panel title gives E-BFMI = sum(Delta E^2) / sum((E - mean E)^2); values below 0.3 are flagged.

Bottom row: number of divergent transitions per chain (ideal: 0).

Argument Type Description
m Fitted BF model with NumPyro MCMC sampler.
title Plot title.
x_label X-axis title (a list gives one per subplot, in order). Defaults to the plot’s own label.
y_label Y-axis title, as x_label.

Returns

  • plotly Figure.

m.diag.ess

m.diag.ess(include=None, exclude=None, kind='bulk', filtered=True)

Effective sample size of each parameter.

Argument Type Description
include str or list of str Parameters to check (default: all).
exclude str or list of str Parameters to leave out.
kind str "bulk" (default) or "tail" ESS.
filtered bool Use m.posteriors (True) or m.posteriors_full (False).

Returns

  • ESS per parameter.

m.diag.forest

m.diag.forest(
    include=None,
    exclude=None,
    filtered=True,
    x_label=None,
    y_label=None,
    **kw,
)

Forest plot: posterior mean and credible interval of each parameter.

Argument Type Description
include str or list of str Parameters to plot (default: all).
exclude str or list of str Parameters to leave out.
filtered bool Use m.posteriors (True, default) or every sampled site, m.posteriors_full (False).
x_label str or list of str X-axis title; a list gives one per subplot, in order. Defaults to the plot’s own labels.
y_label str or list of str Y-axis title, as x_label.
**kw Passed to the plotting function (e.g. figsize).

Returns

  • plotly.graph_objects.Figure

m.diag.get_yrep

m.diag.get_yrep(site=None, seed=None)

Posterior predictive draws of the observed outcome(s).

Argument Type Description
site str Name of the observed site when multiple observed sites exist. If None and there are multiple sites, a dict mapping site names to their draws is returned.
seed int Seed of the predictive simulation. Defaults to None (a fresh draw from the model’s random stream).

Returns

  • Array of shape (draws, observations) or dict[str, Array].

m.diag.influence

m.diag.influence(
    log_likelihood=None,
    x=None,
    y=None,
    good_k=None,
    title='LOO Influence: Pareto-k Diagnostics',
    x_label=None,
    y_label=None,
)

Scatter of Pareto-k values per observation.

The fitted model m is supplied automatically.

High k values (k > 0.7) indicate influential observations where the model is sensitive — potential outliers or model misspecification.

Argument Type Description
m Fitted BF model. Used to auto-compute log_likelihood if not given.
log_likelihood Pre-computed log-likelihood array, shape (C, S, N) or (S, N). If None, computed from m.model + m.data_on_model.
x Optional 1D array of x-axis values (e.g. predictor). Defaults to 1..N.
y Optional 1D array of observed values for hover text.
good_k Threshold for flagging bad k (default 0.7).
title Plot title.
x_label X-axis title (a list gives one per subplot, in order). Defaults to the plot’s own label.
y_label Y-axis title, as x_label.

Returns

  • plotly Figure with horizontal reference lines at k=0.5, 0.7.

m.diag.loo

m.diag.loo(log_likelihood=None, pointwise=False, scale='log', reff=None, var_name=None)

Pareto-smoothed importance-sampling leave-one-out cross-validation (PSIS-LOO).

Estimates the expected log pointwise predictive density (ELPD) of the fitted model. Use m.diag.compare({"m1": m1, "m2": m2}) to rank models.

Argument Type Description
log_likelihood array Pointwise log-likelihood (chains, draws, observations). Computed from the model by default.
pointwise bool Also return per-observation values and Pareto k. Defaults to False.
scale str "log" (default), "negative_log" or "deviance".
reff float Relative MCMC efficiency; estimated from the chains by default.
var_name str Observed variable to use when the model has several.

Returns

  • ELPD estimate, its standard error and the effective number of parameters (p_loo).

m.diag.mcse

m.diag.mcse(include=None, exclude=None, kind='mean', filtered=True)

Monte Carlo standard error of each parameter’s posterior summary.

Argument Type Description
include str or list of str Parameters to check (default: all).
exclude str or list of str Parameters to leave out.
kind str Summary whose error is estimated: "mean" (default), "sd" or a quantile.
filtered bool Use m.posteriors (True) or m.posteriors_full (False).

Returns

  • MCSE per parameter.

m.diag.model_checks

m.diag.model_checks(include=None, exclude=None, filter_regex=None, filtered=True)

Show the standard convergence plots in one call.

Displays posterior densities, autocorrelation, trace, forest and pair plots.

Argument Type Description
include str or list of str Parameters to plot (default: all).
exclude str or list of str Parameters to leave out.
filter_regex str Regular expression on parameter names.
filtered bool Use m.posteriors (True) or m.posteriors_full (False).

m.diag.multimodality

m.diag.multimodality(
    posteriors=None,
    param_names=None,
    n_modes=2,
    title='Multimodality Check',
    x_label=None,
    y_label=None,
)

Detect multiple modes in posterior marginals using KDE + local maxima.

The fitted model m is supplied automatically.

Flags parameters whose KDE has more than one local maximum (potential multimodality). Also overlays chain-separated density to show if chains explore different regions.

Argument Type Description
m Fitted BF model. Uses m.posteriors and m.posteriors_by_chain.
posteriors Dict {param: array(S,)} — override m.posteriors.
param_names Subset of parameters to check.
n_modes Number of modes to highlight.
title Plot title.
x_label X-axis title (a list gives one per subplot, in order). Defaults to the plot’s own label.
y_label Y-axis title, as x_label.

Returns

  • plotly Figure, one subplot per parameter.

m.diag.pair

m.diag.pair(include=None, exclude=None, filtered=True, x_label=None, y_label=None, **kw)

Pairwise scatter plots of the draws (correlations, funnels, multimodality).

Argument Type Description
include str or list of str Parameters to plot (default: all).
exclude str or list of str Parameters to leave out.
filtered bool Use m.posteriors (True, default) or every sampled site, m.posteriors_full (False).
x_label str or list of str X-axis title; a list gives one per subplot, in order. Defaults to the plot’s own labels.
y_label str or list of str Y-axis title, as x_label.
**kw Passed to the plotting function (e.g. figsize).

Returns

  • plotly.graph_objects.Figure

m.diag.plot_compare

m.diag.plot_compare(
    comp_df,
    insample_dev=False,
    plot_standard_error=True,
    plot_ic_diff=False,
    order_by_rank=True,
    legend=False,
    title=True,
    figsize=None,
    textsize=None,
    labeller=None,
    plot_kwargs=None,
    ax=None,
    backend=None,
    backend_kwargs=None,
    show=None,
)

Summary plot for model comparison.

Models are compared based on their expected log pointwise predictive density (ELPD). This plot is in the style of the one used in [2]_. Chapter 6 in the first edition or 7 in the second.

Notes

The ELPD is estimated either by Pareto smoothed importance sampling leave-one-out cross-validation (LOO) or using the widely applicable information criterion (WAIC). We recommend LOO in line with the work presented by [1]_.

Argument Type Description
comp_df pandas.DataFrame Result of the arviz.compare method.
insample_dev bool Plot in-sample ELPD, that is the value of the information criteria without the penalization given by the effective number of parameters (p_loo or p_waic).
plot_standard_error bool Plot the standard error of the ELPD.
plot_ic_diff bool Plot standard error of the difference in ELPD between each model and the top-ranked model.
order_by_rank bool If True ensure the best model is used as reference.
legend bool Add legend to figure.
figsize (float, float) If None, size is (6, num of models) inches.
title bool Show a tittle with a description of how to interpret the plot.
textsize float Text size scaling factor for labels, titles and lines. If None it will be autoscaled based on figsize.
labeller Labeller Class providing the method make_label_vert to generate the labels in the plot titles. Read the :ref:label_guide for more details and usage examples.
plot_kwargs dict Optional arguments for plot elements. Currently accepts ‘color_ic’, ‘marker_ic’, ‘color_insample_dev’, ‘marker_insample_dev’, ‘color_dse’, ‘marker_dse’, ‘ls_min_ic’ ‘color_ls_min_ic’, ‘fontsize’
ax matplotlib_axes or bokeh_figure Matplotlib axes or bokeh figure.
backend “matplotlib”, “bokeh” Select plotting backend.
backend_kwargs bool These are kwargs specific to the backend being used, passed to matplotlib.pyplot.subplots or bokeh.plotting.figure. For additional documentation check the plotting method of the backend.
show bool Call backend show function.

Returns

  • matplotlib_axes or bokeh_figure:

See Also

plot_elpd : Plot pointwise elpd differences between two or more models. compare : Compare models based on PSIS-LOO loo or WAIC waic cross-validation. loo : Compute Pareto-smoothed importance sampling leave-one-out cross-validation (PSIS-LOO-CV). waic : Compute the widely applicable information criterion.

References

  1. Vehtari et al. (2016). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC https://arxiv.org/abs/1507.04544

  2. McElreath R. (2022). Statistical Rethinking A Bayesian Course with Examples in R and Stan, Second edition, CRC Press.

m.diag.plot_ess

m.diag.plot_ess(
    include=None,
    exclude=None,
    filtered=True,
    x_label=None,
    y_label=None,
    **kw,
)

Evolution of the effective sample size as draws accumulate.

Argument Type Description
include str or list of str Parameters to plot (default: all).
exclude str or list of str Parameters to leave out.
filtered bool Use m.posteriors (True, default) or every sampled site, m.posteriors_full (False).
x_label str or list of str X-axis title; a list gives one per subplot, in order. Defaults to the plot’s own labels.
y_label str or list of str Y-axis title, as x_label.
**kw Passed to the plotting function (e.g. figsize).

Returns

  • plotly.graph_objects.Figure

m.diag.plot_trace

m.diag.plot_trace(
    include=None,
    exclude=None,
    filtered=True,
    x_label=None,
    y_label=None,
    **kw,
)

Trace plot of each chain (mixing and stationarity).

Argument Type Description
include str or list of str Parameters to plot (default: all).
exclude str or list of str Parameters to leave out.
filtered bool Use m.posteriors (True, default) or every sampled site, m.posteriors_full (False).
x_label str or list of str X-axis title; a list gives one per subplot, in order. Defaults to the plot’s own labels.
y_label str or list of str Y-axis title, as x_label.
**kw Passed to the plotting function (e.g. figsize).

Returns

  • plotly.graph_objects.Figure

m.diag.posterior

m.diag.posterior(
    include=None,
    exclude=None,
    filtered=True,
    x_label=None,
    y_label=None,
    **kw,
)

Posterior density of each parameter with its credible interval.

Argument Type Description
include str or list of str Parameters to plot (default: all).
exclude str or list of str Parameters to leave out.
filtered bool Use m.posteriors (True, default) or every sampled site, m.posteriors_full (False).
x_label str or list of str X-axis title; a list gives one per subplot, in order. Defaults to the plot’s own labels.
y_label str or list of str Y-axis title, as x_label.
**kw Passed to the plotting function (e.g. figsize).

Returns

  • plotly.graph_objects.Figure

m.diag.ppc_bars

m.diag.ppc_bars(y=None, yrep=None, title=None, name='y', x_label=None, y_label=None)

Bar chart comparing observed y to posterior predictive yrep.

y and yrep default to the model’s observed outcome and its posterior predictive draws (m.diag.get_yrep()); name defaults to the observed site name. For ppc_loo_pit, log_likelihood is computed from the model when yrep is not given.

For ordinal, categorical, or discrete outcomes. Shows observed counts and, per category, the median predicted count with a 90% interval, as in bayesplot’s ppc_bars.

Argument Type Description
y Observed discrete values.
yrep Posterior predictive matrix.
title Plot title. Defaults to one naming the outcome.
name Name of the outcome used in the labels.
x_label X-axis title (a list gives one per subplot, in order). Defaults to the plot’s own label.
y_label Y-axis title, as x_label.

Returns: plotly Figure.

m.diag.ppc_boxplot

m.diag.ppc_boxplot(
    y=None,
    yrep=None,
    n=20,
    title=None,
    name='y',
    x_label=None,
    y_label=None,
)

Box-and-whisker: y (black) vs n yrep draws.

y and yrep default to the model’s observed outcome and its posterior predictive draws (m.diag.get_yrep()); name defaults to the observed site name. For ppc_loo_pit, log_likelihood is computed from the model when yrep is not given.

Argument Type Description
y Observed data.
yrep Posterior predictive matrix.
n Number of yrep draws.
title Plot title. Defaults to one naming the outcome.
name Name of the outcome used in the labels.
x_label X-axis title (a list gives one per subplot, in order). Defaults to the plot’s own label.
y_label Y-axis title, as x_label.

Returns: plotly Figure.

m.diag.ppc_density

m.diag.ppc_density(
    y=None,
    yrep=None,
    n=50,
    bw_adjust=1.0,
    title=None,
    name='y',
    x_label=None,
    y_label=None,
)

KDE of y (black) vs n random draws from yrep rows (blue).

y and yrep default to the model’s observed outcome and its posterior predictive draws (m.diag.get_yrep()); name defaults to the observed site name. For ppc_loo_pit, log_likelihood is computed from the model when yrep is not given.

Argument Type Description
y Observed data, shape (n_obs,).
yrep Posterior predictive matrix, shape (n_rep, n_obs).
n Max number of yrep lines to show.
bw_adjust Bandwidth multiplier passed to scipy KDE.
title Plot title. Defaults to one naming the outcome.
name Name of the outcome used in the labels (“Predictions of ”); m.diag passes the observed site name.
x_label X-axis title (a list gives one per subplot, in order). Defaults to the plot’s own label.
y_label Y-axis title, as x_label.

Returns: plotly Figure.

m.diag.ppc_error_hist

m.diag.ppc_error_hist(
    y=None,
    yrep=None,
    bins=40,
    title=None,
    name='y',
    x_label=None,
    y_label=None,
)

Distribution of mean residuals r_i = y_i - E[yrep_i].

y and yrep default to the model’s observed outcome and its posterior predictive draws (m.diag.get_yrep()); name defaults to the observed site name. For ppc_loo_pit, log_likelihood is computed from the model when yrep is not given.

Argument Type Description
y Observed data.
yrep Posterior predictive matrix.
bins Number of histogram bins.
title Plot title. Defaults to one naming the outcome.
name Name of the outcome used in the labels.
x_label X-axis title (a list gives one per subplot, in order). Defaults to the plot’s own label.
y_label Y-axis title, as x_label.

Returns: plotly Figure.

m.diag.ppc_hist

m.diag.ppc_hist(
    y=None,
    yrep=None,
    n=8,
    bins=30,
    title=None,
    name='y',
    x_label=None,
    y_label=None,
)

Histograms: observed y plus n random yrep draws.

y and yrep default to the model’s observed outcome and its posterior predictive draws (m.diag.get_yrep()); name defaults to the observed site name. For ppc_loo_pit, log_likelihood is computed from the model when yrep is not given.

Argument Type Description
y Observed data.
yrep Posterior predictive matrix.
n Number of yrep draws to show.
bins Number of histogram bins.
title Plot title. Defaults to one naming the outcome.
name Name of the outcome used in the labels.
x_label X-axis title (a list gives one per subplot, in order). Defaults to the plot’s own label.
y_label Y-axis title, as x_label.

Returns: plotly Figure.

m.diag.ppc_intervals

m.diag.ppc_intervals(
    y=None,
    yrep=None,
    x=None,
    prob=0.5,
    prob_outer=0.9,
    title=None,
    name='y',
    x_label=None,
    y_label=None,
)

Predictive interval of each observation, with the observed value.

y and yrep default to the model’s observed outcome and its posterior predictive draws (m.diag.get_yrep()); name defaults to the observed site name. For ppc_loo_pit, log_likelihood is computed from the model when yrep is not given.

One vertical bar per observation, as bayesplot’s ppc_intervals: a thin line for the outer (prob_outer) interval, a thick line for the inner (prob) interval, a light point for the median prediction and a dark point for the observed value. About prob of the observed points should fall on the thick bars and prob_outer on the thin ones.

Argument Type Description
y Observed data, shape (n_obs,).
yrep Posterior predictive matrix, shape (n_rep, n_obs).
x Optional x-axis variable, shape (n_obs,) (e.g. a predictor). Defaults to the observation index.
prob Inner interval probability (e.g., 0.5).
prob_outer Outer interval probability (e.g., 0.9).
title Plot title. Defaults to one naming the outcome.
name Name of the outcome used in the labels.
x_label X-axis title (a list gives one per subplot, in order). Defaults to the plot’s own label.
y_label Y-axis title, as x_label.

Returns: plotly Figure.

m.diag.ppc_loo_intervals

m.diag.ppc_loo_intervals(
    y=None,
    yrep=None,
    x=None,
    prob=0.9,
    title=None,
    name='y',
    x_label=None,
    y_label=None,
)

Deprecated alias for ppc_intervals_sorted (it is not LOO-based).

y and yrep default to the model’s observed outcome and its posterior predictive draws (m.diag.get_yrep()); name defaults to the observed site name. For ppc_loo_pit, log_likelihood is computed from the model when yrep is not given.

prob is the outer interval, as before; the inner one is 50%.

m.diag.ppc_ribbon

m.diag.ppc_ribbon(
    y=None,
    yrep=None,
    x=None,
    prob=0.5,
    prob_outer=0.9,
    title=None,
    name='y',
    x_label=None,
    y_label=None,
)

Predictive intervals drawn as continuous ribbons along x.

y and yrep default to the model’s observed outcome and its posterior predictive draws (m.diag.get_yrep()); name defaults to the observed site name. For ppc_loo_pit, log_likelihood is computed from the model when yrep is not given.

Same intervals as ppc_intervals, as bayesplot’s ppc_ribbon: a light outer ribbon, a darker inner ribbon, a thin line for the median prediction and the observed values as points. Easier to read than the bars when x is continuous (time, dose, a predictor).

Argument Type Description
y Observed data, shape (n_obs,).
yrep Posterior predictive matrix, shape (n_rep, n_obs).
x Optional x-axis variable, shape (n_obs,). Defaults to the observation index.
prob Inner interval probability (e.g., 0.5).
prob_outer Outer interval probability (e.g., 0.9).
title Plot title. Defaults to one naming the outcome.
name Name of the outcome used in the labels.
x_label X-axis title (a list gives one per subplot, in order). Defaults to the plot’s own label.
y_label Y-axis title, as x_label.

Returns: plotly Figure.

m.diag.ppc_rootogram

m.diag.ppc_rootogram(
    y=None,
    yrep=None,
    title=None,
    name='y',
    x_label=None,
    y_label=None,
)

Hanging rootogram for count outcomes.

y and yrep default to the model’s observed outcome and its posterior predictive draws (m.diag.get_yrep()); name defaults to the observed site name. For ppc_loo_pit, log_likelihood is computed from the model when yrep is not given.

Compares sqrt of observed counts (bars) to expected sqrt counts (curve). Bars hanging below zero indicate over-prediction; above zero: under-prediction.

Argument Type Description
y Observed integer counts.
yrep Posterior predictive matrix of counts.
title Plot title. Defaults to one naming the outcome.
name Name of the outcome used in the labels.
x_label X-axis title (a list gives one per subplot, in order). Defaults to the plot’s own label.
y_label Y-axis title, as x_label.

Returns: plotly Figure.

m.diag.ppc_scatter

m.diag.ppc_scatter(
    y=None,
    yrep=None,
    n_reps=9,
    title=None,
    name='y',
    x_label=None,
    y_label=None,
)

Small-multiple scatterplots of y vs n_reps random rows of yrep.

y and yrep default to the model’s observed outcome and its posterior predictive draws (m.diag.get_yrep()); name defaults to the observed site name. For ppc_loo_pit, log_likelihood is computed from the model when yrep is not given.

Argument Type Description
y Observed data.
yrep Posterior predictive matrix.
n_reps Number of replications to show.
title Plot title. Defaults to one naming the outcome.
name Name of the outcome used in the labels.
x_label X-axis title (a list gives one per subplot, in order). Defaults to the plot’s own label.
y_label Y-axis title, as x_label.

Returns: plotly Figure.

m.diag.ppc_stat

m.diag.ppc_stat(
    y=None,
    yrep=None,
    stat='mean',
    title=None,
    name='y',
    x_label=None,
    y_label=None,
)

Distribution of test statistic over yrep vs observed value.

y and yrep default to the model’s observed outcome and its posterior predictive draws (m.diag.get_yrep()); name defaults to the observed site name. For ppc_loo_pit, log_likelihood is computed from the model when yrep is not given.

Argument Type Description
y Observed data.
yrep Posterior predictive matrix.
stat Statistic name or callable. Options: ‘mean’, ‘median’, ‘sd’, ‘var’, ‘min’, ‘max’, ‘q25’, ‘q75’, ‘skew’, ‘n_zero’, ‘n_pos’. A callable takes one 1D array and returns a number, e.g. lambda v: np.percentile(v, 90).
title Plot title. Defaults to one naming the statistic, the outcome and the Bayesian p-values.
name Name of the outcome used in the labels.
x_label X-axis title (a list gives one per subplot, in order). Defaults to the plot’s own label.
y_label Y-axis title, as x_label.

Returns: plotly Figure with Bayesian p-value annotation.

m.diag.ppc_stat_2d

m.diag.ppc_stat_2d(
    y=None,
    yrep=None,
    stat1='mean',
    stat2='sd',
    title=None,
    name='y',
    x_label=None,
    y_label=None,
)

Scatter of two test statistics over yrep vs observed point.

y and yrep default to the model’s observed outcome and its posterior predictive draws (m.diag.get_yrep()); name defaults to the observed site name. For ppc_loo_pit, log_likelihood is computed from the model when yrep is not given.

Argument Type Description
y Observed data.
yrep Posterior predictive matrix.
stat1, stat2 Statistic names or callables.
title Plot title. Defaults to one naming the outcome.
name Name of the outcome used in the labels.
x_label X-axis title (a list gives one per subplot, in order). Defaults to the plot’s own label.
y_label Y-axis title, as x_label.

Returns: plotly Figure.

m.diag.prior_sensitivity

m.diag.prior_sensitivity(
    posteriors_list,
    labels,
    param_names=None,
    hdi_prob=0.89,
    title='Prior Sensitivity Analysis',
    x_label=None,
    y_label=None,
)

Overlay posteriors from models fitted with different priors/assumptions.

Compares posterior distributions across multiple model fits to assess how much conclusions change when priors (or likelihood assumptions) vary.

Argument Type Description
posteriors_list List of posterior dicts, each {param: array(S,)}. Typically [m1.posteriors, m2.posteriors, …].
labels List of labels for each fit (e.g. [‘weakly informative’, ‘strong prior’, ‘alternative likelihood’]).
param_names Subset of parameters to compare. Defaults to all parameters present in all fits.
hdi_prob HDI probability for interval markers.
title Plot title.
x_label X-axis title (a list gives one per subplot, in order). Defaults to the plot’s own label.
y_label Y-axis title, as x_label.

Returns

  • plotly Figure with one subplot per parameter.

Example

Refit with a tighter prior on b and compare m1.fit(model_weak, …); m2.fit(model_strong, …) fig = prior_sensitivity_plot( [m1.posteriors, m2.posteriors], labels=[‘weak prior’, ‘strong prior’], )

m.diag.rank

m.diag.rank(include=None, exclude=None, filtered=True, x_label=None, y_label=None, **kw)

Rank plots: histograms of draw ranks per chain (uniform when chains agree).

Argument Type Description
include str or list of str Parameters to plot (default: all).
exclude str or list of str Parameters to leave out.
filtered bool Use m.posteriors (True, default) or every sampled site, m.posteriors_full (False).
x_label str or list of str X-axis title; a list gives one per subplot, in order. Defaults to the plot’s own labels.
y_label str or list of str Y-axis title, as x_label.
**kw Passed to the plotting function (e.g. figsize).

Returns

  • plotly.graph_objects.Figure

m.diag.rhat

m.diag.rhat(include=None, exclude=None, filtered=True, method='rank')

Potential scale reduction factor (R-hat) of each parameter.

Values close to 1 (below 1.01) indicate that the chains have mixed. Requires more than one chain.

Argument Type Description
include str or list of str Parameters to check (default: all).
exclude str or list of str Parameters to leave out.
filtered bool Use m.posteriors (True) or m.posteriors_full (False).
method str R-hat variant, "rank" (rank-normalised split R-hat, default) or "split".

Returns

  • R-hat per parameter.

m.diag.summary

m.diag.summary(
    include=None,
    exclude=None,
    round_to=2,
    hdi_prob=0.89,
    filter_regex=None,
    filtered=True,
    kind='all',
)

Posterior summary table (mean, sd, credible interval, ESS, R-hat, MCSE).

Argument Type Description
include str or list of str Parameters to summarise (default: all).
exclude str or list of str Parameters to leave out.
round_to int Number of decimals. Defaults to 2.
hdi_prob float Probability mass of the credible interval. Defaults to 0.89.
filter_regex str Regular expression on parameter names (JAX backend).
filtered bool Use m.posteriors (True) or every sampled site, m.posteriors_full (False). Defaults to True.
kind str "all", "stats" or "diagnostics". Defaults to "all".

Returns

  • pandas.DataFrame: One row per parameter element (mean, sd, credible interval, mcse_mean, mcse_sd, ess_bulk, ess_tail, r_hat).
  • Updates on m / m.diag:
    • When using the 'arviz' backend (default), initializes and caches m._az_diag (including m._az_diag.trace and m._az_diag.tab_summary) if not yet built. Does not overwrite m.posteriors when include/exclude is passed.

m.diag.to_az

m.diag.to_az(
    backend='numpyro',
    sample_stats_name=['target_log_prob', 'log_accept_ratio', 'has_divergence', 'energy'],
)

Convert the sampler output to an ArviZ InferenceData trace object.

This method prepares the trace for use with ArviZ diagnostic tools.

Returns

  • arviz.InferenceData: The ArviZ InferenceData object stored in m.diag.trace.
  • Updates on m.diag:
    • m.diag.trace: stores the converted arviz.InferenceData object (posterior and sample_stats groups).
    • m.diag.priors_name: list of posterior variable names present in m.diag.trace.

m.diag.waic

m.diag.waic(log_likelihood=None, pointwise=False, scale='log', var_name=None)

Widely applicable information criterion (WAIC).

Argument Type Description
log_likelihood array Pointwise log-likelihood (chains, draws, observations). Computed from the model by default.
pointwise bool Also return per-observation values. Defaults to False.
scale str "log" (default), "negative_log" or "deviance".
var_name str Observed variable to use when the model has several.

Returns

  • ELPD estimate (elpd_waic), its standard error and p_waic.