''' lecture_13_bayesian_updating.py Bayesian updating in globe tossing example with binomial distribution CS251: Data Analysis and Visualization Oliver W. Layton Spring 2019 ''' import numpy as np import scipy.stats as stats import matplotlib.pyplot as plt import sys plt.style.use(['seaborn-colorblind', 'seaborn-darkgrid']) def posterior(p_samps=40, waters=6, tosses=9, prior=None): '''Do one Bayesian update step, corresponding to one toss of the globe.''' # define samples on a regular grid from 0 to 1 p_grid = np.linspace(0, 1, p_samps) # define prior to be uniform on 1st step (all ps equally likely) if prior is None: prior = np.repeat(1, p_samps) # compute binomial probs for every sampled p value binomial_probs = stats.binom.pmf(waters, tosses, p_grid) # multiply with our prior distribution (probs from last toss) post = binomial_probs * prior # normalize so it sums to 1 post_norm = post / np.sum(post) return p_grid, post_norm def main(args): if len(args) < 2: n = 1 print('Using default n value.') print('Usage: python3 lecture_13_bayesian_updating.py <# tosses n>') else: n = int(args[1]) # Data: Number of waters that emerge from each toss (index i) water_counts = [1, 1, 2, 3, 4, 4, 5, 5, 6] # Number of p sample values between 0 and 1 (inclusive) n_p_samps = 40 prior = None # Globe tosses for i in range(n): toss_num = i+1 p_grid, post = posterior(p_samps=n_p_samps, waters=water_counts[i], tosses=toss_num, prior=prior) prior = post plt.plot(p_grid, post, 'o-', label=f'success = {water_counts[i]}\ntosses = {toss_num}') plt.xlabel('probability of water', fontsize=14) plt.ylabel('posterior probability', fontsize=14) plt.title(f'{n} trials') plt.legend() plt.show() if __name__ == '__main__': main(sys.argv)