#coding=utf-8'''
Created on 2016年9月14日
基本MCMC算法以及M-H算法的python實現(xiàn)
@author: whz
p:輸入的概率分布,離散情況采用元素為概率值的數(shù)組表示
N:認為迭代N次馬爾可夫鏈收斂
Nlmax:馬爾可夫鏈收斂后又取的服從p分布的樣本數(shù)
isMH:是否采用MH算法,默認為True
'''from __future__ import division
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from array import array
defmcmc(p,N=10000,Nlmax=10000,isMH=True):A = np.array([[1.0 / len(p) for x in range(len(p))] for y in range(len(p))], dtype=np.float64) X0 = np.random.randint(len(p))count = 0samplecount = 0L = array("d",[X0])l = array("d")whileTrue:X = L[samplecount]cur = np.argmax(np.random.multinomial(1,A[X]))count += 1if isMH:a = (p[cur]*A[cur][X])/(p[X]*A[X][cur])alpha = min(a,1)else:alpha = p[cur]*A[cur][X]u = np.random.uniform(0,1) if u<alpha:samplecount += 1L.append(cur)if count>N:l.append(cur)if len(l)>=Nlmax:breakelse:continueLa = np.frombuffer(L)la = np.frombuffer(l)return La,la
defcount(q,n):L = array("d")l1 = array("d")l2 = array("d")for e in q:L.append(e)for e in range(n):l1.append(L.count(e))for e in l1:l2.append(e/sum(l1))return l1,l2p = np.array([0.9,0.05,0.05])
a = mcmc(p,Nlmax=10000000)[1]
l1 = ['state%d'% x for x in range(len(p))]
plt.pie(count(a,len(p))[0],labels=l1,labeldistance=0.3,autopct='%1.2f%%')
plt.title("sampling")
plt.show()