python - 估计回归中的后验预测

标签 python scipy scikit-learn statsmodels pymc

假设我有一组随机的 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)

enter image description here

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

是否有使用 pymcscikit-learn 的直接方法?

最佳答案

如果我正确理解您的需求,您可以使用 PyMC (PyMC3) 的 git 版本和 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')

得到这样的东西posterior predictive

您应该会发现这些博文很有趣: 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]

如果不是最优雅的,我们深表歉意 - 希望您能遵循逻辑。

关于python - 估计回归中的后验预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22183035/

相关文章:

python - 被 GradientBoostingClassifier 的 apply 函数搞糊涂了

python - 这个 "score"到底是什么?使用 sklearn/Python 的额外树分类器

python - 为 python 安装 mysqldb

python - Scipy 稀疏矩阵在余弦相似度方面内存效率不高

python - 如何将 pandas df 写入具有多个空格的文本

python - 根据复杂条件选择和重新分配数组中元素的最快方法

image - 如何在 tensorflow 图中使用另一个库?

python - 一些数据的Scipy拟合多项式模型

python - Matplotlib 绘制带渐变填充的三角形

python - 为什么打印 my_list[10 :0:-1] stop with the second item rather than the first item in Python?