楼主: Lisrelchen
1182 4

PySSM: Bayesian Inference of Linear Gaussian State Space Models [推广有奖]

  • 0关注
  • 62粉丝

VIP

院士

67%

还不是VIP/贵宾

-

TA的文库  其他...

Bayesian NewOccidental

Spatial Data Analysis

东西方数据挖掘

威望
0
论坛币
49957 个
通用积分
79.5487
学术水平
253 点
热心指数
300 点
信用等级
208 点
经验
41518 点
帖子
3256
精华
14
在线时间
766 小时
注册时间
2006-5-4
最后登录
2022-11-6

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币


Authors:

Christopher Strickland, Robert Burdett, Kerrie Mengersen, Robert Denham

Title:

PySSM: A Python Module for Bayesian Inference of Linear Gaussian State Space Models

Abstract:

PySSM is a Python package that has been developed for the analysis of time series using linear Gaussian state space models. PySSM is easy to use; models can be set up quickly and efficiently and a variety of different settings are available to the user. It also takes advantage of scientific libraries NumPy and SciPy and other high level features of the Python language. PySSM is also used as a platform for interfacing between optimized and parallelized Fortran routines. These Fortran routines heavily utilize basic linear algebra and linear algebra Package functions for maximum performance. PySSM contains classes for filtering, classical smoothing as well as simulation smoothing.

Page views:: 5207. Submitted: 2012-03-23. Published: 2014-04-07.

Paper:

PySSM: A Python Module for Bayesian Inference of Linear Gaussian State Space Models     [size=1em]Download PDF (Downloads: 5736)

Supplements:

pyssm-1.1e.tar.gz: Python source package

[size=1em]Download(Downloads: 277; 95KB)

pyssm-1.1e.win32-py2.7.exe: Windows 32-bit binary package

[size=1em]Download(Downloads: 254; 2MB)

v57i06-examples.zip: Python example code from the paper

[size=1em]Download(Downloads: 270; 5KB)


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:State Space Inference Bayesian Gaussian models scientific different advantage available developed

