欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

M-H Python实现

程序员文章站 2024-02-02 15:03:52
...
import random
from scipy.stats import gamma,rayleigh
import matplotlib.pyplot as plt
def rayleigh_dist_prob(x,a): #提议分布
    y = rayleigh.pdf(x,a)
    return y
def gamma_dist_prob(x): #提议分布
    y = gamma.pdf(x,1,scale=1)
    return y
a=1.9
sigmaf=4
T = 10000#采样次数
pi = [0 for i in range(T)]              #每次采样的结果
sigma = 1                               #转移矩阵分布参数
t = 0
#采样次数初始化
pi[0] =gamma.rvs(a,1, scale=1)
jujue=0
while t < T-1:
    t = t + 1
    # rvs 产生服从指定分布的随机数
    pi[t]  =gamma.rvs(pi[t-1],1,scale=1)
#根据转移矩阵进行采样,从这个分布中抽一些样本
    alpha = min(1,(gamma_dist_prob(pi[t])*rayleigh_dist_prob(pi[t],sigmaf) )/ (rayleigh_dist_prob(pi[t - 1],sigmaf)*gamma_dist_prob(pi[t - 1])))
    u = random.uniform(0, 1)
    if u < alpha:
        pass            # 接受
    else:
        pi[t] = pi[t-1]               # 拒绝
        jujue+=1
#plt.scatter(pi, gamma.pdf(pi,1,scale=1))
num_bins = 50
#plt.hist(pi, num_bins, density=1, facecolor='red', alpha=0.7)
#alpha设置透明度,0为完全透明
#plt.show()
print(jujue)
"""
import random
from scipy.stats import gamma,rayleigh
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.01)
y1 = gamma.pdf(x, 1, scale=1)
y2 = gamma.pdf(x, 1.5, scale=1)
y3 = gamma.pdf(x, 2, scale=1)
plt.plot(x, y1, lw=2, label='$r = 1$')
plt.plot(x, y2, lw=2, label='$r = 1.5$')
plt.plot(x, y3, lw=2, label='$r = 2$')
plt.xlabel('$x$')
plt.title('Gamma $(r, 1)$ Densities');
plt.legend()
plt.show()
"""