bayesplain.Result

class bayesplain.Result(*, quantity, draws, posterior=None, prior=None, subject='', analysis='', frequentist=None, log_bf10=None, bf_caveat='', bf_alternative='a difference', unit='', display_scale=1.0, decimals=None, direction_reference=0.0, reference_is_null=True, higher_label='', lower_label='', components=None, component_axis='', component_scale=None, custom_plots=None, no_sensitivity_reason='', no_bayes_factor_reason='', predictor=None, no_predict_reason='', next_steps='', refit=None, prior_ladder=None, n_draws=None, notes=None)[source]

What every bayesplain analysis hands back.

Parameters:
quantity : str

Name of the estimated quantity, as it should appear in output, e.g. "difference in filing rate (District B - District A)".

draws : ndarray

Posterior draws of quantity. Always present, so that a single plotting routine and a single set of summary methods work for every analysis in the package.

posterior : scipy.stats.rv_continuous_frozen, optional

The analytic posterior, when one exists in closed form. When present, intervals and probabilities are read from it rather than estimated, and carry no Monte Carlo error.

prior : object, optional

The resolved prior, expected to expose .label and .dist().

subject : str, optional

How to refer to the quantity inside a running sentence, when the header form does not read well there. quantity might be "rate (34 of 220)" while subject is "filing rate". Defaults to quantity.

analysis : str

Name of the analysis that produced this, for the summary header.

frequentist : FrequentistTwin, optional

The conventional test on the same data.

log_bf10 : float, optional

Log Bayes factor, if the analysis defines one.

bf_caveat : str

What the Bayes factor depends on besides the data.

bf_alternative : str, default 'a difference'

What the alternative hypothesis asserts, so the Bayes factor’s verbal grade reads correctly – ‘an association’ for a table, ‘a relationship’ for a correlation.

unit : str

Display unit, e.g. "percentage points".

display_scale : float, default 1.0

Multiplier applied for display only. Use 100 to show a difference in proportions as percentage points. Thresholds passed to probability() and decide() are always in the unscaled units of the quantity itself.

decimals : int, optional

Decimal places for display. Defaults to 1 when display_scale is 100, otherwise 3.

direction_reference : float, default 0.0

The value that probability() compares against by default, and the one the “probability of direction” line in the summary reports.

reference_is_null : bool, default True

Whether direction_reference is the same hypothesis the paired frequentist test is built against. It is not for a quantity that cannot be negative – Cramér’s V is compared against a conventional “small association” bar, while the chi-square null is exact independence. When the two targets differ, the summary reconciles the frameworks on the size of the effect rather than on its sign, because a probability of direction says nothing about a quantity that has only one direction available to it.

higher_label : str, optional

Group names used to build a plain-English sentence for comparisons.

lower_label : str, optional

Group names used to build a plain-English sentence for comparisons.

components : mapping, optional

Per-group posteriors or draws, for plotting and for the pairwise views used by compare_groups.

component_axis : str, optional

Axis label for the components plot. Components live on a different scale from the headline quantity – each group’s own rate rather than the difference between them – so they need their own label.

component_scale : float, optional

Display multiplier for the components plot. Defaults to display_scale, which is wrong whenever the estimand is a ratio of quantities rather than the quantities themselves.

custom_plots : mapping, optional

Extra plot kinds this analysis offers, as {name: draw(ax)}. Lets a correlation expose a scatter plot without every other analysis carrying the concept.

no_sensitivity_reason : str, optional

Why sensitivity() is unavailable, when it is. Saying why is more useful than a bare “not implemented”, because usually the reason is that there is no prior to vary rather than that nobody wrote the code.

no_bayes_factor_reason : str, optional

Why bayes_factor() is unavailable, when it is.

predictor : callable, optional

Builds the Prediction returned by predict(). Its arguments are whatever that analysis’s forecast needs: a number of future trials, a future exposure, a value of the predictor.

no_predict_reason : str, optional

Why predict() is unavailable, when it is.

next_steps : str, optional

The suggestions printed at the foot of a summary. Defaults to the methods every result supports.

refit : callable, optional

refit(prior) -> Result, used by sensitivity() to recompute the same analysis under a different assumption.