沙发
Lisrelchen 发表于 2016-12-11 03:39:17 |只看作者 |坛友微信交流群
  1. from numpy import log, ones, column_stack, hstack, mean
  2. from numpy import random, zeros, sqrt
  3. from pymcmc.mcmc import MCMC, CFsampler, IndMH
  4. from pymcmc.regtools import LinearModel, CondScaleSampler
  5. import pylab
  6. from pyssm.ssm import Filter, SimSmoother


  7. def simdata(nobs):
  8.     ht = 1.0 ** 2
  9.     zt = 1.0
  10.     tt = 0.95
  11.     qt = 0.3 ** 2
  12.     gt = 1.0
  13.     rt = 1.0
  14.     mu = 5.0
  15.     a1 = mu
  16.     p1 = qt / (1. - tt ** 2)
  17.     beta = mu * (1.0 - tt)
  18.     wmat = ones((1, 1, nobs))

  19.     filt = Filter(nobs, 1, 1, 1, False, wmat=wmat)
  20.     filt.initialise_system(a1, p1, zt, ht, tt, gt, qt, rt, beta=beta)
  21.     filt.simssm()

  22.     yvec = filt.get_ymat().T.flatten()
  23.     simstate = filt.get_state()
  24.     return yvec, simstate


  25. def simstate(store):
  26.     system = store['simsm'].get_system()
  27.     system.update_tt(store['rho'])

  28.     p1 = system._qt() / (1.0 - store['rho'] ** 2)
  29.     a1 = store['beta'] / (1.0 - store['rho'])

  30.     system.update_a1(a1)
  31.     system.update_p1(p1)

  32.     system.update_beta(store['beta'])

  33.     state = store['simsm'].sim_smoother()

  34.     return state


  35. def simht(store):
  36.     system = store['simsm'].get_system()
  37.     residual = store['simsm'].get_meas_residual()
  38.     ht = store['scale_sampler'].sample(residual.T)
  39.     system.update_ht(ht ** 2)

  40.     return ht ** 2


  41. def prior_rho(store):
  42.     if store['rho'] < 1.0 and store['rho'] > 0.0:
  43.         rho1 = 15.0
  44.         rho2 = 1.5
  45.         return (rho1 - 1.0) * log(store['rho']) + (rho2 - 1.0) * log(1.0 - store['rho'])
  46.     else:
  47.         return -1E256


  48. def prior_sigma(store):
  49.     nu = 10.0
  50.     S = 0.01
  51.     return -(nu + 1) * log(store['sigma']) - S / (2.0 * store['sigma'] ** 2)


  52. def post_rho_sigma(store):
  53.     if store['rho'] < 1.0 and store['rho'] > 0.0:
  54.         system = store['simsm'].get_system()
  55.         p1 = system._qt() / (1.0 - store['rho'] ** 2)
  56.         a1 = store['beta'] / (1.0 - store['rho'])
  57.         system.update_p1(p1)
  58.         system.update_a1(a1)
  59.         system.update_tt(store['rho'])
  60.         system.update_beta(store['beta'])
  61.         system.update_qt(store['sigma'] ** 2)
  62.         lnpr = store['simsm'].log_probability_state()

  63.         #lnpr =  store['simsm'].calc_log_likelihood()
  64.         return lnpr + prior_rho(store) + prior_sigma(store)
  65.     else:
  66.         return -1E256


  67. def cand_rho_sigma(store):
  68.     nobs = store['state'].shape[1]
  69.     store['bayes_reg'].update_yvec(store['state'][0, 1:nobs])
  70.     xmat = column_stack([ones(nobs - 1), store['state'][0, 0:nobs - 1]])
  71.     store['bayes_reg'].update_xmat(xmat)
  72.     sig, beta = store['bayes_reg'].sample()
  73.     return sig, beta[0], beta[1]


  74. def cand_prob(store):
  75.     beta = hstack([store['beta'], store['rho']])
  76.     return store['bayes_reg'].log_posterior_probability(store['sigma'], beta)


  77. def transform_beta(store):
  78.     return store['beta'] / (1.0 - store['rho'])


  79. def main():
  80.     """
  81.     The main routine.
  82.     """

  83.     random.seed(12345)
  84.     nobs = 1000
  85.     nstate = 1
  86.     rstate = 1
  87.     yvec, simulated_state = simdata(nobs)
  88.     data = {'yvec': yvec}

  89.     ht = 1.0
  90.     tt = 0.9
  91.     zt = 1.0
  92.     qt = 0.4
  93.     gt = 1.0
  94.     rt = 1.0
  95.     p1 = qt / (1. - tt ** 2)
  96.     mu = mean(yvec)
  97.     a1 = mu
  98.     beta = mu * (1 - tt)
  99.     wmat = 1.0

  100.     data['simsm'] = SimSmoother(yvec, nstate, rstate,
  101.                                 False, properties={'gt': 'eye'},
  102.                                 wmat=wmat)
  103.     data['simsm'].initialise_system(a1, p1, zt, ht, tt, gt, qt, rt, beta=beta)
  104.     data['scale_sampler'] = CondScaleSampler(prior=['inverted_gamma', 10.0, 0.01])
  105.     data['bayes_reg'] = LinearModel(yvec[1:nobs], column_stack([ones(nobs - 1), yvec[0:nobs - 1]]))
  106.     samplestate = CFsampler(simstate, zeros((nstate, nobs)), 'state')
  107.     sampleht = CFsampler(simht, ht, 'ht')
  108.     samplesigbetarho = IndMH(cand_rho_sigma, post_rho_sigma,
  109.                              cand_prob, [sqrt(qt), 0.1, tt],
  110.                              ['sigma', 'beta', 'rho'])

  111.     blocks1 = [samplestate, sampleht, samplesigbetarho]
  112.     mcmc = MCMC(5000, 2000, data, blocks1,
  113.                 transform={'beta': transform_beta}, runtime_output = True)
  114.     mcmc.sampler()
  115.     mcmc.output(parameters=['ht', 'sigma', 'rho', 'beta'],
  116.                filename='ar1out.txt')

  117.     means, vars = mcmc.get_mean_var('state')
  118.     pylab.plot(range(nobs), means[0], color='k')
  119.     pylab.plot(range(nobs), simulated_state[0], color='k',)
  120.     pylab.title('Simulated vs estimated state')
  121.     pylab.savefig('AR1.pdf')
  122.     pylab.close("all")
  123.    
  124. if __name__ == '__main__':
  125.     main()
