Python
Stan
PyStan

StanとRでベイズ統計モデリング(アヒル本)をPythonにしてみる - 12.2-季節調整項

実行環境

インポート

import numpy as np
import pandas as pd
import pystan
import matplotlib.pyplot as plt
from matplotlib.figure import figaspect
%matplotlib inline

データ読み込み

ss2 = pd.read_csv('./data/data-ss2.txt')

12.2 季節調整項

12.2.3 Stanで実装

data = dict(
    T=ss2.index.size,
    Y=ss2['Y']
)
stanmodel = pystan.StanModel('./stan/model12-6.stan')
fit = stanmodel.sampling(data=data, iter=4000, thin=5, seed=1234)
stanmodel_b = pystan.StanModel('./stan/model12-6b.stan')
fit_b = stanmodel_b.sampling(data=data, pars=('mu', 'season', 's_mu', 's_season', 's_Y', 'y_mean'), iter=4000, thin=5, seed=1234)

12.2.4 推定結果の解釈

ms = fit.extract()

probs  = (10, 25, 50, 75, 90)
_, (ax1, ax2) = plt.subplots(1, 2, figsize=figaspect(3/8), sharex=True)

d_est = pd.DataFrame(np.percentile(ms['mu'], probs, axis=0).T, columns=['p{}'.format(p) for p in probs])
d_est['x'] = d_est.index + 1
ax1.plot('X', 'Y', 'o-', data=ss2, color='k')
ax1.plot('x', 'p50', data=d_est, color='k')
ax1.fill_between('x', 'p10', 'p90', data=d_est, color='k', alpha=0.2)
ax1.fill_between('x', 'p25', 'p75', data=d_est, color='k', alpha=0.4)
plt.setp(ax1, xlabel='Time (Quarter)', ylabel='Y', xlim=(1, 44))

d_est = pd.DataFrame(np.percentile(ms['season'], probs, axis=0).T, columns=['p{}'.format(p) for p in probs])
d_est['x'] = d_est.index + 1
ax2.plot('x', 'p50', data=d_est, color='k')
ax2.fill_between('x', 'p10', 'p90', data=d_est, color='k', alpha=0.2)
ax2.fill_between('x', 'p25', 'p75', data=d_est, color='k', alpha=0.4)
plt.setp(ax2, xlabel='Time (Quarter)', ylabel='Y', xlim=(1, 44))

plt.show()

fig12-4.png