1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
| # 例6.3での線形回帰
data(cars)
y <- cars$dist
x <- cars$speed
x2 <- x^2
fit <- lm(y ~ x + x2)
loglik <- function(a,b,c,sigma){-(n/2)*log(sigma)-sum((y-a-b*x-c*x2)^2)/(2*sigma)}
logq <- function(a,b,c,sigma){
dnorm(a,mean=a.est[1],sd=a.std,log=T)
+ dnorm(b,mean=b.est[1],sd=b.std,log=T)
+ dnorm(c,mean=c.est[1],sd=c.std,log=T)
- (n/2)*log(sigma) - (n-3)*(15.18)^2/(2*sigma)
}
Niter <- 4000
n <- length(x)
fit.param <- summary(fit)$coef
a.est <- fit.param[1,1]
a.std <- fit.param[1,2]
b.est <- fit.param[2,1]
b.std <- fit.param[2,2]
c.est <- fit.param[3,1]
c.std <- fit.param[3,2]
sig <- 1/rgamma(1, n/2, rate=(n-3)*(15.18)^2/2)
for(i in 2:Niter){
candidate <- c(rnorm(1, mean=a.est[1], sd=a.std),
rnorm(1, mean=b.est[1], sd=b.std),
rnorm(1, mean=c.est[1], sd=c.std),
1/rgamma(1, n/2, rate=(n-3)*(15.18)^2/2)
)
fy <- loglik(candidate[1], candidate[2], candidate[3], candidate[4])
fx <- loglik(a.est[i-1], b.est[i-1], c.est[i-1], sig[i-1])
qxy <- logq(a.est[i-1], b.est[i-1], c.est[i-1], sig[i-1])
qyx <- logq(candidate[1], candidate[2], candidate[3], candidate[4])
rho <- min(1, exp(fy-fx+qxy-qyx))
if (runif(1)<rho){
a.est[i] <- candidate[1]
b.est[i] <- candidate[2]
c.est[i] <- candidate[3]
sig[i] <- candidate[4]
}else{
a.est[i] <- a.est[i-1]
b.est[i] <- b.est[i-1]
c.est[i] <- c.est[i-1]
sig[i] <- sig[i-1]
}
}
s <- seq(4,25,by=0.1)
yhat <- fit$coef[1] + fit$coef[2]*s + fit$coef[3]*s^2
plot(x,y, ylim=c(0,120), xlab="speed", ylab="dist", main="data(cars)", type="n")
for(i in (Niter-500):Niter){
lines(x, a.est[i]+b.est[i]*x+c.est[i]*x2, lwd=2, col="grey")
}
lines(s, yhat, lwd=4, col="orange")
points(x, y, pch=19)
|