API reference

The analyses

Eleven functions, each returning a Result. The frequentist counterpart each one is paired with is named in its own documentation.

proportion(successes, n[, prior, reference, ...])

Estimate one unknown rate from counts.

compare_proportions(successes, n[, prior, ...])

Compare a rate between two groups, or across several.

rate(events[, exposure, reference, prior, ...])

Estimate one rate of events per unit of exposure.

compare_rates(events[, exposure, prior, ...])

Compare the rate of events between two groups.

contingency(table[, prior, scheme, fixed, ...])

Test whether the rows and columns of a table are related.

categories(data[, expected, prior, labels, ...])

Compare how one categorical variable splits against expected shares.

mean(x[, prior, reference, label, unit, ...])

Estimate one unknown average from a sample.

compare_means(x[, y, prior, labels, ...])

Compare the average of two groups.

correlation(x, y[, prior, labels, ...])

Estimate the correlation between two variables.

regression(x, y[, prior, labels, unit, ...])

Estimate how much y changes per unit of x, with one predictor.

compare_groups(data[, by, labels, pool, ...])

Compare the averages of three or more groups.

The result object

Every analysis returns one of these, with the same methods throughout, so the interface learned for one carries over to all of them.

Result(*, quantity, draws[, posterior, ...])

What every bayesplain analysis hands back.

Decision(verdict, rope, interval, ...)

The outcome of comparing a credible interval against a ROPE.

BayesFactor(bf10, bf01, log_bf10, ...)

A Bayes factor, with the caveat it should never be quoted without.

Prediction(*, what, dist[, plug_in, ...])

A forecast of the next observation, with the parameter uncertainty in it.

Priors

Named presets, so nobody has to type a shape parameter to get started, and nobody can hide which assumption they used.

BetaPrior(a, b[, name, rationale])

A Beta prior over a proportion, carrying its own explanation.

ConcentrationPrior(a[, name, rationale])

A symmetric Dirichlet prior over the cells of a contingency table.

EffectSizePrior(scale[, name, rationale])

A Cauchy prior on standardised effect size, for means and correlations.

CorrelationPrior(kappa[, name, rationale])

A stretched-beta prior on a correlation coefficient.

RatePrior(shape[, exposure, name, rationale])

A Gamma prior on a rate of events per unit of exposure.

resolve_proportion(prior)

Turn whatever the user passed as prior= into a BetaPrior.

resolve_table(prior)

Turn whatever the user passed as prior= into a ConcentrationPrior.

resolve_effect_size(prior)

Turn whatever the user passed as prior= into an EffectSizePrior.

resolve_correlation(prior)

Turn whatever the user passed as prior= into a CorrelationPrior.

resolve_rate(prior)

Turn whatever the user passed as prior= into a RatePrior.

from_previous_study(successes, n)

Build a prior from an earlier study's counts.

from_previous_period(events, exposure)

Build a rate prior from an earlier period's count.

describe([prior])

Explain in one line what a prior assumes.

available()

List the preset prior names.

Frequentist twins

The conventional tests, computed and printed alongside every Bayesian result. Usable on their own when you only want the classical answer.

FrequentistTwin(test, statistic_name, ...[, ...])

A conventional test result, with its interpretation attached.

one_proportion(successes, n[, p0, level])

Exact binomial test and Wilson score interval for one proportion.

two_proportions(successes, n[, level, estimand])

Two-proportion chi-square test, with an interval on the chosen estimand.

several_proportions(successes, n)

Chi-square test that three or more groups share one rate.

one_rate(events, exposure, rate0[, level])

Exact Poisson test and exact (Garwood) interval for one rate.

two_rates(events, exposure[, estimand, level])

Exact conditional test comparing two Poisson rates.

chi_square_independence(table[, correction])

Pearson chi-square test of independence for an r x c table.

goodness_of_fit(counts, expected_shares)

Pearson chi-square goodness-of-fit test for one categorical variable.

one_mean(x[, mu0, level])

One-sample t-test and its confidence interval.

two_means(x, y[, equal_var, level])

Two-sample t-test and confidence interval on the difference.

paired_means(x, y[, level])

Paired t-test: a one-sample t-test on the within-pair differences.

correlation(x, y[, level])

Pearson correlation with its p-value and Fisher-z interval.

simple_regression(x, y[, level])

t-test and confidence interval for a least-squares slope.

one_way_anova(groups)

One-way ANOVA F test across three or more groups.

Teaching tools

Pedagogy-only helpers that show a mechanism the analysis functions deliberately hide. Nothing here belongs in a research package; all of it belongs in a first course.

natural_frequencies(base_rate, sensitivity, ...)

Lay out a detection problem as whole counts instead of probabilities.

grid_posterior(grid[, prior, likelihood, ...])

Multiply prior by likelihood over a grid, then divide by the total.

binomial_likelihood(successes, n, grid)

Likelihood of binomial data at each candidate rate on a grid.

sequential(outcomes[, step, prior, level, label])

Recompute the posterior after each chunk of incoming data.

precision_planning(target_width[, ...])

Find the sample size that makes an interval narrow enough to act on.

precision_planning_mean(target_width, sd[, ...])

Find the sample size that pins down an average, or a difference.

NaturalFrequencies(table, n, base_rate, ...)

A 2x2 grid of whole counts, and what it implies.

GridPosterior(grid, prior, likelihood, ...)

Prior, likelihood, and posterior over a grid, with the arithmetic shown.

SequentialUpdate(checkpoints, successes[, ...])

The posterior after each successive chunk of data.

PrecisionPlan(required_n, target_width, ...)

How much data a target precision requires.

Datasets

available()

List the datasets shipped with the package.

describe([name])

Explain what a dataset holds and which analyses it suits.

load(name)

