pffun <- function(beta, x ,y ) { # beta[1] : mu1 , beta[2] : mu2 , beta[3] : sigma1 , beta[4] : sigma2 , beta[5] : rho ifelse( beta[3] < 0 | beta[4] < 0 , l<- -Inf , # 確率密度(pdf): dxxx(q):q は確率点を表す # xとyの共分散 mean((x-mean(x))*(y-mean(y))) l <- sum(log(dmvnorm(matrix(c(x,y),ncol=2), mean=c(beta[1],beta[2]) , # sigma=matrix(c(beta[3]^2,mean((x-beta[1])*(y-beta[2])),mean((x-beta[1])*(y-beta[2])),beta[3]^2),ncol=2))))) sigma=matrix(c(beta[3]^2,beta[3]*beta[4]*beta[5],beta[3]*beta[4]*beta[5],beta[4]^2),ncol=2))))) return(l) } # chains <- 1:5 seeds <- seq(1,5,1) init<-c(0,0,30,30,0) burnin<-2000 mcmc_n<-200000 thin<- verbose <-10 #sink("./likelihood.txt") DEF <- lapply(chains , function(chain) { MCMCmetrop1R(fun = pffun , theta.init = init , burnin = burnin, mcmc = mcmc_n ,thin=thin, # verbose= verbose, seed = seeds[chain], x=x1,y=x2 )}) # sink() # system("gawk '/function value/' ./likelihood.txt | gawk 'gsub(\"function value =\",\"\")' > ./def_lik.txt") # l<-scan("./def_lik.txt") # ll<-matrix(l,ncol=length(chains),byrow = FALSE) # head(ll) ; tail(ll) # lll<-ll[-c(1 : burnin/thin),] # ( waic2 <- waic(matrix(lll,ncol=1)) ) ######## waic 217.0 ####### # # WAIC : EQU=213.5 < 217=DEF --> EQUを採用する # DEF.mcmc <- mcmc.list(DEF) # #plot(DEF.mcmc, trace = TRUE, density = TRUE) #summary(DEF.mcmc) #gelman.diag(DEF.mcmc) #effectiveSize(DEF.mcmc) # df<-data.frame(mu1=unlist(DEF.mcmc[,1]),mu2=unlist(DEF.mcmc[,2]), sigma1=unlist(DEF.mcmc[,3]),sigma2=unlist(DEF.mcmc[,4]),rho=unlist(DEF.mcmc[,5]) ) # ryou<-data.frame(c(round(mean(df[,1]),2) , round(sd(df[,1]),2) , round(quantile(df[,1],c(0.025,0.05,0.5,0.95,0.975)),2))) for (i in 2:ncol(df) ){ ryou<-cbind(ryou,data.frame(c(round(mean(df[,i]),2) , round(sd(df[,i]),2) , round(quantile(df[,i],c(0.025,0.05,0.5,0.95,0.975)),2)))) } names(ryou)<-c("mu1","mu2","sigma1","sigma2","rho") rownames(ryou)<-c("EAP","post.sd","2.5%","5%","50%","95%","97.5%") mu1_mu2 <- df$mu1 - df$mu2 ryou<-cbind(ryou,data.frame(c(round(mean(mu1_mu2),2) , round(sd(mu1_mu2),2) , round(quantile(mu1_mu2,c(0.025,0.05,0.5,0.95,0.975)),2)))) names(ryou)<-c("mu1","mu2","sigma1","sigma2","rho","mu1_mu2") #kable(t(ryou)) # set.seed(1234) mu<-matrix(rep(NA,nrow(df)*2),ncol=2) for (i in 1:nrow(df)){ mu[i,]<-rmvnorm(n = 1, mean =c(df$mu1[i],df$mu2[i]), sigma=matrix(c(df$sigma1[i]^2,df$sigma1[i]*df$sigma2[i]*df$rho[i],df$sigma1[i]*df$sigma2[i]*df$rho[i],df$sigma2[i]^2),ncol=2)) } x1aste<-mu[,1] x2aste<-mu[,2] # ryou<-cbind(ryou,data.frame(c(round(mean(x1aste),2) , round(sd(x1aste),2) , round(quantile(x1aste,c(0.025,0.05,0.5,0.95,0.975)),2)))) ryou<-cbind(ryou,data.frame(c(round(mean(x2aste),2) , round(sd(x2aste),2) , round(quantile(x2aste,c(0.025,0.05,0.5,0.95,0.975)),2)))) # names(ryou)<-c("mu1","mu2","sigma1","sigma2","rho","mu1_mu2","x1*","x2*") kable(t(ryou))
|