复制代码

使用道具

藤椅
Lisrelchen 发表于 2016-12-11 03:39:59 |只看作者 |坛友微信交流群
  1. import numpy as np
  2. import os
  3. import pymcmc.mcmc as mcmc
  4. import pymcmc.regtools as regtools
  5. import pylab
  6. import pyssm.ssm as ssm

  7. """ Get the path for the data. If this was
  8. installed using setup.py it will be in the
  9. data directory of the module"""

  10. datadir = os.path.join(os.path.dirname(ssm.__file__), 'data')


  11. def update_tt(store):
  12.     system = store['simsm'].get_system()
  13.     tt = system.tt()
  14.     tt[2, 2] = store['rho'] * np.cos(store['lambda'])
  15.     tt[2, 3] = store['rho'] * np.sin(store['lambda'])
  16.     tt[3, 2] = -tt[2, 3]
  17.     tt[3, 3] = tt[2, 2]
  18.     system.update_tt(tt)


  19. def update_p1(store):
  20.     system = store['simsm'].get_system()
  21.     p1 = system.p1()
  22.     p1[2, 2] = store['sigma_cycle'] ** 2 / \
  23.                (1. - store['rho'] ** 2)
  24.     p1[3, 3] = p1[2, 2]
  25.     system.update_p1(p1)


  26. def update_qt(store):
  27.     system = store['simsm'].get_system()
  28.     qt = np.zeros((3, 3))
  29.     qt[0, 0] = store['sigma_level'] ** 2
  30.     qt[1, 1] = store['sigma_cycle'] ** 2
  31.     qt[2, 2] = qt[1, 1]
  32.     system.update_qt(qt)


  33. def simstate(store):
  34.     update_tt(store)
  35.     update_qt(store)
  36.     update_p1(store)
  37.     return store['simsm'].sim_smoother()


  38. def simht(store):
  39.     residual = store['simsm'].get_meas_residual()
  40.     ht = np.linalg.inv(
  41.         store['scale_sampler'].sample(residual.T)
  42.         )
  43.     system = store['simsm'].get_system()
  44.     system.update_ht(ht)
  45.    
  46.     return ht


  47. def simsig_level(store):
  48.     update_tt(store)
  49.     residual = store['simsm'].get_state_residual(
  50.         state_index=[0])
  51.     sigma_level = store['scale_sampler2'].sample(
  52.         residual.T)
  53.     return sigma_level


  54. def posterior_sig_cycle(store):
  55.     if store['sigma_cycle'] > 0:
  56.         update_tt(store)
  57.         update_qt(store)
  58.         update_p1(store)
  59.         probstate = store['simsm'].log_probability_state()
  60.         #probstate = store['simsm'].log_likelihood()
  61.         return probstate + prior_sig(store['sigma_cycle'])
  62.     else:
  63.         return -1E256


  64. def prior_sig(sig):
  65.     nu = -1.
  66.     S = 0.0
  67.     return -(nu + 1) * np.log(sig) - S / (2.0 * sig ** 2)


  68. def posterior_lambda(store):
  69.     update_tt(store)
  70.     lnpr = store['simsm'].log_probability_state()
  71.     #lnpr = store['simsm'].log_likelihood()
  72.     return lnpr + prior_lambda(store)


  73. def prior_lambda(store):
  74.     """flat prior restricting the period of the cycle to be between 10
  75.     months and 14 months"""
  76.     if store['lambda'] > np.pi / 20. and store['lambda'] < 2 * np.pi / 4.:
  77.         return 0.0
  78.     else:
  79.         return -1E256


  80. def posterior_rho(store):
  81.     if store['rho'] > 0 and store['rho'] < 1.0:
  82.         update_tt(store)
  83.         update_p1(store)
  84.         lnpr = store['simsm'].log_probability_state()
  85.         #lnpr = store['simsm'].log_likelihood()
  86.         return lnpr + prior_rho(store)
  87.     else:
  88.         return -1E256


  89. def prior_rho(store):
  90.     rho1 = 15.0
  91.     rho2 = 1.5
  92.     return (rho1 - 1.0) * np.log(store['rho']) + (rho2 - 1.) * \
  93.            np.log(1. - store['rho'])


  94. def main():
  95.     np.random.seed(12345)
  96.     filename = os.path.join(datadir, 'farmb.txt')
  97.     ymat = np.loadtxt(filename).T / 1000.
  98.     nseries, nobs = ymat.shape
  99.     data = {'ymat': ymat}

  100.     nstate = 4
  101.     rstate = 3
  102.     ht = np.eye(nseries)
  103.     zt = np.column_stack([np.ones(nseries), np.zeros(nseries),
  104.                           np.ones(nseries), np.zeros(nseries)])
  105.     rt = np.ones(nseries)
  106.     tt = np.zeros((nstate, nstate))
  107.     rho = 0.9
  108.     lamb = 2. * np.pi / 20.
  109.     tt[0, 0] = 1.0
  110.     tt[0, 1] = 1.0
  111.     tt[1, 1] = 1.0
  112.     tt[2, 2] = rho * np.cos(lamb)
  113.     tt[2, 3] = rho * np.sin(lamb)
  114.     tt[3, 2] = -tt[2, 3]
  115.     tt[3, 3] = tt[2, 2]

  116.     sig_cycle = 0.3
  117.     sig_level = 0.3
  118.     qt = np.diag(np.array([sig_level, sig_cycle, sig_cycle]) ** 2)
  119.     gt = np.zeros((nstate, rstate))
  120.     gt[0, 0] = 1.0
  121.     gt[2:, 1:] = np.eye(2)
  122.     a1 = np.array([7.5, 0.000, 0.0, 0.0])
  123.     p1 = np.zeros((nstate, nstate))
  124.     p1[0, 0] = 10.
  125.     p1[1, 1] = 10.
  126.     p1[2, 2] = qt[2, 2] / (1 - rho ** 2)
  127.     p1[3, 3] = p1[2, 2]

  128.     timevar = False
  129.     data['simsm'] = ssm.SimSmoother(ymat, nstate, rstate, timevar,
  130.                                 properties={'rt': 'eye'})
  131.     data['simsm'].initialise_system(a1, p1, zt, ht, tt, gt, qt, rt)

  132.     prior_wishart = ['wishart', 10 * np.ones(nseries), 0.1 * np.eye(nseries)]
  133.     data['scale_sampler'] = regtools.CondScaleSampler(prior=prior_wishart)
  134.     data['scale_sampler2'] = regtools.CondScaleSampler(
  135.         prior=['inverted_gamma', 10, 0.1])

  136.     samplestate = mcmc.CFsampler(simstate,
  137.                                  np.zeros((nstate, nobs)),
  138.                                  'state', store='none')
  139.     sampleht = mcmc.CFsampler(simht, ht, 'ht')
  140.     samplesig_level = mcmc.CFsampler(simsig_level,
  141.                                      sig_level, 'sigma_level')
  142.     samplesig_cycle = mcmc.RWMH(posterior_sig_cycle, 0.05,
  143.                                 sig_cycle ** 2, 'sigma_cycle',
  144.                                 adaptive='GFS')
  145.     samplerho = mcmc.RWMH(posterior_rho, 0.09, rho, 'rho', adaptive='GFS')
  146.     samplelambda = mcmc.RWMH(posterior_lambda, 1.03, lamb,
  147.                              'lambda', adaptive='GFS')

  148.     blocks = [samplestate, sampleht, samplesig_cycle,
  149.               samplesig_level, samplerho, samplelambda]
  150.     mcmcobj = mcmc.MCMC(8000, 3000, data, blocks, runtime_output=True)
  151.     mcmcobj.sampler()
  152.     mcmcobj.output(parameters=['rho', 'lambda', 'sigma_level', 'sigma_cycle'])

  153.     means, vars = mcmcobj.get_mean_var('state')

  154.     pylab.subplot(2, 1, 1)
  155.     pylab.title("Trend Cycle Model")
  156.     pylab.plot(ymat.T, color='k')
  157.     pylab.plot(means[0], color='k')
  158.     pylab.subplot(2, 1, 2)
  159.     pylab.plot(means[2], color='k')
  160.     pylab.savefig('trendcycle.pdf')
  161.     pylab.close("all")
  162.    
  163. if __name__ == '__main__':
  164.     main()
