使用PyMC3执行贝叶斯线性回归。我构建了我的模型,我想使用相同的模型预测新X值的后验。我一直在尝试按照文档网站上的说明进行操作:https://pymc-devs.github.io/pymc3/notebooks/posterior_predictive.html(参见预测)。这包括在分析之前使您的X值成为theano共享变量,然后在模型构建之后更改值,并运行run_ppc()
。我只是作为一个例子运行了200次迭代(我为实际分析运行了很多)。
X1_shared = theano.shared(final_df['poll_diff'].values)
Y1 = final_df['rd_diff'].values
basic_model = pm.Model()
with basic_model:
# Priors for unknown model parameters
sigma = HalfCauchy('sigma', beta=10, testval=1.)
intercept = Normal('Intercept', 0, sd=20)
x_coeff = Normal('x', 0, sd=20)
# Define likelihood
likelihood = Normal('y', mu=intercept + x_coeff * X1_shared,
sd=sigma, observed= Y1)
#start = find_MAP()
start = find_MAP() # Find starting value by optimization
step = NUTS(scaling=start) # Instantiate MCMC sampling algorithm
trace = sample(200, step, start=start)
pm.traceplot(trace)
plt.show()
sns.lmplot(x="poll_diff", y="rd_diff", data=final_df, size=10)
x = np.array(range(-1, 2))
pm.glm.plot_posterior_predictive(trace, samples=100, eval=x)
plt.show()
X1_shared.set_value(ana_2016_df['poll_diff'].values)
ppc = pm.sample_ppc(trace, model=model, samples=100)
但是我收到以下错误:
AttributeError Traceback (most recent call last)
<ipython-input-73-9c1eb48d987f> in <module>()
----> 1 ppc = pm.sample_ppc(trace, model=model, samples=100)
C:\Users\W\Anaconda3\lib\site-packages\pymc3\sampling.py in sample_ppc(trace, samples, model, vars, size, random_seed)
349
350 if vars is None:
--> 351 vars = model.observed_RVs
352
353 seed(random_seed)
AttributeError: module 'pymc3.model' has no attribute 'observed_RVs'
值得注意的是,如果我使用patsy表示法版本而不更改变量,则不会弹出此错误,但我不知道patsy格式如何接受theano共享变量。因此,解决方案可以解决我的错误消息,或者展示如何将theano共享变量引入到模型的patsy版本中。谢谢!
答案 0 :(得分:2)
正如aloctavodia所指出的,这是设置变量时的一个简单错误。在ppc = pm.sample_ppc(trace, model=model, samples=100)
中,model
应为model = basic_model