马氏链,Metropolis-Hastings采样与Gibbs采样的理解(附有python仿真)

文章目录

马氏链

马氏链,Metropolis-Hastings采样与Gibbs采样的理解(附有python仿真)

MH采样

马氏链,Metropolis-Hastings采样与Gibbs采样的理解(附有python仿真)

代码

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
np.random.seed(42)
# 正态分布
x_=np.linspace(-20,20,100)
y_=stats.norm.pdf(x_,0,5)# 正态分布
# y_=stats.expon(scale=1).pdf(x_)# 指数分布
 
# 采样数10000
Samp_Num=10000
result=[]
init=1
result.append(init)
# p=lambda r:stats.expon(scale=1).pdf(r)# 指数分布
p=lambda r:stats.norm.pdf(r,0,5) # 正态分布
q=lambda v:stats.norm.rvs(loc = v,scale = 2, size = 1)
 
for i in range(Samp_Num):
    y=q(result[i])# 从分布q(y|x_t)中采样
    alpha=min(1,p(y)/p(result[i]))# 接受概率(简化)
    u=np.random.rand(1)# 从uniform(0,1)中采样
    if u<alpha:
        result.append(y[0])# 接受
    else:
        result.append(result[i])# 拒绝
    if i%1000==0:
        print(i)

plt.hist(result, 50, density=1, facecolor='blue', alpha=0.5)
plt.plot(x,raw_y)
plt.show()

马氏链,Metropolis-Hastings采样与Gibbs采样的理解(附有python仿真)

Gibbs采样

马氏链,Metropolis-Hastings采样与Gibbs采样的理解(附有python仿真)

代码

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
def p_x_given_y(y, mus, sigmas):
    mu = mus[0] + sigmas[1, 0] / sigmas[0, 0] * (y - mus[1])
    sigma = sigmas[0, 0] - sigmas[1, 0] / sigmas[1, 1] * sigmas[1, 0]
    return np.random.normal(mu, sigma)


def p_y_given_x(x, mus, sigmas):
    mu = mus[1] + sigmas[0, 1] / sigmas[1, 1] * (x - mus[0])
    sigma = sigmas[1, 1] - sigmas[0, 1] / sigmas[0, 0] * sigmas[0, 1]
    return np.random.normal(mu, sigma)


def gibbs_sampling(mus, sigmas, iter=10000):
    samples = np.zeros((iter, 2))
    y = np.random.rand() * 10

    for i in range(iter):
        x = p_x_given_y(y, mus, sigmas)
        y = p_y_given_x(x, mus, sigmas)
        samples[i, :] = [x, y]

    return samples
mus = np.array([5, 5])
sigmas = np.array([[1, .9], [.9, 1]])
x,y = np.random.multivariate_normal(mus, sigmas, int(1e5)).T
sns.jointplot(x,y,kind='kde')

马氏链,Metropolis-Hastings采样与Gibbs采样的理解(附有python仿真)

samples = gibbs_sampling(mus, sigmas)
sns.jointplot(samples[:, 0], samples[:, 1])

马氏链,Metropolis-Hastings采样与Gibbs采样的理解(附有python仿真)

上一篇:BLE扫描安卓实现


下一篇:Linux环境下无法使用非权威ping问题