PyMC3 regression with change point(带变点的PyMC3回归)
本文介绍了带变点的PyMC3回归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到了如何使用pymc3进行变点分析的示例,但似乎遗漏了一些东西,因为我得到的结果与真实值相差甚远。这里有一个玩具示例。
数据:
脚本:
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)
结果如下:
如您所见,它们与初始值有很大不同。我做错了什么?
推荐答案
最终看来,使用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)
这篇关于带变点的PyMC3回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:带变点的PyMC3回归


基础教程推荐
猜你喜欢
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01