PyMC3的接受率(Metropolis-Hastings)

时间:2017-12-30 18:28:01

标签: pymc3

有谁知道我怎样才能看到PyMC3(Metropolis-Hastings)的最终接受率?或者一般来说,我怎样才能看到pymc3.sample()返回的所有信息?

由于

2 个答案:

答案 0 :(得分:1)

举个例子,首先建立模型:

import pymc3 as pm3

sigma = 3 # Note this is the std of our data
data = norm(10,sigma).rvs(100)
mu_prior = 8
sigma_prior = 1.5  # Note this is our prior on the std of mu

plt.hist(data,bins=20)
plt.show()

basic_model = pm3.Model()

with basic_model:
    # Priors for unknown model parameters
    mu = pm3.Normal('Mean of Data',mu_prior,sigma_prior)
    # Likelihood (sampling distribution) of observations
    data_in = pm3.Normal('Y_obs', mu=mu, sd=sigma, observed=data)

其次,进行模拟:

chain_length = 10000 

with basic_model:
    # obtain starting values via MAP
    startvals = pm3.find_MAP(model=basic_model)
    # instantiate sampler
    step = pm3.Metropolis() 
    # draw 5000 posterior samples
    trace = pm3.sample(chain_length, step=step, start=startvals)

使用上面的例子,接受率可以这样计算:

accept = np.sum(trace['Mean of Data'][1:] != trace['Mean of Data'][:-1])
print("Acceptance Rate: ", accept/trace['Mean of Data'].shape[0])

(我在一个在线教程中找到了这个解决方案,但我不太明白。)

参考:Introduction to PyMC3

答案 1 :(得分:0)

让step = pymc3.Metropolis()成为我们的采样器,我们可以通过

获得最终验收率

" step.accepted"

对于像我这样的初学者(pymc3),在每个变量/ obj之后。放一个"。"并按Tab键;你会看到一些有趣的建议;)