复制代码

使用道具

板凳
Lisrelchen 发表于 2016-12-11 03:40:28 |只看作者 |坛友微信交流群
  1. import numpy as np
  2. import os
  3. import pylab

  4. import pymcmc.mcmc as mcmc
  5. import pymcmc.regtools as regtools

  6. import pyssm.ssm as ssm

  7. """ Get the path for the data. If this was installed using setup.py
  8. it will be in the data directory of the module"""
  9. datadir = os.path.join(os.path.dirname(ssm.__file__), 'data')


  10. def update_gt(store):
  11.     system = store['simsm'].get_system()
  12.     gt = np.eye(2) * store['sigma']
  13.     system.update_gt(gt)


  14. def simstate(store):
  15.     update_gt(store)
  16.     #import pdb
  17.     #pdb.set_trace()
  18.     state = store['simsm'].sim_smoother()
  19.     return state


  20. def sim_ht(store):
  21.     residual = store['simsm'].get_meas_residual()
  22.     sqrtht = store['scale_sampler'].sample(residual.T)
  23.     system = store['simsm'].get_system()
  24.     ht = sqrtht ** 2
  25.     system.update_ht(ht)
  26.     return ht


  27. def post_sigma(store):
  28.     if store['sigma'] > 0:
  29.         update_gt(store)
  30.         lnpr = store['simsm'].log_likelihood()
  31.         #lnpr = store['simsm'].log_probability_state(diffuse = True)

  32.         return lnpr + prior_sigma(store['sigma'])
  33.     else:
  34.         return -1E256


  35. def prior_sigma(sigma):
  36.     nu = 10
  37.     S = 0.1
  38.     return -(nu + 1) * np.log(sigma) - 0.5 * S / sigma ** 2


  39. def main():
  40.     np.random.seed(1234)
  41.     data = np.loadtxt(os.path.join(datadir, 'motorcycle.txt'))
  42.     data = data[data[:, 1] > 0]
  43.     yvec = data[:, 2]
  44.     delta = data[:, 1]
  45.     nobs = yvec.shape[0]
  46.     nstate = 2
  47.     rstate = 2
  48.     data = {'yvec': yvec}

  49.     sigeps = 0.9
  50.     ht = sigeps ** 2
  51.     rt = 1.
  52.     zt = np.array([[1.0, 0.0]])
  53.     tt = np.zeros((2, 2, nobs))
  54.     tt[0, 0, :] = 1.
  55.     tt[1, 1, :] = 1.
  56.     tt[0, 1, :] = delta

  57.     sigma = 0.3
  58.     qt = np.zeros((2, 2, nobs))
  59.     qt[0, 0, :] = delta ** 3 / 3.
  60.     qt[0, 1, :] = qt[1, 0, :] = delta ** 2 / 2
  61.     qt[1, 1, :] = delta

  62.     gt = np.eye(nstate) * sigma
  63.     a1 = np.zeros(2)
  64.     p1 = np.eye(2)
  65.     wmat = np.zeros((2, 2, nobs))

  66.     data['simsm'] = ssm.SimSmoother(yvec, nstate, rstate,
  67.                            timevar={'tt': True, 'qt': True},
  68.                            properties={'rt': 'eye'}, wmat=wmat,
  69.                            joint_sample=['diffuse', np.eye(2)])

  70.     data['simsm'].initialise_system(a1, p1, zt, ht, tt, gt, qt, rt)
  71.     data['scale_sampler'] = regtools.CondScaleSampler(
  72.         prior=['inverted_gamma', 10, 0.1]
  73.         )

  74.     samplestate = mcmc.CFsampler(simstate, np.zeros((nstate, nobs)), 'state',
  75.                                  store='none')
  76.     sample_ht = mcmc.CFsampler(sim_ht, np.var(yvec), 'ht')
  77.     sample_sigma = mcmc.RWMH(post_sigma, 1., 0.2, 'sigma', adaptive='GFS')

  78.     blocks = [samplestate, sample_ht, sample_sigma]
  79.     mcmcobj = mcmc.MCMC(8000, 3000, data, blocks, runtime_output=True)
  80.     mcmcobj.sampler()
  81.     mcmcobj.output(parameters=['ht', 'sigma'], filename='spline.out')

  82.     means, vars = mcmcobj.get_mean_var('state')
  83.     pylab.plot(np.cumsum(delta), yvec, '.', color='k')
  84.     pylab.title("Smoothing spline for motorcycle acceleration data.")
  85.     pylab.plot(np.cumsum(delta), means[0], color='k')
  86.     pylab.savefig('spline.pdf')
  87.     pylab.close("all")

  88. if __name__ == '__main__':
  89.     main()
