14. 13
tyttt trendady ,
1 tt trendtrend
t
t a x
t t-1 ( )
1,, tntn aa
n t t-1
tntnttttt xaxaxaad ,,,2,2,1,1 ・・・
bxaxaxay tnnttt ,,22,11 ...
cf.
15. ( OK)
14
tyttt trendady ,
t
y 0 y
y, 0,~ ty
y,~ ttt trendady
a 0 a
nn ata 0,~, tatntn n
aa ,1,,
n t t-1
natt aa ,~ 1
1,, tntn aa
18. 17
#パッケージの展開
library(rstan)
#入力データをリスト化
d <- read.csv("sample.csv")
T = nrow(d)
N = ncol(d)-1
data <- list(
T = T,
N = N,
y = d[,1],
x = d[,1:N+1]
)
#dataの中身を確認
data
Stan list
data T,x N,y , x
OK
N/A
csv
> data
$T
[1] 53
$N
[1] 6
$y
[1] 6.51 5.85 6.40 6.89 5.97 2.90 3.06 3.19 2.88 3.29 3.60 4.58 4.31
7.17 5.81 5.26 5.23 5.19 3.16 3.14 3.01 2.95 2.89 3.21 3.46 3.50 3.14
3.44 3.64 3.18 3.14 3.42 3.04 2.92 3.26 2.85 3.59 4.29 4.43 3.92 4.58
4.18 2.92 3.19 3.30 2.96 2.86 3.18 3.21 3.36 3.46 3.25 3.76
$x
バナー広告 TVCM 電車A. 電車B. 雑誌A 雑誌B
1 13.18 0 0 0 0 0
2 11.76 0 0 0 0 0
3 11.45 0 0 0 0 0
4 10.46 0 0 0 0 0
5 9.78 0 0 0 0 0
19. Stan
18
#stanを実行する
fit <- stan( file = 'model.stan', data = data, iter = 1500, chains=3)
model.stan fit
file data
iter chains
iter
doParallel
#パッケージのインストール(初回のみでOK)
install.packages(“doParallel", dependencies = TRUE)
run_stan.text 17-29 #
( )
21. 20
#もっとも確からしいパラメータを導出
smp<-extract(fit)
a_est<-matrix(1:T*N,T,N)
for (i in 1:N){
for (t in 1:T) {
tmp<-density(smp$a[,t,i])
a_est[t,i]<-
tmp$x[tmp$y==max(tmp$y)]
}
}
colnames(a_est)<- c("a1","a2","a3","a4","a5","a6")
#↑xの個数に応じて適宜増減
trend_est<-matrix(1:T,T,1)
for (t in 1:T) {
tmp<-density(smp$trend[,t])
trend_est[t]<-tmp$x[tmp$y==max(tmp$y)]
}
colnames(trend_est)<- "trend"
parameters_est<-cbind(a_est,trend_est)
write.table(parameters_est,"parameters.csv")
a
a_est
colnames
x n
an,trend}