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

python – PYMC3贝叶斯预测锥

发布时间:2020-12-20 13:19:25 所属栏目:Python 来源:网络整理
导读:我还在学习PYMC3,但我在文档中找不到任何关于以下问题的内容.考虑 this question的贝叶斯结构时间序列(BSTS)模型,没有季节性.这可以在PYMC3中建模如下: import pymc3,numpy,matplotlib.pyplot# generate some test datat = numpy.linspace(0,2*numpy.pi,100
我还在学习PYMC3,但我在文档中找不到任何关于以下问题的内容.考虑 this question的贝叶斯结构时间序列(BSTS)模型,没有季节性.这可以在PYMC3中建模如下:

import pymc3,numpy,matplotlib.pyplot
# generate some test data
t = numpy.linspace(0,2*numpy.pi,100)
y_full = numpy.cos(5*t)
y_train = y_full[:90]
y_test = y_full[90:]

# specify the model
with pymc3.Model() as model:
  grw = pymc3.GaussianRandomWalk('grw',mu=0,sd=1,shape=y_train.size)
  y = pymc3.Normal('y',mu=grw,observed=y_train)
  trace = pymc3.sample(1000)
  y_mean_pred = pymc3.sample_ppc(trace,samples=1000,model=model)['y'].mean(axis=0)

  fig = matplotlib.pyplot.figure(dpi=100)
  ax = fig.add_subplot(111)
  ax.plot(t,y_full,c='b')
  ax.plot(t[:90],y_mean_pred,c='r')
  matplotlib.pyplot.show()

现在我想预测接下来10个时间步的行为,即y_test.我还希望在该区域包括可信区域产生贝叶斯锥体,例如,参见here.不幸的是,在上述链接中产生锥体的机制有点模糊.在更传统的AR模型中,可以学习平均回归系数并手动扩展平均曲线.但是,在这个BSTS模型中没有明显的方法可以做到这一点.或者,如果有回归量,那么我可以使用theano.shared并使用更精细/扩展的网格更新它以使用sample_ppc进行估算和推断,但这不是这个设置中的选项.也许sample_ppc在这里是一个红鲱鱼,但它还不清楚如何继续.欢迎任何帮助.

解决方法

我认为以下工作.然而,它非常笨重,并且要求我知道在我训练之前我想要预测多远(特别是它包括流媒体使用或简单的EDA).我怀疑有更好的方法,我宁愿接受更多Pymc3经验的人提供更好的解决方案

import numpy,pymc3,matplotlib.pyplot,seaborn

# generate some data
t = numpy.linspace(0,100)
y_full = numpy.cos(5*t)
# mask the data that I want to predict (requires knowledge 
#   that one might not always have at training time).
cutoff_idx = 80
y_obs = numpy.ma.MaskedArray(y_full,numpy.arange(t.size)>cutoff_idx)

# specify and train the model,used the masked array to supply only 
#   the observed data
with pymc3.Model() as model:
  grw = pymc3.GaussianRandomWalk('grw',shape=y_obs.size)
  y = pymc3.Normal('y',observed=y_obs)
  trace = pymc3.sample(5000)
  y_pred = pymc3.sample_ppc(trace,samples=20000,model=model)['y']
  y_pred_mean = y_pred.mean(axis=0)

  # compute percentiles
  dfp = numpy.percentile(y_pred,[2.5,25,50,70,97.5],axis=0)

  # plot actual data and summary posterior information
  pal = seaborn.color_palette('Purples')
  fig = matplotlib.pyplot.figure(dpi=100)
  ax = fig.add_subplot(111)
  ax.plot(t,c='g',label='true value',alpha=0.5)
  ax.plot(t,y_pred_mean,c=pal[5],label='posterior mean',dfp[2,:],alpha=0.75,color=pal[3],label='posterior median')
  ax.fill_between(t,dfp[0,dfp[4,alpha=0.5,color=pal[1],label='CR 95%')
  ax.fill_between(t,dfp[1,dfp[3,alpha=0.4,color=pal[2],label='CR 50%')
  ax.axvline(x=t[cutoff_idx],linestyle='--',color='r',alpha=0.25)
  ax.legend()
  matplotlib.pyplot.show()

这输出以下似乎是一个非常糟糕的预测,但至少代码提供了样本值.

enter image description here

(编辑:李大同)

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

    推荐文章
      热点阅读