Load a shipped dataset by name.

load_collisions()

Load traffic collisions for Los Angeles and San Diego counties.

load_tracts()

Load ACS estimates for Los Angeles County census tracts.

load_blockgroups()

Load ACS estimates for Los Angeles County block groups.

load_parcels()

Load Baltimore residential parcels with assessed values.

Configuration

get_seed()

Return the current default seed.

set_seed(seed)

Set the default seed for every subsequent analysis.

get_draws()

Return the current default number of posterior draws.

set_draws(n_draws)

Set the default number of posterior draws.

Core mathematics

Layer 0: pure functions, no objects, no printing, nothing that knows it is being used to teach. Documented because the derivations belong somewhere readable, and because a methods audience will want to check them.

Proportions

posterior(successes, n[, a, b])

Exact Beta posterior for an unknown proportion.

draws(successes, n[, a, b, size, rng])

Draw independent samples from the exact Beta posterior.

log_marginal_likelihood(successes, n[, a, b])

Log marginal likelihood of binomial data under a Beta prior.

log_bayes_factor_point_null(successes, n[, ...])

Log Bayes factor comparing an unknown rate against a fixed value.

prior_predictive_mean([a, b])

Mean of a Beta(a, b) prior, i.e. the rate expected before data.

validate_counts(successes, n)

Check that a successes/trials pair describes a possible experiment.

Rates

posterior(events, exposure[, a, b])

Exact Gamma posterior for one rate.

ratio_posterior(events1, exposure1, events2, ...)

Exact posterior for the ratio of two rates, group 2 over group 1.

predictive(events, exposure[, new_exposure, ...])

Posterior predictive distribution of the count over a new exposure.

log_marginal_likelihood(events, exposure[, a, b])

Log marginal likelihood of a count under a proper Gamma prior.

log_bayes_factor_point_null(events, ...[, a, b])

Log Bayes factor for "the rate is unknown" against "it equals rate0".

log_bayes_factor_equal_rates(events1, ...[, ...])

Log Bayes factor for "the two rates differ" against "they are equal".

validate_events(events, exposure)

Check that an events/exposure pair describes something observable.

Contingency tables and categories

log_bayes_factor_independence(table[, ...])

Log Bayes factor for association against independence.

posterior_cell_draws(table[, concentration, ...])

Draw whole tables of cell probabilities from the Dirichlet posterior.

log_bayes_factor_goodness_of_fit(counts, ...)

Log Bayes factor for "the shares are unknown" against fixed shares.

cramers_v(prob_tables)

Cramer's V for one or many tables of probabilities.

cohens_w(share_draws, expected_shares)

Cohen's w for one or many vectors of category shares.

log_odds_ratio(prob_tables)

Log odds ratio of a 2x2 table of probabilities, or a stack of them.

log_multivariate_beta(alpha)

Log of the Dirichlet normalising function.

validate_table(table)

Check that an array is a usable table of counts.

Means

mean_posterior(n, mean, sd)

Exact Student-t posterior for one unknown mean.

pooled_difference_posterior(n1, mean1, sd1, ...)

Exact Student-t posterior for a difference of means, equal variances.

difference_draws(n1, mean1, sd1, n2, mean2, sd2)

Draw the difference of two means without assuming equal variances.

log_bayes_factor_ttest(t, n_effective, df[, ...])

Log JZS Bayes factor for a t statistic.

summarise(x[, name])

Reduce a sample to the three numbers every later step needs.

validate_sample(x[, name])

Check that a sample is usable, dropping missing values.

Correlation

log_sampling_density(r, rho, n)

Log density of an observed correlation given the true one.

log_prior_density(rho[, kappa])

Log density of the stretched-beta prior on a correlation.

posterior_on_grid(r, n[, kappa, points])

Evaluate and normalise the posterior over the true correlation.

log_bayes_factor(r, n[, kappa, points])

Log Bayes factor for a real correlation against no correlation.

rho_grid(r, n[, points])

Build a grid over (-1, 1) that resolves a sharply peaked posterior.

validate_pair(x, y)

Check two paired samples and drop rows where either value is missing.

Regression

fit_line(x, y)

Fit a least-squares line, dropping rows where either value is missing.

LineFit(n, slope, intercept, residual_sd, ...)

The sufficient statistics of a least-squares line.

slope_posterior(fit)

Exact Student-t posterior for the slope.

mean_response_posterior(fit, x0)

Exact posterior for the average outcome at x0.

predictive(fit, x0)

Posterior predictive distribution of one new outcome at x0.

log_bayes_factor_slope(fit[, scale])

Log Zellner-Siow Bayes factor for "the slope is not zero".

Partial pooling

shrink(means, standard_errors)

Pull group means toward the overall average, in proportion to noise.

shrink_proportions(successes, n)

Pull group rates toward the typical rate, by empirical-Bayes beta-binomial.

between_group_variance(means, standard_errors)

Estimate the spread between true group means, by DerSimonian-Laird.

Summarising a posterior

interval([draws, level, kind, dist])

Posterior interval, taken analytically when that is possible.

hdi_from_draws(draws[, level])

Highest-density interval from posterior draws.

eti_from_draws(draws[, level])

Equal-tailed interval from posterior draws.

probability_from_draws(draws, op, value)

Posterior probability that a quantity satisfies a comparison.

monte_carlo_se(draws)

Compute the standard error of a posterior mean from i.i.d.

Grid approximation

normalize_log_density(log_density, grid)

Turn an unnormalised log density on a grid into a proper density.

sample_from_grid(density, grid[, size, rng])

Sample from a grid-approximated posterior by inverting its CDF.

grid_mean(density, grid)

Posterior mean by numerical integration on a grid.

grid_quantile(density, grid, q)

Quantiles of a grid-approximated posterior.