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=...):
m.sample() # Predictions from model based on data in data_on_modelpred = m.sample(data=dict(weight=jnp.array([0.4])), remove_obs=False) # Full posterior predictive (2000 draws)# 1. Single random predictive draw from the posteriorm.sample(data=dict(weight=jnp.array([0.4])), remove_obs=False, samples=1)# 2. Posterior predictive mean across all 2000 drawsjnp.mean(pred["height"])# 3. Single draw at fixed parameter valuesm.sample( data=dict(weight=jnp.array([0.4])), posterior=dict(a=154.6, b=5.8, s=5.1), remove_obs=False,)
m$sample() # Predictions from model based on data in data_on_modelpred <- 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 posteriorm$sample(data =list(weight = jnp$array(c(0.4))), remove_obs =FALSE, samples =1L)# 2. Posterior predictive mean across all 2000 drawsjnp$mean(pred$height)# 3. Single draw at fixed parameter valuesm$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_modelpred = m.sample(data =pydict(weight = jnp.array([0.4])), remove_obs =false) # Full posterior predictive (2000 draws)# 1. Single random predictive draw from the posteriorm.sample(data =pydict(weight = jnp.array([0.4])), remove_obs =false, samples =1)# 2. Posterior predictive mean across all 2000 drawsjnp.mean(pred["height"])# 3. Single draw at fixed parameter valuesm.sample( data =pydict(weight = jnp.array([0.4])), posterior =pydict(a =154.6, b =5.8, s =5.1), remove_obs =false)
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:
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.
/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.
# Refit the same model with a tighter prior on bposteriors_weak = m.posteriorsdef 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 bposteriors_weak <- m$posteriorsmodel_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 bposteriors_weak = m.posteriors@BFfunctionmodel_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)endm.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.
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 fitsobs =list(weight = weight, height = height),fit_kwargs =list(num_samples =500L, num_chains =1L),return_results =TRUE) # out[[1]]: figure, out[[2]]: table
@simfunctionmodel(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")endfig, 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.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).
⚠️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.
/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.
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.
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.
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).
⚠️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.
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.
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.
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.