prior_ladder : sequence of str, optional

Prior names to walk through in sensitivity().

n_draws : int, optional

Number of draws taken; inferred from draws when omitted.

notes : sequence of str, optional

Warnings or caveats specific to this data, e.g. small cell counts.

Methods

bayes_factor()

Evidence for a difference relative to no difference.

decide(rope[, level, kind])

Compare the credible interval against a region of practical equivalence.

interval([level, kind])

Credible interval for the quantity.

monte_carlo_error()

Monte Carlo standard error of the posterior mean.

plot([kind, threshold, level, ax])

Plot the posterior, optionally shaded at a threshold.

plot_kinds()

List the plot kinds this particular result supports.

point([kind])

Return a single representative value from the posterior.

predict(*args, **kwargs)

Forecast the next observation, carrying the uncertainty through.

probability([op, value])

Posterior probability that the quantity satisfies a comparison.

probability_of_direction()

Probability the quantity is on the side of zero the data suggest.

sensitivity([priors])

Rerun the analysis under a range of priors and show what moves.

sentence([level])

One plain-English line, ready to paste into a memo.

summary([level, kind])

Build the full side-by-side report: posterior first, then its twin.

to_dict([level])

Flat dictionary of the headline numbers, for autograding.

translate([level])

Set the two frameworks' claims side by side, in words.

bayes_factor()[source]

Evidence for a difference relative to no difference.

Deliberately a method call rather than part of the printed summary. Bayes factors answer a model-comparison question, not an estimation question, and they depend on the prior in a way credible intervals largely stop doing once there is a reasonable amount of data. Reach for this when a reviewer asks for it, not when writing a recommendation.

Returns:

The Bayes factor with its interpretation and caveat.

Return type:

BayesFactor

Raises:

NotImplementedError – If this analysis does not define one.

decide(rope, level=0.95, kind='hdi')[source]

Compare the credible interval against a region of practical equivalence.

The replacement for “reject the null”. You name a range of values too small to matter for the decision at hand – on policy grounds, not statistical ones – and the verdict follows from whether the credible interval sits inside it, outside it, or straddles its edge.

Parameters:
rope : tuple of float

(low, high) bounds of the region of practical equivalence, in the quantity’s own units.

level : float, default 0.95

Credible level for the comparison.

kind : {'hdi', 'eti'}, default 'hdi'

Interval type.

Returns:

The verdict and its explanation.

Return type:

Decision

property exact[source]

Whether an analytic posterior is available for this quantity.

interval(level=0.95, kind='hdi')[source]

Credible interval for the quantity.

Unlike a confidence interval, this one supports the sentence people already want to say: given the data and the stated prior, there is a level probability the quantity lies in this range.

Parameters:
level : float, default 0.95

Probability the interval should contain.

kind : {'hdi', 'eti'}, default 'hdi'

Highest-density (shortest) or equal-tailed. Use 'eti' when lining the interval up against a confidence interval.

Returns:

Lower and upper bounds, in the quantity’s own units.

Return type:

tuple of float

property is_comparison[source]

Whether this result estimates a difference between groups.

monte_carlo_error()[source]

Monte Carlo standard error of the posterior mean.

Reported rather than hidden. Because the package fixes a default seed so that a whole classroom sees identical digits, the noise that seed conceals should be stated explicitly somewhere – this is where.

Returns:

Standard error of the mean, or 0.0 when the answer is analytic.

Return type:

float

plot(kind='posterior', threshold=None, level=0.95, ax=None, **kwargs)[source]

Plot the posterior, optionally shaded at a threshold.

Parameters:
kind : str, default 'posterior'

What to draw. 'posterior' and 'prior_posterior' are always available; 'components' shows each group’s posterior separately, which is the picture that explains where a difference came from. Some analyses add their own – a correlation offers 'scatter'. See .plot_kinds().

threshold : float, optional

Shade the posterior beyond this value and label the shaded mass. Defaults to direction_reference for comparisons.

level : float, default 0.95

Credible level to mark.

ax : matplotlib.axes.Axes, optional

Axes to draw on. Created if omitted.

**kwargs

Passed to the underlying fill.

Returns:

The axes drawn on.

Return type:

