Quantcast
Viewing all articles
Browse latest Browse all 123

RStan でベイズ逆問題もどき

Image may be NSFW.
Clik here to view.
y_i = p_i A +\varepsilon_i
, Image may be NSFW.
Clik here to view.
 0\le p_i \le 1
という系列を考える。Aは定数。

(この系列になんらかの解釈があればおもしろかったんだけど思いつかなかった。)

いま、観測されるのは Image may be NSFW.
Clik here to view.
y_i
のみである。

Image may be NSFW.
Clik here to view.
f:id:abrahamcow:20151014032900p:plain

Image may be NSFW.
Clik here to view.
p_i
が既知ならば Aを推定するのはかんたん。Aが既知ならば Image may be NSFW.
Clik here to view.
p_i
を推定するのはかんたん。

しかし、いま観測されるのは Image may be NSFW.
Clik here to view.
y_i
のみ。

Image may be NSFW.
Clik here to view.
A \times p_i
Image may be NSFW.
Clik here to view.
y_i
になる組み合わせは無数にあり、Image may be NSFW.
Clik here to view.
p_i
Aを同時に推定するのは困難に思える。

しかし、以下の仮定を置くことで、Image may be NSFW.
Clik here to view.
p_i
Aを推定することができる。

  • Image may be NSFW.
    Clik here to view.
    p_i
    は区間 [0,1] の一様分布に従う。
  • Image may be NSFW.
    Clik here to view.
    \varepsilon_i
    は平均 0 , 標準偏差σ の正規分布に従う。

推定に用いた Stan のコードはこう。

#inverse.stan
data{
	int<lower=0> N;
	real <lower=0>y[N];}
parameters{
	real <lower=0,upper=1> p[N];
	real <lower=0>sigma;
	real <lower=0>A;}
transformed parameters  {
    real mu1[N];for(i in1:N){
    	mu1[i]<- p[i]*A;}}
model{for(i in1:N){
 	y[i]~ normal(mu1[i], sigma);}}

R のコードはこう。

##データ生成##
set.seed(123)
p <- runif(20)
A <-100
y <- rnorm(20,p*A)
plot(y,type="b")
dat4stan <-list(N=20,y=y)############
model1 <- stan_model("inverse.stan")
fit <- sampling(model1, data=dat4stan)
traceplot(fit,pars=c("A","sigma"))
ex<-extract(fit)##図示##
plot(y,type="b")
lines(apply(ex$mu,2,mean),col="orange")
plot(p,apply(ex$p,2,mean),xlim=c(0,1),ylim=c(0,1),ylab="estimates")
abline(0,1,lty=2)

Aσについて、MCMCサンプリングのトレースラインを描いてみる。収束してくれたようだ。

Image may be NSFW.
Clik here to view.
f:id:abrahamcow:20151014032924p:plain

次に、原系列(黒)と推定値(オレンジ)を重ねてみる。

Image may be NSFW.
Clik here to view.
f:id:abrahamcow:20151014033109p:plain

最後に、横軸に乱数で生成した真の Image may be NSFW.
Clik here to view.
p_i
、縦軸に Image may be NSFW.
Clik here to view.
p_i
の推定値をとりプロットした。

Image may be NSFW.
Clik here to view.
f:id:abrahamcow:20151014033755p:plain

ほぼ一直線上に並んでいることから、Image may be NSFW.
Clik here to view.
p_i
の推定値の妥当さが分かる。

しかしなんでこれが求まってしまうんだろう……?


Viewing all articles
Browse latest Browse all 123

Trending Articles