【问题标题】:Estimating the Posterior Predictive in Regression估计回归中的后验预测
【发布时间】:2014-04-06 15:24:46
【问题描述】:

假设我有一组随机的 X,Y 点:

x = np.array(range(0,50))
y = np.random.uniform(low=0.0, high=40.0, size=200)
y = map((lambda a: a[0] + a[1]), zip(x,y))
plt.scatter(x,y)

假设我使用线性回归x的每个值将y建模为高斯,我如何估计posterior predictive,即p(y|x) 对于x 的每个(可能)值?

pymcscikit-learn 有直接的方法吗?

【问题讨论】:

  • 你知道如何手工完成吗?

标签: python scipy scikit-learn statsmodels pymc


【解决方案1】:

如果我正确理解您想要什么,您可以使用 git 版本的 PyMC (PyMC3) 和 glm 子模块来执行此操作。 例如

import numpy as np
import pymc as pm
import matplotlib.pyplot as plt 
from pymc import glm 

## Make some data
x = np.array(range(0,50))
y = np.random.uniform(low=0.0, high=40.0, size=50)
y = 2*x+y
## plt.scatter(x,y)

data = dict(x=x, y=y)
with pm.Model() as model:
    # specify glm and pass in data. The resulting linear model, its likelihood and 
    # and all its parameters are automatically added to our model.
    pm.glm.glm('y ~ x', data)
    step = pm.NUTS() # Instantiate MCMC sampling algorithm
    trace = pm.sample(2000, step)


##fig = pm.traceplot(trace, lines={'alpha': 1, 'beta': 2, 'sigma': .5});## traces
fig = plt.figure()
ax = fig.add_subplot(111)
plt.scatter(x, y, label='data')
glm.plot_posterior_predictive(trace, samples=50, eval=x,
                              label='posterior predictive regression lines')

得到这样的东西

您应该会发现这些博客文章很有趣: 12 我从那里得到这些想法。

编辑 要获取每个 x 的 y 值,请尝试使用我从 glm 源中获得的。

lm = lambda x, sample: sample['Intercept'] + sample['x'] * x ## linear model
samples=50 ## Choose to be the same as in plot call
trace_det = np.empty([samples, len(x)]) ## initialise
for i, rand_loc in enumerate(np.random.randint(0, len(trace), samples)):
    rand_sample = trace[rand_loc]
    trace_det[i] = lm(x, rand_sample)
y = trace_det.T
y[0]

抱歉,如果它不是最优雅的 - 希望你能遵循逻辑。

【讨论】:

  • 谢谢!我对获取y[0], y[1], ... y[50] 的样本特别感兴趣(即每个y[i] 的样本向量)。你知道我怎么能得到它吗?
  • 要清楚,对于 x 的每个值,您想要 50 y 值?
  • 是的 - 这是正确的(即我正在寻找的应该是确定性的有效痕迹)。
  • 据我所见,已经实现了确定性的跟踪(参见此处:github.com/pymc-devs/pymc/issues/192),但我不知道如何使用它,例如在这个例子中
  • 我已经进行了编辑 - 如果您想要这样做,请告诉我。
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2020-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-01
  • 2021-10-20
相关资源
最近更新 更多