Path: blob/master/deprecated/scripts/bayes_unigauss_2d_pymc3.py
1192 views
# Approximate 2d posterior using PyMc31# https://www.ritchievink.com/blog/2019/06/10/bayesian-inference-how-we-are-able-to-chase-the-posterior/2# We use the same data and model as in posteriorGrid2d.py34import superimport56import numpy as np7import matplotlib.pyplot as plt8from scipy import stats9import pymc3 as pm10import pyprobml_utils as pml11import os1213data = np.array([195, 182])1415# lets create a grid of our two parameters16mu = np.linspace(150, 250)17sigma = np.linspace(0, 15)[::-1]18mm, ss = np.meshgrid(mu, sigma) # just broadcasted parameters19likelihood = stats.norm(mm, ss).pdf(data[0]) * stats.norm(mm, ss).pdf(data[1])20aspect = mm.max() / ss.max() / 321extent = [mm.min(), mm.max(), ss.min(), ss.max()]22# extent = left right bottom top2324prior = stats.norm(200, 15).pdf(mm) * stats.cauchy(0, 10).pdf(ss)25# Posterior - grid26unnormalized_posterior = prior * likelihood27posterior = unnormalized_posterior / np.nan_to_num(unnormalized_posterior).sum()2829plt.figure()30plt.imshow(posterior, cmap='Blues', aspect=aspect, extent=extent)31plt.xlabel(r'$\mu$')32plt.ylabel(r'$\sigma$')33plt.title('Grid approximation')34pml.savefig('bayes_unigauss_2d_grid.pdf')35plt.show()363738with pm.Model():39# priors40mu = pm.Normal('mu', mu=200, sd=15)41sigma = pm.HalfCauchy('sigma', 10)42# likelihood43observed = pm.Normal('observed', mu=mu, sd=sigma, observed=data)44# sample45trace = pm.sample(draws=10000, chains=2, cores=1)4647pm.traceplot(trace);4849plt.figure()50plt.scatter(trace['mu'], trace['sigma'], alpha=0.01)51plt.xlim([extent[0], extent[1]])52plt.ylim([extent[2], extent[3]])53plt.ylabel('$\sigma$')54plt.xlabel('$\mu$')55plt.title('MCMC samples')56pml.savefig('bayes_unigauss_2d_pymc3_post.pdf')57plt.show()585960