PYMC3贝叶斯预测锥

时间:2017-08-22 23:45:08

标签: python bayesian pymc pymc3

我还在学习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,sd=1,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在这里是一个红鲱鱼,但它还不清楚如何继续。欢迎任何帮助。

1 个答案:

答案 0 :(得分:3)

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

import numpy, pymc3, matplotlib.pyplot, seaborn

# generate some data
t = numpy.linspace(0,2*numpy.pi,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',mu=0,sd=1,shape=y_obs.size)
  y = pymc3.Normal('y',mu=grw,sd=1,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,y_full,c='g',label='true value',alpha=0.5)
  ax.plot(t,y_pred_mean,c=pal[5],label='posterior mean',alpha=0.5)
  ax.plot(t,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