matplotlib.axes.Axes

Raises:

ImportError – If matplotlib is not installed. Install with pip install bayesplain[plot].

plot_kinds()[source]

List the plot kinds this particular result supports.

Returns:

Names accepted by plot().

Return type:

list of str

point(kind='median')[source]

Return a single representative value from the posterior.

Parameters:
kind : {'median', 'mean'}, default 'median'

The median is the default because it is stable under the skew that rate posteriors routinely have.

Returns:

The requested summary, taken analytically when possible.

Return type:

float

predict(*args, **kwargs)[source]

Forecast the next observation, carrying the uncertainty through.

The arguments depend on the analysis: proportion(...).predict(n=100) forecasts successes in the next 100 cases, rate(...).predict( exposure=1) the count over the next unit of exposure, mean(...).predict() one new observation, and regression(...).predict(x=...) the outcome at a new value of the predictor.

Returns:

The forecast, next to the plug-in forecast that ignores the uncertainty in the estimate.

Return type:

Prediction

Raises:

NotImplementedError – If this analysis does not forecast a single quantity.

probability(op='>', value=None)[source]

Posterior probability that the quantity satisfies a comparison.

This is the method that answers the question a planner actually has: not “is there an effect” but “how likely is it that this program cuts filings by at least ten percent”.

Parameters:
op : {'>', '>=', '<', '<=', 'between', 'outside'}, default '>'

Comparison to evaluate.

value : float or tuple of float, optional

Threshold in the quantity’s own units – not the display units. A difference in proportions displayed as “5.7 percentage points” is compared against 0.057. Defaults to direction_reference (0 for comparisons).

Returns:

Posterior probability, computed analytically when an exact posterior is available.

Return type:

float

Examples

>>> import bayesplain as bp
>>> res = bp.compare_proportions([34, 51], [220, 240])
>>> round(res.probability(">", 0), 2)
0.94
probability_of_direction()[source]

Probability the quantity is on the side of zero the data suggest.

Returns:

A value between 0.5 and 1. Read as confidence in the sign of the effect, separately from its size.

Return type:

float

sensitivity(priors=None)[source]

Rerun the analysis under a range of priors and show what moves.

A first-class method rather than an advanced footnote, because prior sensitivity is the strongest legitimate objection to canned Bayesian analysis, and a package that reports it by default converts that objection into a scheduled lecture. No frequentist package has an equivalent – which is not because frequentist methods have no assumptions, only because theirs are not parameters you can vary.

Parameters:
priors : sequence, optional

Prior specifications to try. Defaults to this analysis’s ladder, ordered from least to most constraining.

Returns:

A table of the interval, the direction probability, and the Bayes factor under each prior, plus a verdict on whether the conclusion survived.

Return type:

_Report

Raises:

NotImplementedError – If this analysis cannot be refit under a different prior.

sentence(level=0.95)[source]

One plain-English line, ready to paste into a memo.

Parameters:
level : float, default 0.95

Credible level to quote.

Returns:

A single sentence stating direction, magnitude, and uncertainty.

Return type:

str

Notes

Have students write this sentence themselves before revealing this method. Otherwise the convenience quietly becomes the learning objective.

summary(level=0.95, kind='hdi')[source]

Build the full side-by-side report: posterior first, then its twin.

Parameters:
level : float, default 0.95

Credible and confidence level to report.

kind : {'hdi', 'eti'}, default 'hdi'

Interval type for the Bayesian half.

Returns:

Printable text. Use print(res.summary()) in a script, or let Jupyter display it directly.

Return type:

_Report

to_dict(level=0.95)[source]

Flat dictionary of the headline numbers, for autograding.

Parameters:
level : float, default 0.95

Credible level for the reported interval.

Returns:

Keys are stable across releases; compare with a tolerance.

Return type:

dict

translate(level=0.95)[source]

Set the two frameworks’ claims side by side, in words.

The method behind the final-exam requirement: translate a posterior-based finding into frequentist terms for a skeptical audience who will ask for a p-value, without misstating either one.

Parameters:
level : float, default 0.95

Credible level to quote.

Returns:

Printable text contrasting what the p-value claims with what the posterior claims for this specific data.

Return type:

_Report