2021-06-01 贝叶斯 Python

image.png
# -*- coding: utf-8 -*-
"""
Created on Tue Jun  1 03:42:19 2021

@author: Quan Wang(Sunny)
"""

import scipy.stats as stats 
import numpy as np 
import matplotlib.pyplot as plt 

dist = stats.beta 
n_trials = [0, 1, 2, 3, 5, 8, 15, 50,500]
print(n_trials)
data = stats.bernoulli.rvs(0.5, size = n_trials[-1])
print(n_trials[-1])
print(data)
x = np.linspace(0,1,100)

# print(enumerate(n_trials))

for k, N in enumerate(n_trials):
    sx =plt.subplot(len(n_trials)/2, 2, k+1)
    # plt.xlabel("$p$, probability of heads") if k in [0,len(n_trials)-1]
    plt.setp(sx.get_yticklabels(), visible=False)
    heads = data[:N].sum()
    y = dist.pdf(x, 1 + heads, 1 + N - heads )
    plt.plot( x, y, label= "observe %d tosses,\n %d heads"%(N,heads) )
    plt.fill_between( x, 0, y, color="#348ABD", alpha = 0.4 )
    plt.vlines( 0.5, 0, 4, color = "k", linestyles = "--", lw=1 )
    leg = plt.legend()
    leg.get_frame().set_alpha(0.4)
    plt.autoscale(tight = True)
    
plt.suptitle("Bayesian updating of posterior probalilities", y= 1.02, fontsize= 14);
plt.tight_layout()

你可能感兴趣的:(2021-06-01 贝叶斯 Python)