Exemple d'implémentation de l'algorithme de Metropolis-Hastings (méthode Markov-Chain Monte Carlo MCMC) avec python. Exemple avec une distribution gaussienne comme postérieure
[image:posterior]
import matplotlib.pyplot as pltimport numpy as npimport math#----------------------------------------------------------------------------------------## define posterior distributiondef posterior(x):mu, sigma = 5, 2.0 # mean and standard deviationnum = math.exp( - ( x - mu )**2 / ( 2.0 * sigma **2 ) )den = math.sqrt( 2 * math.pi * sigma **2)return num / den#----------------------------------------------------------------------------------------## plot posteriorx_array = np.linspace(-5.0, 15.0, 100)y_array = np.asarray( [posterior(x) for x in x_array] )plt.plot(x_array,y_array)plt.grid()plt.title('Metropolis Hastings Posterior')plt.savefig('posterior.png',bbox_inches='tight')plt.show()plt.close()#----------------------------------------------------------------------------------------## Metropolis Hastings sampling from the posterior distributionN = 100000s = 10x = 0p = posterior(x)samples = []for i in xrange(N):xn = x + np.random.normal(size=1)pn = posterior(xn)if pn >= p:p = pnx = xnelse:u = np.random.rand()if u < pn/p:p = pnx = xnif i % s == 0:samples.append(x)samples = np.array(samples)plt.scatter(samples, np.zeros_like(samples), s=10)plt.plot(x_array,y_array)plt.hist(samples, bins=50,normed=1)plt.title('Metropolis Hastings sampling')plt.grid()plt.savefig('metropolis_hastings_1d.png',bbox_inches='tight')plt.show()plt.close()
donne
Recherches associées
| Liens | Site |
|---|---|
| Tiago Ramalho's blog | nehalemlabs.net |
| METROPOLIS-HASTINGS SAMPLER (PYTHON RECIPE) | code.activestate.com |
| Metropolis-Hastings sampling algorithm | youtube |
