Note

Go to the endto download the full example code.

The Bayes update#

This animation displays the posterior estimate updates as it is refitted whennew data arrives.The vertical line represents the theoretical value to which the plotteddistribution should converge.

Output generated viamatplotlib.animation.Animation.to_jshtml.

importmathimportmatplotlib.pyplotaspltimportnumpyasnpfrommatplotlib.animationimportFuncAnimationdefbeta_pdf(x,a,b):return(x**(a-1)*(1-x)**(b-1)*math.gamma(a+b)/(math.gamma(a)*math.gamma(b)))classUpdateDist:def__init__(self,ax,prob=0.5):self.success=0self.prob=probself.line,=ax.plot([],[],'k-')self.x=np.linspace(0,1,200)self.ax=ax# Set up plot parametersself.ax.set_xlim(0,1)self.ax.set_ylim(0,10)self.ax.grid(True)# This vertical line represents the theoretical value, to# which the plotted distribution should converge.self.ax.axvline(prob,linestyle='--',color='black')defstart(self):# Used for the *init_func* parameter of FuncAnimation; this is called when# initializing the animation, and also after resizing the figure.returnself.line,def__call__(self,i):# This way the plot can continuously run and we just keep# watching new realizations of the processifi==0:self.success=0self.line.set_data([],[])returnself.line,# Choose success based on exceed a threshold with a uniform pickifnp.random.rand()<self.prob:self.success+=1y=beta_pdf(self.x,self.success+1,(i-self.success)+1)self.line.set_data(self.x,y)returnself.line,# Fixing random state for reproducibilitynp.random.seed(19680801)fig,ax=plt.subplots()ud=UpdateDist(ax,prob=0.7)anim=FuncAnimation(fig,ud,init_func=ud.start,frames=100,interval=100,blit=True)plt.show()

Tags:component: animationplot-type: line

Total running time of the script: (0 minutes 7.844 seconds)

Gallery generated by Sphinx-Gallery