Python 为什么回火mcmc配合不好?

Python 为什么回火mcmc配合不好?,python,numpy,curve-fitting,mcmc,emcee,Python,Numpy,Curve Fitting,Mcmc,Emcee,我正在尝试使用并行mcmc将一条简单的直线y=mx+c类型拟合到一些合成数据。我的目标是能够理解如何使用它,以便以后可以应用于一些更复杂的模型。我正在尝试的示例是一个简单的主持人代码中已经完成的工作的副本: 但我不想使用mcmc,而是想使用并行mcmc: 以下是工作代码: import numpy as np from emcee import PTSampler import emcee # Choose the "true" parameters. m_true = -0.9594 b_

我正在尝试使用
并行mcmc
将一条简单的直线
y=mx+c
类型拟合到一些合成数据。我的目标是能够理解如何使用它,以便以后可以应用于一些更复杂的模型。我正在尝试的示例是一个简单的主持人代码中已经完成的工作的副本: 但我不想使用mcmc,而是想使用并行mcmc:

以下是工作代码:

import numpy as np
from emcee import PTSampler
import emcee

# Choose the "true" parameters.
m_true = -0.9594
b_true = 4.294
f_true = 0.534

# Generate some synthetic data from the model.
N = 50
x = np.sort(10*np.random.rand(N))
yerr = 0.1+0.5*np.random.rand(N)
y = m_true*x+b_true
y += np.abs(f_true*y) * np.random.randn(N)
y += yerr * np.random.randn(N)


def lnlike(theta, x, y, yerr):
    m, b, lnf = theta
    model = m * x + b
    inv_sigma2 = 1.0/(yerr**2 + model**2*np.exp(2*lnf))
    return -0.5*(np.sum((y-model)**2*inv_sigma2 - np.log(inv_sigma2)))
def lnprior(theta):
    m, b, lnf = theta
    if -5.0 < m < 0.5 and 0.0 < b < 10.0 and -10.0 < lnf < 1.0:
        return 0.0
    return -np.inf
def lnprob(theta, x, y, yerr):
    lp = lnprior(theta)
    if not np.isfinite(lp):
        return -np.inf
    return lp + lnlike(theta, x, y, yerr)

import scipy.optimize as op
nll = lambda *args: -lnlike(*args)
result = op.minimize(nll, [m_true, b_true, np.log(f_true)], args=(x, y, yerr))
m_ml, b_ml, lnf_ml = result["x"]
init = [0.5, m_ml, b_ml, lnf_ml]

ntemps = 10
nwalkers = 100
ndim = 3
from multiprocessing import Pool
pos = np.random.uniform(low=-1, high=1, size=(ntemps, nwalkers, ndim))
for i in range(ntemps):
    #initialize parameters near scipy optima
    pos[i:,] = np.array([result["x"] + 1e-4*np.random.randn(ndim) for i in range(nwalkers)])
pool = Pool(processes=4)
sampler=PTSampler(ntemps,nwalkers, ndim, lnlike, lnprior, loglargs=(x, y, yerr), pool=pool)# args=(x, y, yerr))
#burn-in 
sampler.run_mcmc(pos, 1000)
sampler.reset()
sampler.run_mcmc(pos, 10000, thin=10)
samples = sampler.chain.reshape((-1, ndim))
print('Number of posterior samples is {}'.format(samples.shape[0]))
#print best fit value together with errors
print(map(lambda v: (v[1], v[2]-v[1], v[1]-v[0]),
                             zip(*np.percentile(samples, [16, 50, 84],
                                                axis=0))))

import corner
fig = corner.corner(samples, labels=["$m$", "$b$", "$\ln\,f$"],
                      truths=[m_true, b_true, np.log(f_true)])
fig.savefig("triangle.png")
将numpy导入为np
从主持人导入PTSampler
进口主持
#选择“true”参数。
m_真=-0.9594
b_真=4.294
f_真=0.534
#从模型生成一些合成数据。
N=50
x=np.sort(10*np.rand.rand(N))
yerr=0.1+0.5*np.random.rand(N)
y=m_真*x+b_真
y+=np.abs(f_真*y)*np.random.randn(N)
y+=yerr*np.random.randn(N)
def lnlike(θ,x,y,yerr):
m、 b,lnf=θ
型号=m*x+b
inv_sigma2=1.0/(yerr**2+型号**2*np.exp(2*lnf))
返回值-0.5*(np.sum((y型)**2*inv_sigma2-np.log(inv_sigma2)))
def lnprior(θ):
m、 b,lnf=θ
如果-5.0
运行这段代码时唯一的问题是我得到的最佳参数值与真实值相差甚远。增加步行者或样本的数量在任何意义上都没有帮助。有人能告诉我为什么mcmc不在这里工作吗

更新:


我发现了一个名为
ptemcee
()的有用包,尽管这个包的文档并不存在。看来这个软件包可能很有用,对于如何使用这个软件包实现相同的线性拟合,我们也非常感谢您的帮助。

我已经修改了一些行

导入时间
将numpy作为np导入
从主持人导入PTSampler
进口角
将matplotlib.pyplot作为plt导入
导入scipy.optimize作为op
t1=时间。时间()
np.random.seed(6)#复制结果
#选择“true”参数。
m_真=-0.9594
b_真=4.294
f_真=0.534
#从模型生成一些合成数据。
N=50
x=np.sort(10*np.rand.rand(N))
yerr=0.1+0.5*np.random.rand(N)
y_1=m_真*x+b_真
y=np.abs(f_真*y_1)*np.randn(N)+y_1
y+=yerr*np.random.randn(N)
plt.绘图(x,y,'o')
#主持人
def lnlike(θ,x,y,yerr):
m、 b,lnf=θ
型号=m*x+b
inv_sigma2=1.0/(yerr**2+型号**2*np.exp(2*lnf))
返回值-0.5*(np.sum((y型)**2*inv_sigma2-np.log(inv_sigma2)))
def lnprior(θ):
m、 b,lnf=θ
如果-5.0
我在
拐角处得到的图形是:

重要的是

sampler=PTSampler(NTEMP、nwalkers、ndim、LNIKE、lnprior、loglargs=(x、y、yerr)、threads=4)
我使用了
threads=4
而不是
Pool

仔细看这一行
print(p1'\n',p2'\n',p3)
,它打印
m_true
b_true
f_true
的值,您可以得到:

(-1.277782877669762,0.5745273177144817,2.0813620981463297)
(4.800481378230051, 3.174735685120116
       mean        sd  mc_error   hpd_2.5  hpd_97.5        n_eff      Rhat
m -0.995545  0.067818  0.001174 -1.123187 -0.857653  2685.610018  1.000121
b  4.398158  0.332526  0.005585  3.767336  5.057909  2746.736563  1.000201
f  0.425442  0.063884  0.000904  0.311037  0.554446  4195.591204  1.000309