使用pyMCMC / pyMC为数据/观察拟合非线性函数

问题描述 投票:25回答:2

我试图用高斯(和更复杂)函数拟合一些数据。我在下面创建了一个小例子。

我的第一个问题是,我做得对吗?

我的第二个问题是,如何在x方向上添加误差,即在观测/数据的x位置?

如何在pyMC中进行这种回归很难找到很好的指南。也许是因为它更容易使用一些最小二乘或类似的方法,但我最终有很多参数,需要看看我们如何约束它们并比较不同的模型,pyMC似乎是一个很好的选择。

import pymc
import numpy as np
import matplotlib.pyplot as plt; plt.ion()

x = np.arange(5,400,10)*1e3

# Parameters for gaussian
amp_true = 0.2
size_true = 1.8
ps_true = 0.1

# Gaussian function
gauss = lambda x,amp,size,ps: amp*np.exp(-1*(np.pi**2/(3600.*180.)*size*x)**2/(4.*np.log(2.)))+ps
f_true = gauss(x=x,amp=amp_true, size=size_true, ps=ps_true )

# add noise to the data points
noise = np.random.normal(size=len(x)) * .02 
f = f_true + noise 
f_error = np.ones_like(f_true)*0.05*f.max()

# define the model/function to be fitted.
def model(x, f): 
    amp = pymc.Uniform('amp', 0.05, 0.4, value= 0.15)
    size = pymc.Uniform('size', 0.5, 2.5, value= 1.0)
    ps = pymc.Normal('ps', 0.13, 40, value=0.15)

    @pymc.deterministic(plot=False)
    def gauss(x=x, amp=amp, size=size, ps=ps):
        e = -1*(np.pi**2*size*x/(3600.*180.))**2/(4.*np.log(2.))
        return amp*np.exp(e)+ps
    y = pymc.Normal('y', mu=gauss, tau=1.0/f_error**2, value=f, observed=True)
    return locals()

MDL = pymc.MCMC(model(x,f))
MDL.sample(1e4)

# extract and plot results
y_min = MDL.stats()['gauss']['quantiles'][2.5]
y_max = MDL.stats()['gauss']['quantiles'][97.5]
y_fit = MDL.stats()['gauss']['mean']
plt.plot(x,f_true,'b', marker='None', ls='-', lw=1, label='True')
plt.errorbar(x,f,yerr=f_error, color='r', marker='.', ls='None', label='Observed')
plt.plot(x,y_fit,'k', marker='+', ls='None', ms=5, mew=2, label='Fit')
plt.fill_between(x, y_min, y_max, color='0.5', alpha=0.5)
plt.legend()

我意识到我可能需要运行更多的迭代,最后使用刻录和细化。绘制数据和拟合的图如下所示。

pymc.Matplot.plot(MDL)数字看起来像这样,显示出很好的峰值分布。这很好,对吗?

python regression pymc
2个回答
15
投票

我的第一个问题是,我做得对吗?

是!您需要包含一个老化期,您知道。我想丢掉我的样品的前半部分。您不需要进行任何细化,但有时它会使您的MCMC后处理工作更快,存储更小。

我建议的唯一另一件事就是设置一个随机种子,这样你的结果就是“可重复的”:np.random.seed(12345)就可以了。

哦,如果我真的给了太多建议,我会说import seabornmatplotlib的结果更漂亮一点。

我的第二个问题是,如何在x方向上添加误差,即在观测/数据的x位置?

一种方法是为每个错误包含一个潜在变量。这适用于您的示例,但如果您有更多观察,则不可行。我会举一个例子让你开始走这条路:

# add noise to observed x values
x_obs = pm.rnormal(mu=x, tau=(1e4)**-2)

# define the model/function to be fitted.
def model(x_obs, f): 
    amp = pm.Uniform('amp', 0.05, 0.4, value= 0.15)
    size = pm.Uniform('size', 0.5, 2.5, value= 1.0)
    ps = pm.Normal('ps', 0.13, 40, value=0.15)

    x_pred = pm.Normal('x', mu=x_obs, tau=(1e4)**-2) # this allows error in x_obs

    @pm.deterministic(plot=False)
    def gauss(x=x_pred, amp=amp, size=size, ps=ps):
        e = -1*(np.pi**2*size*x/(3600.*180.))**2/(4.*np.log(2.))
        return amp*np.exp(e)+ps
    y = pm.Normal('y', mu=gauss, tau=1.0/f_error**2, value=f, observed=True)
    return locals()

MDL = pm.MCMC(model(x_obs, f))
MDL.use_step_method(pm.AdaptiveMetropolis, MDL.x_pred) # use AdaptiveMetropolis to "learn" how to step
MDL.sample(200000, 100000, 10)  # run chain longer since there are more dimensions

如果你在xy有噪音,看起来很难得到好的答案:

这是a notebook collecting this all up


13
投票

