在专门使用emcee多年之后,我最近开始学习pymc3,我遇到了一些概念上的问题。
我正在练习Hogg's Fitting a model to data的第7章。这涉及到mcmc拟合到具有任意2d不确定性的直线。我用emcee很容易就做到了这一点,但是pymc给我带来了一些问题。
它本质上归结为使用多变量高斯似然。
这是我到目前为止所拥有的。
from pymc3 import *
import numpy as np
import matplotlib.pyplot as plt
size = 200
true_intercept = 1
true_slope = 2
true_x = np.linspace(0, 1, size)
# y = a + b*x
true_regression_line = true_intercept + true_slope * true_x
# add noise
# here the errors are all the same but the real world they are usually not!
std_y, std_x = 0.1, 0.1
y = true_regression_line + np.random.normal(scale=std_y, size=size)
x = true_x + np.random.normal(scale=std_x, size=size)
y_err = np.ones_like(y) * std_y
x_err = np.ones_like(x) * std_x
data = dict(x=x, y=y)
with Model() as model: # model specifications in PyMC3 are wrapped in a with-statement
# Define priors
intercept = Normal('Intercept', 0, sd=20)
gradient = Normal('gradient', 0, sd=20)
# Define likelihood
likelihood = MvNormal('y', mu=intercept + gradient * x,
tau=1./(np.stack((y_err, x_err))**2.), observed=y)
# start the mcmc!
start = find_MAP() # Find starting value by optimization
step = NUTS(scaling=start) # Instantiate MCMC sampling algorithm
trace = sample(2000, step, start=start, progressbar=False) # draw 2000 posterior samples using NUTS sampling这会引发错误:LinAlgError: Last 2 dimensions of the array must be square
因此,我尝试将x和y的测量值(mus)及其相关的测量不确定性(y_err和x_err)传递给MvNormal。但它似乎不喜欢2d tau的论点。
有什么想法吗?这必须是可能的
谢谢
发布于 2016-09-25 17:38:22
您可以尝试采用以下模型。是一种“常规”线性回归。但是x和y已经被高斯分布所取代。在这里,我不仅假设输入和输出变量的测量值,而且还假设它们的误差的可靠估计(例如,由测量设备提供)。如果您不信任这些错误值,则可以尝试从数据中估计它们。
with pm.Model() as model:
intercept = pm.Normal('intercept', 0, sd=20)
gradient = pm.Normal('gradient', 0, sd=20)
epsilon = pm.HalfCauchy('epsilon', 5)
obs_x = pm.Normal('obs_x', mu=x, sd=x_err, shape=len(x))
obs_y = pm.Normal('obs_y', mu=y, sd=y_err, shape=len(y))
likelihood = pm.Normal('y', mu=intercept + gradient * obs_x,
sd=epsilon, observed=obs_y)
trace = pm.sample(2000)如果你从数据中估计误差,那么可以合理地假设它们可能是相关的,因此,你可以使用多变量高斯而不是两个单独的高斯。在这种情况下,您将得到如下所示的模型:
df_data = pd.DataFrame(data)
cov = df_data.cov()
with pm.Model() as model:
intercept = pm.Normal('intercept', 0, sd=20)
gradient = pm.Normal('gradient', 0, sd=20)
epsilon = pm.HalfCauchy('epsilon', 5)
obs_xy = pm.MvNormal('obs_xy', mu=df_data, tau=pm.matrix_inverse(cov), shape=df_data.shape)
yl = pm.Normal('yl', mu=intercept + gradient * obs_xy[:,0],
sd=epsilon, observed=obs_xy[:,1])
mu, sds, elbo = pm.variational.advi(n=20000)
step = pm.NUTS(scaling=model.dict_to_array(sds), is_cov=True)
trace = pm.sample(1000, step=step, start=mu)请注意,在前面的模型中,协方差矩阵是根据数据计算得出的。如果你打算这样做,那么我认为第一个模型更好,但如果你要估计协方差矩阵,那么第二个模型可能是一个明智的方法。
对于第二个模型,我使用ADVI对其进行初始化。ADVI是初始化模型的好方法,它通常比find_MAP()好得多。
你可能还想看看David Hogg写的这个repository。McElreath在Statistical Rethinking一书中讨论了线性回归的问题,包括输入和输出变量中的误差。
https://stackoverflow.com/questions/39677240
复制相似问题