【发布时间】:2018-05-01 22:01:59
【问题描述】:
我在使用 emcee 时遇到问题。它是一个足够简单的 3 参数拟合,但偶尔(尽管使用很多,但仅在两种情况下发生)我的助行器烧得很好,但然后不动(见下图)。报告的接受分数为 0。
以前有没有其他人遇到过这个问题?我尝试改变我的初始条件以及步行者和迭代的数量等。这段代码在非常相似的数据集上运行良好。它不是一个具有挑战性的参数空间,步行者似乎不太可能“卡住”。
有什么想法吗?我被难住了……我的步行者似乎很懒……
下面的示例代码(和sample data file)。这个代码+数据文件在我运行时失败。
`
import numpy as n
import math
import pylab as py
import matplotlib.pyplot as plt
import scipy
from scipy.optimize import curve_fit
from scipy import ndimage
import pyfits
from scipy import stats
import emcee
import corner
import scipy.optimize as op
import matplotlib.pyplot as pl
from matplotlib.ticker import MaxNLocator
def sersic(x, B,r_s,m):
return B * n.exp(-1.0 * (1.9992*m - 0.3271) * ( (x/r_s)**(1.0/m) - 1.))
def lnprior(theta):
B,r_s,m, lnf = theta
if 0.0 < B < 500.0 and 0.5 < m < 10. and r_s > 0. and -10.0 < lnf < 1.0:
return 0.0
return -n.inf
def lnlike(theta, x, y, yerr): #"least squares"
B,r_s,m, lnf = theta
model = sersic(x,B, r_s, m)
inv_sigma2 = 1.0/(yerr**2 + model**2*n.exp(2*lnf))
return -0.5*(n.sum((y-model)**2*inv_sigma2 - n.log(inv_sigma2)))
def lnprob(theta, x, y, yerr):#kills based on priors
lp = lnprior(theta)
if not n.isfinite(lp):
return -n.inf
return lp + lnlike(theta, x, y, yerr)
profile=open("testprofile.dat",'r') #read in the data file
profilelines=profile.readlines()
x=n.empty(len(profilelines))
y=n.empty(len(profilelines))
yerr=n.empty(len(profilelines))
for i,line in enumerate(profilelines):
col=line.split()
x[i]=col[0]
y[i]=col[1]
yerr[i]=col[2]
# Find the maximum likelihood value.
chi2 = lambda *args: -2 * lnlike(*args)
result = op.minimize(chi2, [50,2.0,0.5,0.5], args=(x, y, yerr))
B_ml, rs_ml,m_ml, lnf_ml = result["x"]
print("""Maximum likelihood result:
B = {0}
r_s = {1}
m = {2}
""".format(B_ml, rs_ml,m_ml))
# Set up the sampler.
ndim, nwalkers = 4, 4000
pos = [result["x"] + 1e-4*n.random.randn(ndim) for i in range(nwalkers)]
sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(x, y, yerr))
# Clear and run the production chain.
print("Running MCMC...")
Niter = 2000 #2000
sampler.run_mcmc(pos, Niter, rstate0=n.random.get_state())
print("Done.")
# Print out the mean acceptance fraction.
af = sampler.acceptance_fraction
print "Mean acceptance fraction:", n.mean(af)
# Plot sampler chain
pl.clf()
fig, axes = pl.subplots(3, 1, sharex=True, figsize=(8, 9))
axes[0].plot(sampler.chain[:, :, 0].T, color="k", alpha=0.4)
axes[0].yaxis.set_major_locator(MaxNLocator(5))
axes[0].set_ylabel("$B$")
axes[1].plot(sampler.chain[:, :, 1].T, color="k", alpha=0.4)
axes[1].yaxis.set_major_locator(MaxNLocator(5))
axes[1].set_ylabel("$r_s$")
axes[2].plot(n.exp(sampler.chain[:, :, 2]).T, color="k", alpha=0.4)
axes[2].yaxis.set_major_locator(MaxNLocator(5))
axes[2].set_xlabel("step number")
fig.tight_layout(h_pad=0.0)
fig.savefig("line-time_test.png")
# plot MCMC fit
burnin = 100
samples = sampler.chain[:, burnin:, :3].reshape((-1, ndim-1))
B_mcmc, r_s_mcmc, m_mcmc = map(lambda v: (v[0]),
zip(*n.percentile(samples, [50],
axis=0)))
print("""MCMC result:
B = {0}
r_s = {1}
m = {2}
""".format(B_mcmc, r_s_mcmc, m_mcmc))
pl.close()
# Make the triangle plot.
burnin = 50
samples = sampler.chain[:, burnin:, :3].reshape((-1, ndim-1))
fig = corner.corner(samples, labels=["$B$", "$r_s$", "$m$"])
fig.savefig("line-triangle_test.png")
【问题讨论】:
-
我们需要看到minimal reproducible example。这包括示例数据和在示例数据上运行时重现问题的可运行代码。如果看不到您正在运行的内容,我们将无法对此进行调试。
-
我添加了一个示例 - 它有点笨拙且冗长,但如果我简化所有内容,那么它运行得很好并且没有问题...... :(
-
您从您执行的卡方最小化 (
op.minimize) 中获得了什么样的参数值?当我尝试您的示例时,返回的值非常大(以千计),这意味着初始步行者位置确实远远超出了您设置的先前范围。看看如果你刚开始步行者,他们从先前的边界(或这些边界内的一些小球)均匀地被拉出来,会发生什么。 -
您可能还想确保只保留有限概率的样本,例如
idx = n.isfinite(sampler.lnprobability[:,burnin:].reshape((Niter-burnin)*nwalkers)); newsamps = samples[idx,:],并通过计算每个参数的 autocorrelation times 来查看细化样本,例如from emcee.autocorr import integrated_time; acls = []; for samps in newsamps.T: acls.append(integrated_time(samps)); newsamps = newsamps[0:-1:int(n.max(acls)),:]