python - 带变化点的 PyMC3 回归

标签 python regression pymc pymc3

我看到了如何使用 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', lower=-10, upper=10)
    x_coeff_u1 = Normal('x_u1', 0, sd=20)
    x_coeff_u2 = Normal('x_u2', 0, 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_u1, 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', beta=10, testval=1.)

    switchpoint = DiscreteUniform('switchpoint', lower=0, upper=90, testval=45)

    # Priors for pre- and post-switch intercepts and slopes
    intercept_u1 = Uniform('Intercept_u1', lower=-10, upper=10, testval = 0)
    intercept_u2 = Uniform('Intercept_u2', lower=-10, upper=10, testval = 0)
    x_coeff_u1 = Normal('x_u1', 0, sd=20)
    x_coeff_u2 = Normal('x_u2', 0, 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() 

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

    trace = sample(20000, step=[step1, step2], start=start, njobs=4,progressbar=True)

the traceplot

关于python - 带变化点的 PyMC3 回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36045851/

相关文章:

python - 我们可以为我们正在使用的键函数和排序函数传递任何参数吗

python:类对象的多维排序

python - 为什么 PyMC3 和 Tensorflow 需要对象的双重命名?

r - 回归和 PCA 的视觉比较

python - PYMC3 贝叶斯预测锥

python - PyMC 中的负二项式混合

python - 从 Python 的子类中删除属性

python - 使用 pickle 在 postgres 表中保存 python 对象

python - 如何(快速)从二维图像的特定点提取双线性插值补丁?

python - 如何在Python中进行指数非线性回归