我正在尝试自我介绍MCMC抽样与主持人。我只想使用github,https://github.com/dfm/emcee/blob/master/examples/quickstart.py上的一组示例代码从Maxwell Boltzmann发行版中获取一个示例。
示例代码确实很好,但是当我将分布从高斯改为Maxwellian时,我收到了错误,TypeError: lnprob()正好有2个参数(3给定)
但是,在没有给出适当参数的任何地方都不会调用它?对于如何定义麦克斯韦曲线并使其符合本示例代码,需要提供一些指导。
这是我所拥有的;
from __future__ import print_function
import numpy as np
import emcee
try:
xrange
except NameError:
xrange = range
def lnprob(x, a, icov):
pi = np.pi
return np.sqrt(2/pi)*x**2*np.exp(-x**2/(2.*a**2))/a**3
ndim = 2
means = np.random.rand(ndim)
cov = 0.5-np.random.rand(ndim**2).reshape((ndim, ndim))
cov = np.triu(cov)
cov += cov.T - np.diag(cov.diagonal())
cov = np.dot(cov,cov)
icov = np.linalg.inv(cov)
nwalkers = 50
p0 = [np.random.rand(ndim) for i in xrange(nwalkers)]
sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=[means, icov])
pos, prob, state = sampler.run_mcmc(p0, 5000)
sampler.reset()
sampler.run_mcmc(pos, 100000, rstate0=state)谢谢
发布于 2017-07-04 15:01:36
我想我看到了几个问题。主要的一点是,主持人希望你给出你想要样本的概率分布函数的自然对数。因此,与其拥有:
def lnprob(x, a, icov):
pi = np.pi
return np.sqrt(2/pi)*x**2*np.exp(-x**2/(2.*a**2))/a**3相反,你会想要的。
def lnprob(x, a):
pi = np.pi
if x < 0:
return -np.inf
else:
return 0.5*np.log(2./pi) + 2.*np.log(x) - (x**2/(2.*a**2)) - 3.*np.log(a)在那里if...else..。语句是显式地表示x的负值具有零概率(或日志空间中的-infinity )。
您也不应该计算icov并将其传递给lnprob,因为在链接到的示例中,只需要计算高斯情况。
当你打电话:
sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=[means, icov])args值应该只是您的lnprob函数所需的任何附加参数,因此在您的示例中,这将是要设置Maxwell-Boltxmann发行版的a值。这应该是一个值,而不是在创建mean时设置的两个随机初始化的值。
总的来说,以下内容应该适用于您:
from __future__ import print_function
import emcee
import numpy as np
from numpy import pi as pi
# define the natural log of the Maxwell-Boltzmann distribution
def lnprob(x, a):
if x < 0:
return -np.inf
else:
return 0.5*np.log(2./pi) + 2.*np.log(x) - (x**2/(2.*a**2)) - 3.*np.log(a)
# choose a value of 'a' for the distributions
a = 5. # I'm choosing 5!
# choose the number of walkers
nwalkers = 50
# set some initial points at which to calculate the lnprob
p0 = [np.random.rand(1) for i in xrange(nwalkers)]
# initialise the sampler
sampler = emcee.EnsembleSampler(nwalkers, 1, lnprob, args=[a])
# Run 5000 steps as a burn-in.
pos, prob, state = sampler.run_mcmc(p0, 5000)
# Reset the chain to remove the burn-in samples.
sampler.reset()
# Starting from the final position in the burn-in chain, sample for 100000 steps.
sampler.run_mcmc(pos, 100000, rstate0=state)
# lets check the samples look right
mbmean = 2.*a*np.sqrt(2./pi) # mean of Maxwell-Boltzmann distribution
print("Sample mean = {}, analytical mean = {}".format(np.mean(sampler.flatchain[:,0]), mbmean))
mbstd = np.sqrt(a**2*(3*np.pi-8.)/np.pi) # std. dev. of M-B distribution
print("Sample standard deviation = {}, analytical = {}".format(np.std(sampler.flatchain[:,0]), mbstd))https://stackoverflow.com/questions/43964707
复制相似问题