Advertisement
nlw

Metropolis-Hastings generation of Gaussian samples

nlw
Oct 27th, 2012
407
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. ## Metropolis algorithm demonstration. This program generates a number
  2. ## of samples from the gaussian distribution, using the uniform
  3. ## distribution to produce the underlying Markov chain.
  4. ##
  5. ## by Nicolau Werneck <nwerneck@gmail.com>, 2012-10-27
  6.  
  7. import sys
  8. from pylab import *
  9. from scipy import random, special
  10.  
  11. def pdf(x):
  12.     return exp(-x**2)
  13.  
  14.  
  15. if __name__=='__main__':
  16.     ## Number of samples to generate.
  17.     Ttot = 10000
  18.  
  19.     ## Initial state.
  20.     x = 0
  21.     f_x = pdf(x)
  22.     ## Scale parameter of uniform distribution.
  23.     s = float(sys.argv[1])
  24.  
  25.     ## Vector to store the output.
  26.     chain = zeros(Ttot)
  27.     chain[0] = x
  28.  
  29.     ## Number of misses
  30.     miss = 0
  31.     ## Start the loop to produce each sample of the chain.
  32.     for t in range(1,Ttot):
  33.         y = x + s * random.uniform(-s,s)
  34.         f_y = pdf(y)
  35.         alpha = 1.0 if f_y > f_x else f_y/f_x
  36.         if alpha > 1.0 or (random.uniform() < alpha):
  37.             ## Make the transition.
  38.             x = y
  39.             f_x = f_y
  40.         else:
  41.             ## The trial was not accepted. Stay at the same state,
  42.             ## and increment the "miss" counter.
  43.             miss += 1
  44.         ## Store current state.
  45.         chain[t] = x
  46.  
  47.     mu = mean(chain)
  48.     sig2 = var(chain)
  49.     acorr = sum((chain[1:]-mu)*(chain[:-1]-mu)) / sig2 / Ttot
  50.  
  51.     ## K-S test
  52.     sc = sort(chain)
  53.     xx = mgrid[-5:5.01:0.01]
  54.     yy = mgrid[0.0:Ttot]/(Ttot-1)
  55.  
  56.     KS = max(abs(yy - (special.erf(sc)+1)/2))
  57.  
  58.     ion()
  59.     figure(1, figsize=(5,7))
  60.     subplot(211)
  61.     plot(chain)
  62.     title('s=%.2f / miss:%d acorr:%.2f KS:%.2f'%(s, miss, acorr, KS))
  63.     ylim(-3,3)
  64.  
  65.     subplot(212)
  66.     plot(xx,(special.erf(xx)+1)/2, 'k--')
  67.     plot(sc, yy, 'r-')
  68.     xlim(-3,3)
  69.     grid()
  70.  
  71.     suptitle('MCMC Gaussian sampling')
  72.  
  73.     savefig('s-%.2f.png'%s)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement