加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 具有变化点的PyMC3回归

发布时间:2020-12-20 11:50:26 所属栏目:Python 来源:网络整理
导读:我看到了如何用pymc3进行变点分析的例子,但似乎我错过了一些东西,因为我得到的结果远非真正的值.这是一个玩具的例子. 数据: 脚本: from pymc3 import *from numpy.random import uniform,normalbp_u = 30 #switch pointc_u = [1,-1] #intercepts before an
我看到了如何用pymc3进行变点分析的例子,但似乎我错过了一些东西,因为我得到的结果远非真正的值.这是一个玩具的例子.

数据:

toy data

脚本:

from pymc3 import *
from numpy.random import uniform,normal

bp_u = 30 #switch point
c_u = [1,-1] #intercepts before and after switch point
beta_u = [0,-0.02]  #slopes before & after switch point

x = uniform(0,90,200)

y = (x < bp_u)*(c_u[0]+beta_u[0]*x) + (x >= bp_u)*(c_u[1]+beta_u[1]*x) + normal(0,0.1,200)

with Model() as sw_model:

    sigma = HalfCauchy('sigma',beta=10,testval=1.)

    switchpoint = Uniform('switchpoint',lower=x.min(),upper=x.max(),testval=45)

    # Priors for pre- and post-switch intercepts and slopes
    intercept_u1 = Uniform('Intercept_u1',lower=-10,upper=10)
    intercept_u2 = Uniform('Intercept_u2',upper=10)
    x_coeff_u1 = Normal('x_u1',sd=20)
    x_coeff_u2 = Normal('x_u2',sd=20)

    intercept = switch(switchpoint < x,intercept_u1,intercept_u2)
    x_coeff = switch(switchpoint < x,x_coeff_u1,x_coeff_u2)

    likelihood = Normal('y',mu=intercept + x_coeff * x,sd=sigma,observed=y)

    start = find_MAP() 

with sw_model:
    step1 = NUTS([intercept_u1,intercept_u2,x_coeff_u2])
    step2 = NUTS([switchpoint])

    trace = sample(2000,step=[step1,step2],start=start,progressbar=True)

以下是结果:

segmented regression results

如您所见,它们与初始值完全不同.我做错了什么?

解决方法

最后,似乎用Metropolis采样切换到离散断点解决了这个问题.这是最终的模型:

with Model() as sw_model:

    sigma = HalfCauchy('sigma',testval=1.)

    switchpoint = DiscreteUniform('switchpoint',lower=0,upper=90,upper=10,testval = 0)
    intercept_u2 = Uniform('Intercept_u2',testval = 0)
    x_coeff_u1 = Normal('x_u1',observed=y)

    start = find_MAP() 

    step1 = NUTS([intercept_u1,x_coeff_u2])
    step2 = Metropolis([switchpoint])

    trace = sample(20000,njobs=4,progressbar=True)

the traceplot

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读