
【Rでベイズ統計モデリング#17】ローカルレベルモデル
記事の目的
状態空間モデルであるローカルレベルモデルのベイズ推定を、RとStanを使用して実装していきます。データの作成から実装するので、コピペで再現することが可能です。
目次
0 前準備
0.1 今回のモデル

0.2 ワーキングディレクトリの設定
以下の画像のようにワーキングディレクトリを設定します。設定したディレクトリに、RファイルとStanファイルを保存します。

1 ライブラリ
# 1 ライブラリ library(dplyr) library(ggplot2) library(rstan) library(bayesplot) set.seed(1) rstan_options(auto_write=TRUE) options(mc.cores=parallel::detectCores())
2 データ
2.1 コード
# 2 データ
日付 <- seq(as.POSIXct("2021/05/01"), as.POSIXct("2021/08/01"), "days")
売り上げ <- c()
mu <- c()
mu[1] <- rnorm(1, 200, 10) %>% round(1)
T <- length(日付)
for(t in 2:T){
  mu[t] <- rnorm(1, mu[t-1], 5)
}
for(t in 1:T){
  売り上げ[t] <- rnorm(1, mu[t], 3) 
}
data <- data.frame(日付, 売り上げ)
data %>% head()
plot <- ggplot() +
  geom_point(aes(x=data$日付, y=data$売り上げ))+
  geom_line(aes(x=data$日付, y=data$売り上げ))+
  theme_classic(base_family = "HiraKakuPro-W3") +
  theme(text = element_text(size = 30))+
  labs(x="日付",y="売り上げ",title="売り上げの推移") +
  scale_x_datetime(date_labels = "%m/%d")
plot
2.2 結果
| 14行目の結果 | 23行目の結果 | 
|  |  | 
3 Stanの利用
3.1 Stanファイル
data {
  int T;
  vector[T] y;
  
  int T_pred;
}
parameters {
  vector[T] mu;
  real<lower=0> sigma_w;
  real<lower=0> sigma_v;
}
model {
  mu[2:T] ~ normal(mu[1:(T-1)], sigma_w);
  y ~ normal(mu, sigma_v);
}
generated quantities{
  vector[T+T_pred] mu_pred;
  vector[T+T_pred] y_pred;
  
  mu_pred[1:T] = mu;
  for(t in 1:T_pred){
    mu_pred[T+t] = normal_rng(mu_pred[T+t-1], sigma_w);
  }
  for(t in 1:(T+T_pred)){
    y_pred[t] = normal_rng(mu_pred[t], sigma_v);
  }
}
3.2 Stanを利用するRのコード
# 3 stanの利用 data_list <- list( T = nrow(data), y = data$売り上げ, T_pred = 10 ) mcmc_result <- stan( file="17ローカルレベルモデル.stan", data=data_list, seed=1, iter = 2000, warmup = 200, chains = 3, thin=1 )
4 分析結果
4.1 コード
# 4 分析結果
## 4.1 推定結果
print(mcmc_result, pars=c("sigma_w", "sigma_v"), probs = c(0.025, 0.5, 0.975))
## 4.2 収束の確認
mcmc_sample <- rstan::extract(mcmc_result, permuted=FALSE)
mcmc_combo(mcmc_sample, pars=c("sigma_w","sigma_v"))
## 4.3 μの確認
mcmc_sample <- rstan::extract(mcmc_result)
func <- function(x){
  return (quantile(x, c(0.025, 0.5, 0.975)))
}
mu_pred <- apply(mcmc_sample[["mu_pred"]], 2, func)
日付_pred <- seq(as.POSIXct("2021/05/01"), as.POSIXct("2021/08/11"), "days")
plot + 
  labs(title="μの推定結果") +
  geom_line(aes(x=日付_pred, y=mu_pred[2,]), col="blue") + 
  geom_ribbon(aes(x=日付_pred, ymin=mu_pred[1,], ymax=mu_pred[3,]), alpha=0.5, fill="gray", col="blue")
## 4.4 予測分布
y_pred <- apply(mcmc_sample[["y_pred"]], 2, func)
plot +
  labs(title="予測分布") +
  geom_line(aes(x=日付_pred, y=y_pred[2,]), col="blue") + 
  geom_ribbon(aes(x=日付_pred, ymin=y_pred[1,], ymax=y_pred[3,]), alpha=0.5, fill="gray", col="blue")
4.2 結果
| 3行目の結果 | 7行目の結果 | 
|  |  | 
| 17行目の結果 | 25行目の結果 | 
|  |  | 
 
                          
                          
                         