{rstan} で 「状態空間時系列分析入門」 を再現したい。やっていること / 数式はテキストを参照。
リポジトリ: https://github.com/sinhrks/stan-statespace
library(devtools)
# devtools::install_github('hoxo-m/pforeach')
# devtools::install_github('sinhrks/ggfortify')
library(rstan)
library(pforeach)
library(ggplot2)
ggplot2::theme_set(theme_bw(base_family="HiraKakuProN-W3"))
library(ggfortify)
# モデルが収束しているか確認
is.converged <- function(stanfit) {
summarized <- summary(stanfit)
all(summarized$summary[, 'Rhat'] < 1.1)
}
# 値がだいたい近いか確認
is.almost.fitted <- function(result, expected, tolerance = 0.001) {
if (abs(result - expected) > tolerance) {
print(paste('Result is ', result))
return(FALSE)
} else {
return(TRUE)
}
}
ukdrivers <- read.table('../data/UKdriversKSI.txt', skip = 1)
ukdrivers <- ts(ukdrivers[[1]], start = c(1969, 1), frequency = 12)
ukdrivers <- log(ukdrivers)
確率的レベルと確率的傾きをもつローカル線形トレンドモデル。
model_file <- '../models/fig03_01.stan'
cat(paste(readLines(model_file)), sep = '\n')
data {
int<lower=1> n;
vector[n] y;
}
parameters {
# 確率的レベル
vector[n] mu;
# 確率的傾き
vector[n-1] v;
# レベル撹乱項
real<lower=0> sigma_level;
# 傾き撹乱項
real<lower=0> sigma_drift;
# 観測撹乱項
real<lower=0> sigma_irreg;
}
transformed parameters {
vector[n] yhat;
for(t in 1:n) {
yhat[t] <- mu[t];
}
}
model {
# 式 3.1
for(t in 2:n-1)
v[t] ~ normal(v[t-1], sigma_drift);
for(t in 2:n)
mu[t] ~ normal(mu[t-1] + v[t-1], sigma_level);
for(t in 1:n)
y[t] ~ normal(yhat[t], sigma_irreg);
}
y <- ukdrivers
standata <- within(list(), {
y <- as.vector(y)
n <- length(y)
})
stan_fit <- stan(file = model_file, chains = 0)
##
## TRANSLATING MODEL 'fig03_01' FROM Stan CODE TO C++ CODE NOW.
## COMPILING THE C++ CODE FOR MODEL 'fig03_01' NOW.
fit <- pforeach(i = 1:4, .final = sflist2stanfit)({
stan(fit = stan_fit, data = standata,
warmup = 8000, iter = 16000, chains = 1, seed = i)
})
stopifnot(is.converged(fit))
mu <- get_posterior_mean(fit, par = 'mu')[, 'mean-all chains']
v <- get_posterior_mean(fit, par = 'v')[, 'mean-all chains']
sigma_irreg <- get_posterior_mean(fit, par = 'sigma_irreg')[, 'mean-all chains']
sigma_level <- get_posterior_mean(fit, par = 'sigma_level')[, 'mean-all chains']
sigma_drift <- get_posterior_mean(fit, par = 'sigma_drift')[, 'mean-all chains']
# stopifnot(is.almost.fitted(mu[[1]], 7.4157))
is.almost.fitted(mu[[1]], 7.4157)
## [1] "Result is 7.41772781583637"
## [1] FALSE
# stopifnot(is.almost.fitted(v[[1]], 0.00028896))
is.almost.fitted(v[[1]], 0.00028896)
## [1] "Result is 0.00131954475263139"
## [1] FALSE
stopifnot(is.almost.fitted(sigma_irreg^2, 0.0021181))
stopifnot(is.almost.fitted(sigma_level^2, 0.012128))
stopifnot(is.almost.fitted(sigma_drift^2, 1.5e-11))
title <- 'Figure 3.1. Trend of stochastic linear trend model.'
title <- '図 3.1 確率的線形トレンド・モデルのトレンド'
# 原系列
p <- autoplot(y)
# stan
yhat <- ts(mu, start = start(y), frequency = frequency(y))
p <- autoplot(yhat, p = p, ts.colour = 'blue')
p + ggtitle(title)
fmt <- function(){
function(x) format(x, nsmall = 5, scientific = FALSE)
}
title <- 'Figure 3.2. Slope of stochastic linear trend model.'
title <- '図 3.2 確率的線形トレンド・モデルの傾き'
slope <- ts(v, start = start(y), frequency = frequency(y))
autoplot(slope) + scale_y_continuous(labels = fmt()) + ggtitle(title)
## Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale.
title <- 'Figure 3.3. Irregular component of stochastic linear trend model.'
title <- '図 3.3 確率的線形トレンド・モデルに対する不規則要素'
autoplot(y - yhat, ts.linetype = 'dashed') + ggtitle(title)