我一直在阅读Metropolis-Hastings(MH)算法。从理论上讲,我理解算法是如何工作的。现在,我正在尝试使用python实现MH算法。
我遇到了以下notebook。它完全适合我的问题,因为我希望通过直线拟合我的数据,同时考虑到我的数据上的测量误差。我要粘贴我发现难以理解的代码:
# initial m, b
m,b = 2, 0
# step sizes
mstep, bstep = 0.1, 10.
# how many steps?
nsteps = 10000
chain = []
probs = []
naccept = 0
print 'Running MH for', nsteps, 'steps'
# First point:
L_old = straight_line_log_likelihood(x, y, sigmay, m, b)
p_old = straight_line_log_prior(m, b)
prob_old = np.exp(L_old + p_old)
for i in range(nsteps):
# step
mnew = m + np.random.normal() * mstep
bnew = b + np.random.normal() * bstep
# evaluate probabilities
# prob_new = straight_line_posterior(x, y, sigmay, mnew, bnew)
L_new = straight_line_log_likelihood(x, y, sigmay, mnew, bnew)
p_new = straight_line_log_prior(mnew, bnew)
prob_new = np.exp(L_new + p_new)
if (prob_new / prob_old > np.random.uniform()):
# accept
m = mnew
b = bnew
L_old = L_new
p_old = p_new
prob_old = prob_new
naccept += 1
else:
# Stay where we are; m,b stay the same, and we append them
# to the chain below.
pass
chain.append((b,m))
probs.append((L_old,p_old))
print 'Acceptance fraction:', naccept/float(nsteps)
代码简单易行,但我很难理解MH的实现方式。
我的问题出在chain.append
(从底部开始的第三行)。作者正在追加m
和b
是否被接受或拒绝。为什么?他append
不应该只接受接受的分数吗?
答案 0 :(得分:2)
快速阅读算法说明:当候选人被拒绝时,它仍然算作一个步骤,但该值与旧步骤相同。即b, m
以任意一种方式附加,但在候选人被接受的情况下,他们只能更新(到bnew, mnew
)。
答案 1 :(得分:2)
以下R代码说明了捕获被拒绝案例的重要性:
# 20 samples from 0 or 1. 1 has an 80% probability of being chosen.
the.population <- sample(c(0,1), 20, replace = TRUE, prob=c(0.2, 0.8))
# Create a new sample that only catches changes
the.sample <- c(the.population[1])
# Loop though the.population,
# but only copy the.population to the.sample if the value changes
for( i in 2:length(the.population))
{
if(the.population[i] != the.population[i-1])
the.sample <- append(the.sample, the.population[i])
}
当此代码运行时,the.population
会获得20个值,例如:
0 1 1 1 1 1 1 1 1 0 1 1 1 1 0 0 1 1 1 1
此人口中1的概率为16/20或0.8。正是我们预期的概率......
另一方面,只记录变化的样本如下所示:
0 1 0 1 0 1
样品中1的概率为3/6或0.5。
我们正在尝试构建分发,拒绝新值意味着旧值更多可能比新值更高。需要捕获,以便我们的分发正确。