Created
October 9, 2021 16:19
-
-
Save javipus/9cbdbd42484660adec70c86e4da735c9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import pandas as pd | |
import matplotlib.pyplot as plt | |
from scipy.stats import beta as beta_dist | |
def credible_interval(t, f, prob=.5, prior='uniform'): | |
"""Calculates posterior credible interval for a beta-binomial model with prior `Beta(a, b)` after `t` successes in `t+f` trials. | |
@param t: Number of successes. | |
@param f: Number of failures. | |
@param prob: Probability mass inside the posterior interval. | |
@param prior: Either a tuple (a, b) parametrizing the Beta prior or one of "uniform" (a=b=1) or "jeffreys" (a=b=1/2). | |
@returns Credible interval bounds as a tuple `(lower, upper)`. | |
""" | |
if prior == 'uniform': | |
a, b = 1, 1 | |
elif prior == 'jeffreys': | |
a, b = .5, .5 | |
else: | |
a, b = prior | |
# NB: Beta(a, b) and Binom(k, n) yield the same CDF for the continuous parameter between (0, 1) (the probability) when a=k+1 and b=n-k+1 | |
ppf = beta_dist(a+t, b+f).ppf | |
lo = (1 - prob) / 2 | |
hi = lo + prob | |
return ppf(lo), ppf(hi) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment