bayesplain.teach.grid_posterior¶
-
bayesplain.teach.grid_posterior(grid, prior=
None, likelihood=None, kind='discrete', label='rate')[source]¶ Multiply prior by likelihood over a grid, then divide by the total.
The whole of Bayesian updating, with nothing hidden. Every posterior this package produces is this operation, either done in closed form or done on a finer grid; running it once by hand is what makes the closed forms believable rather than magical.
- Parameters:¶
- grid : array_like¶
The candidate values under consideration. A handful of named hypotheses for a first lesson; a few hundred points to approximate a continuous posterior.
- prior : array_like, optional¶
Relative prior weight on each candidate. Need not sum to 1 – it is normalised here, which is itself worth pointing out. Defaults to flat.
- likelihood : array_like¶
Likelihood of the observed data at each candidate. See
binomial_likelihood()for the common case.- kind : {'discrete', 'continuous'}, default 'discrete'¶
Whether the grid enumerates distinct hypotheses (posterior sums to 1) or approximates a continuous parameter (posterior integrates to 1).
- label : str, default 'rate'¶
What the grid is a grid of, for printed output.
- Returns:¶
Call
.table()to see the arithmetic,.plot()to see the shapes.- Return type:¶
Examples
Four candidate violation rates, and 7 violations found in 20 inspections:
>>> import bayesplain as bp >>> candidates = [0.1, 0.2, 0.3, 0.4] >>> post = bp.teach.grid_posterior( ... grid=candidates, ... likelihood=bp.teach.binomial_likelihood(7, 20, candidates), ... ) >>> float(round(post.posterior.sum(), 10)) 1.0 >>> round(post.mean(), 4) 0.3278A fine grid reproduces the closed form, which is the point of the exercise:
>>> import numpy as np >>> fine = np.linspace(0.001, 0.999, 999) >>> post = bp.teach.grid_posterior( ... grid=fine, ... likelihood=bp.teach.binomial_likelihood(7, 20, fine), ... kind="continuous", ... ) >>> exact = bp.proportion(7, 20).point("mean") >>> abs(post.mean() - exact) < 1e-4 True