因此,假设我有以下二维目标分布,我想从其中进行采样(双变量正态分布的混合)-
import numba
import numpy as np
import scipy.stats as stats
import seaborn as sns
import pandas as pd
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
%matplotlib inline
def targ_dist(x):
target = (stats.multivariate_normal.pdf(x,[0,0],[[1,0],[0,1]])+stats.multivariate_normal.pdf(x,[-6,-6],[[1,0.9],[0.9,1]])+stats.multivariate_normal.pdf(x,[4,4],[[1,-0.9],[-0.9,1]]))/3
return target和下面的建议分布(双变量随机游走)-
def T(x,y,sigma):
return stats.multivariate_normal.pdf(y,x,[[sigma**2,0],[0,sigma**2]])下面是Metropolis Hastings在每次迭代中更新“整个”状态的代码:
#Initialising
n_iter = 30000
# tuning parameter i.e. variance of proposal distribution
sigma = 2
# initial state
X = stats.uniform.rvs(loc=-5, scale=10, size=2, random_state=None)
# count number of acceptances
accept = 0
# store the samples
MHsamples = np.zeros((n_iter,2))
# MH sampler
for t in range(n_iter):
# proposals
Y = X+stats.norm.rvs(0,sigma,2)
# accept or reject
u = stats.uniform.rvs(loc=0, scale=1, size=1)
# acceptance probability
r = (targ_dist(Y)*T(Y,X,sigma))/(targ_dist(X)*T(X,Y,sigma))
if u < r:
X = Y
accept += 1
MHsamples[t] = X然而,我想在每次迭代中更新“每个组件”(即组件方式的更新)。有没有简单的方法可以做到这一点?
谢谢你的帮助!
发布于 2017-07-19 06:17:59
从你问题的语气来看,我假设你正在寻找性能改进。MonteCarlo算法是计算密集型的。如果你在比python这样的解释型语言更低的层次上执行算法,你会得到更好的结果,例如编写一个c扩展。
也有适用于python (PyStan,PyMC3)的实现。
https://stackoverflow.com/questions/45176701
复制相似问题