复制代码

使用道具

报纸
Lisrelchen 发表于 2016-12-11 03:40:55 |只看作者 |坛友微信交流群
  1. #!/usr/bin/env python
  2. import os

  3. try:
  4.     os.system("clear")
  5. except:
  6.     os.system("cls")


  7. intro = """

  8. PySSM Examples
  9. ==============

  10. This script will run the three examples presented in the
  11. accompanying paper. Scripts can also be run individually, using, for
  12. example,

  13. python example_ssm_ar1_reg.py

  14. """

  15. print intro

  16. print """

  17. Example 1: Autoregressive model with regressors
  18. (see Section 4.1).

  19. This script will produce a pdf called AR1.pdf (see Figure 1 in the paper),
  20. and a summary of the model fit and parameters in a text file called ar1out.txt.

  21. """

  22. os.system("python example_ssm_ar1_reg.py")

  23. print """

  24. Example 2: Spline smoothing
  25. (see Section 4.2)

  26. This script will produce a pdf called spline.pdf (see Figure 2 in the paper),
  27. and a summary of the model fit and parameters in a text file called spline.out

  28. """

  29. os.system("python example_ssm_vector_spline.py")


  30. print """

  31. Example 3: Trend plus cycle model
  32. (see Section 4.3)

  33. This script will produce a pdf called trendcycle.pdf  (see Figure 3 in the paper),
  34. and a summary of the model fit and parameters will be printed to the screen.

  35. """

  36. os.system("python example_ssm_trendcycle2.py")
复制代码

使用道具

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注jltj
拉您入交流群

京ICP备16021002-2号 京B2-20170662号 京公网安备 11010802022788号 论坛法律顾问:王进律师 知识产权保护声明   免责及隐私声明

GMT+8, 2024-4-26 21:58