{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)
  }
}

データの読み込み

fatalities <- read.table('../data/Norwayfinland.txt', skip = 1)
colnames(fatalities) <- c('year', 'Norwegian_fatalities',
                          'Finnish_fatalities')
norwegian_fatalities <- fatalities[['Norwegian_fatalities']]
norwegian_fatalities <- log(ts(norwegian_fatalities, start = 1970, frequency = 1))
finnish_fatalities <- fatalities[['Finnish_fatalities']]
finnish_fatalities <- log(ts(finnish_fatalities, start = 1970, frequency = 1))

モデル定義

確率的ローカルレベルモデル。

# can use the same model as fig02_03
model_file <- '../models/fig02_03.stan'
cat(paste(readLines(model_file)), sep = '\n')
data {
  int<lower=1> n;
  vector[n] y;
}
parameters {
  # 確率的レベル
  vector[n] mu;
  # レベル撹乱項
  real<lower=0> sigma_level;
  # 観測撹乱項
  real<lower=0> sigma_irreg;
}
transformed parameters {
  vector[n] yhat;
  for(t in 1:n) {
    yhat[t] <- mu[t];
  }
}
model {
  for(t in 2:n)
    mu[t] ~ normal(mu[t-1], sigma_level);
  for(t in 1:n)
    y[t] ~ normal(yhat[t], sigma_irreg);
}
y <- norwegian_fatalities

standata <- within(list(), {
  y <- as.vector(y)
  n <- length(y)
})
stan_fit <- stan(file = model_file, chains = 0)
## 
## TRANSLATING MODEL 'fig02_03' FROM Stan CODE TO C++ CODE NOW.
## COMPILING THE C++ CODE FOR MODEL 'fig02_03' NOW.
fit <- pforeach(i = 1:4, .final = sflist2stanfit)({
  stan(fit = stan_fit, data = standata, chains = 1, seed = i)
})
stopifnot(is.converged(fit))

mu <- get_posterior_mean(fit, par = 'mu')[, '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']
# stopifnot(is.almost.fitted(mu[[1]], 6.3048))
is.almost.fitted(mu[[1]], 6.3048)
## [1] "Result is  6.30715405520974"
## [1] FALSE
stopifnot(is.almost.fitted(sigma_irreg^2, 0.00326838))
# stopifnot(is.almost.fitted(sigma_level^2, 0.0047026))
is.almost.fitted(sigma_level^2, 0.0047026)
## [1] "Result is  0.00585552123038848"
## [1] FALSE
title <- 'Figure 2.5. Stochastic level for Norwegian fatalities.'
title <- '図 2.5 ノルウェイの事故に対する確率的レベル'

# 原系列
p <- autoplot(y)

# stan
yhat <- ts(mu, start = start(y), frequency = frequency(y))
p <- autoplot(yhat, p = p, ts.colour = 'blue')
p + ggtitle(title)

title <- 'Figure 2.6. Irregular component for Norwegian fatalities.'
title <- '図 2.6 ノルウェイの事故に対する確率的要素'
autoplot(y - yhat, ts.linetype = 'dashed') + ggtitle(title)