''' 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 # 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 # multiply with our prior distribution (probs from last toss) # normalize so it sums to 1 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 = 20 prior = None # Globe tosses for i in range(n): toss_num = i+1 # compute the posterior p_grid, post = posterior(p_samps=n_p_samps, waters=water_counts[i], tosses=toss_num, prior=prior) # set the posterior as the next 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)