############################################################################################################# # # Example 6.4 Part 2: (pages 216-7) – Figures 6.9 (page 218) - Centered regressor # # In this example time to failure (y) of motorettes were tested at different temperatures. # # A simple linear regression is fit # # t[i] ~ N(alpha + beta z[i],sigma2) # # z[i] = 1000/(x[i]+273.2) # t[i] = log10(y[i]) # # sigma2 = 0.2592 # # Prior: p(alpha,beta) = c # ############################################################################################################## # # Author : Hedibert Freitas Lopes # Graduate School of Business # University of Chicago # 5807 South Woodlawn Avenue # Chicago, Illinois, 60637 # Email : hlopes@ChicagoGSB.edu # ############################################################################################################### loglike = function(m,n,y,x,a,b,s){ max(sum(dnorm(y[1:m],a+b*x[1:m],s,log=T))+ sum(log(1-pnorm(y[(m+1):n],a+b*x[(m+1):n],s))),-5000) } y = c(1764,2772,3444,3542,3780,4860,5196,408,408,1344,1344,1440,408,408,504,504,504, rep(8064,10),rep(5448,3),rep(1680,5),rep(528,5)) x = c(rep(170,7),rep(190,5),rep(220,5),rep(150,10),rep(170,3),rep(190,5),rep(220,5)) y = log10(y) x = 1000/(x+273.2) mx = mean(x) x = x - mx n = 40 m = 17 s = 0.2592 N = 100 as = seq(3.2,3.8,length=N) bs = seq(2.8,6.2,length=N) like = matrix(0,N,N) for (i in 1:N) for (j in 1:N) like[i,j] = loglike(m,n,y,x,as[i],bs[j],s) par(mfrow=c(1,2)) plot(x,y,xlab="Temperatures (Celsius)",ylab="Time to failures (hours)") contour(as,bs,exp(like),xlab="alpha",ylab="beta",drawlabels=F) ################################################################################################################################ # SIMULATIONS # ################################################################################################################################ a0 = c(3.3,3.7,3.7) b0 = c(3,3,5.5) sd = 0.1 nn = length(a0) niter0 = 200 niter = 20000 SIMUL = array(0,c(3,3,niter+1,2)) # [1] Random Walk Metropolis (single move) # ---------------------------------------- set.seed(9237497) draw = array(0,c(3,niter+1,2)) for (j in 1:nn){ a = a0[j] b = b0[j] draws=c(a,b) for (iter in 1:niter){ a1 = rnorm(1,a,sd) accept = min(0,loglike(m,n,y,x,a1,b,s)-loglike(m,n,y,x,a,b,s)) if (log(runif(1))