0

我正在尝试运行一个简单的rstan示例,使用plyranddoMC进行并行计算。如果我在底部附近注释掉,则以下代码正常完成registerDoMC(cores = 2),但照原样,我的R会话在调用adply. 我在 Mac OS 10.11.5 上使用 R 版本 3.3.0 和 R GUI。

编辑:奇怪的是,这可以通过R CMD BATCH命令行在 Linux 服务器和我的 Mac 上运行。不过,仍然没有 R GUI。

library(rstan)
library(doMC)
library(plyr)

model = stan_model(model_code = "
data {
  int k; // number of observations per subject
  real theta; // hierarchical mean of the mu's, estimated beforehand (empirical Bayes)
  vector[k] subject; // subject-specific data
}
parameters {
  real mu; // subject-specific mean
}
model { 
  mu ~ normal(theta, 1) ;
  for(i in 1:k)
    subject[i] ~ normal(mu, 1);
}")

single_subject = function(model, subject, theta){
  diverge = TRUE
  attempt = 1

  while (diverge) {
    print(paste("Attempt", attempt))
    .mcmc = sampling(model, pars = "mu", iter = 2000*attempt, thin = attempt, verbose = F,
                     data = list(k = length(subject), theta = theta, subject = subject))
    .summary = summary(.mcmc)$summary
    diverge = any(.summary[,"n_eff"] < 1000)
    attempt = attempt + 1
  }

  .summary["mu",]
}

n = 100 # number of subjects
k = 32 # number of observations per subject
dataset = matrix(rnorm(n*k), ncol = k)
theta = 0 # could be estimated from the data beforehand

start = proc.time()
out = adply(dataset, 1, function(subject) single_subject(model, subject, theta))
serial_time = proc.time() - start

start = proc.time()
registerDoMC(cores = 2)
out = adply(dataset, 1, 
  function(subject) single_subject(model, subject, theta),
  .parallel = T,
  .paropts = list(.export=c("single_subject", "model", "subject", "theta"), 
                  .packages="rstan"))
registerDoSEQ()
parallel_time = proc.time() - start

cat("Serial time:\n")
print(serial_time)

cat("Parallel time:\n")
print(parallel_time)

write.csv(out, "mu.csv")
4

0 回答 0