编辑:重要说明这一直困扰我一段时间。我和亚伯拉罕在这里给出的答案是正确的,因为它们增加了x的可变性。但是:请注意,您不能简单地以这种方式添加不确定性来抵消x值中的错误,以便您对“true x”进行回归。本答案中的方法可以向您展示如果您拥有真实x,如何向x添加错误会影响您的回归。如果你有一个误测的x,这些答案对你没有帮助。在x值中存在误差是一个非常棘手的问题,因为它会导致“衰减”和“变量误差效应”。简短版本是:在x中具有无偏差的随机误差会导致回归估计出现偏差。如果您有这个问题,请查看Carroll,R.J.,Ruppert,D.,Crainiceanu,C.M。和Stefanski,L.A.,2006年。非线性模型中的测量误差:现代视角。 Chapman和Hall / CRC。,或贝叶斯方法,Gustafson,P.,2003。统计和流行病学中的测量误差和错误分类:影响和贝叶斯调整。 CRC出版社。我最终使用Carroll等人的SIMEX方法和PyMC3来解决我的具体问题。详情见Carstens,H.,Xia,X。和Yadavalli,S.,2017。用于测量和验证的低成本电能表校准方法。 Applied energy,188,pp.563-575。它也可以在ArXiv上使用


我将Abraham Flaxman的上述答案转换为PyMC3,万一有人需要它。一些非常小的变化,但可能会令人困惑。

第一个是确定性装饰器@Deterministic被类似分布的调用函数var=pymc3.Deterministic()所取代。第二,当生成正态分布随机变量的向量时,

rvs = pymc2.rnormal(mu=mu, tau=tau)

被替换为

rvs = pymc3.Normal('var_name', mu=mu, tau=tau,shape=size(var)).random()

完整的代码如下:

import numpy as np
from pymc3 import *
import matplotlib.pyplot as plt

# set random seed for reproducibility
np.random.seed(12345)

x = np.arange(5,400,10)*1e3

# Parameters for gaussian
amp_true = 0.2
size_true = 1.8
ps_true = 0.1

#Gaussian function
gauss = lambda x,amp,size,ps: amp*np.exp(-1*(np.pi**2/(3600.*180.)*size*x)**2/(4.*np.log(2.)))+ps
f_true = gauss(x=x,amp=amp_true, size=size_true, ps=ps_true )

# add noise to the data points
noise = np.random.normal(size=len(x)) * .02 
f = f_true + noise 
f_error = np.ones_like(f_true)*0.05*f.max()

with Model() as model3:
    amp = Uniform('amp', 0.05, 0.4, testval= 0.15)
    size = Uniform('size', 0.5, 2.5, testval= 1.0)
    ps = Normal('ps', 0.13, 40, testval=0.15)

    gauss=Deterministic('gauss',amp*np.exp(-1*(np.pi**2*size*x/(3600.*180.))**2/(4.*np.log(2.)))+ps)

    y =Normal('y', mu=gauss, tau=1.0/f_error**2, observed=f)

    start=find_MAP()
    step=NUTS()
    trace=sample(2000,start=start)

# extract and plot results
y_min = np.percentile(trace.gauss,2.5,axis=0)
y_max = np.percentile(trace.gauss,97.5,axis=0)
y_fit = np.percentile(trace.gauss,50,axis=0)
plt.plot(x,f_true,'b', marker='None', ls='-', lw=1, label='True')
plt.errorbar(x,f,yerr=f_error, color='r', marker='.', ls='None', label='Observed')
plt.plot(x,y_fit,'k', marker='+', ls='None', ms=5, mew=1, label='Fit')
plt.fill_between(x, y_min, y_max, color='0.5', alpha=0.5)
plt.legend()

结果如何

y_error

对于x中的错误(注意变量的'x'后缀):

# define the model/function to be fitted in PyMC3:
with Model() as modelx:

    x_obsx = pm3.Normal('x_obsx',mu=x, tau=(1e4)**-2, shape=40)

    ampx = Uniform('ampx', 0.05, 0.4, testval=0.15)
    sizex = Uniform('sizex', 0.5, 2.5, testval=1.0)
    psx = Normal('psx', 0.13, 40, testval=0.15)

    x_pred = Normal('x_pred', mu=x_obsx, tau=(1e4)**-2*np.ones_like(x_obsx),testval=5*np.ones_like(x_obsx),shape=40) # this allows error in x_obs

    gauss=Deterministic('gauss',ampx*np.exp(-1*(np.pi**2*sizex*x_pred/(3600.*180.))**2/(4.*np.log(2.)))+psx)

    y = Normal('y', mu=gauss, tau=1.0/f_error**2, observed=f)

    start=find_MAP()
    step=NUTS()
    tracex=sample(20000,start=start)

结果如下:

x_error_graph

最后一个观察是做的时候

traceplot(tracex[100:])
plt.tight_layout();

(结果未显示),我们可以看到,由于sizex的测量误差,x似乎正在遭受“衰减”或“回归稀释”。

© www.soinside.com 2019 - 2024. All rights reserved.