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
bayesplainanalysis 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
.labeland.dist().- subject : str, optional¶
How to refer to the quantity inside a running sentence, when the header form does not read well there.
quantitymight be"rate (34 of 220)"whilesubjectis"filing rate". Defaults toquantity.- 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()anddecide()are always in the unscaled units of the quantity itself.- decimals : int, optional¶
Decimal places for display. Defaults to 1 when
display_scaleis 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_referenceis 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
Predictionreturned bypredict(). 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 bysensitivity()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
drawswhen omitted.- notes : sequence of str, optional¶
Warnings or caveats specific to this data, e.g. small cell counts.
Methods
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 standard error of the posterior mean.
plot([kind, threshold, level, ax])Plot the posterior, optionally shaded at a threshold.
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 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:¶
- 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.
-
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
levelprobability the quantity lies in this range.
- 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.
-
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_referencefor 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:¶
- Raises:¶
ImportError – If matplotlib is not installed. Install with
pip install bayesplain[plot].
- 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, andregression(...).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:¶
- 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 todirection_reference(0 for comparisons).
- Returns:¶
Posterior probability, computed analytically when an exact posterior is available.
- Return type:¶
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.
-
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:¶
- Returns:¶
A single sentence stating direction, magnitude, and uncertainty.
- Return type:¶
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.