简体   繁体   English

如何在 R 中使用不同的 set.seed() 多次运行相同的模型?

[英]How to run same model multiple times with different set.seed() in R?

I would like to run the following model three times with a different seed.我想用不同的种子运行以下模型三次。 For example, the following model is run with seed 314159例如,以下模型使用种子314159运行

set.seed(314159)
    x <- c(11, 5, 2, -5, 7, 2, -11, 9, -5, -5, -4, 17, 2, -10, -11, -10,
           -4, 2, 1, 13)
    a <- 0.1
    b <- 0.1
    c <- 0
    d <- 100^2

    M <- 1e3
    sample <- array(NA, dim=c(M,2))
    mu <- mean(x)
    sig2 <- var(x)
    for( m in 1:M ){
      mu <- rnorm(1, (length(x) + 1/d)^(-1) * (sum(x) + c/d),
                  sqrt( sig2/(length(x) + 1/d) ))
      sig2 <- rigamma(1, .5*length(x)+a+.5,
                      .5*sum( (x-mu)^2 ) + 1/(2*d)*(mu-c)^2 + b )
      sample[m,] <- c(mu,sig2)
    }
    plot( density( sample[,1] ))
    plot( density( sample[,2] ))

If I want to run the same model for seed 523626 and 626789 , Can I do it using any for loop?如果我想为种子523626626789运行相同的模型,我可以使用任何 for 循环吗? Any help is appreciated?任何帮助表示赞赏?

Put the code in the function将代码放入函数中

apply_fun <- function() {
  x <- c(11, 5, 2, -5, 7, 2, -11, 9, -5, -5, -4, 17, 2, -10, -11, -10,-4, 2, 1, 13)
  a <- 0.1
  b <- 0.1
  c <- 0
  d <- 100^2
  M <- 1e3
  sample <- array(NA, dim=c(M,2))
  mu <- mean(x)
  sig2 <- var(x)
  for( m in 1:M ){
    mu <- rnorm(1, (length(x) + 1/d)^(-1) * (sum(x) + c/d),
            sqrt( sig2/(length(x) + 1/d) ))
    sig2 <- rigamma(1, .5*length(x)+a+.5,
                .5*sum( (x-mu)^2 ) + 1/(2*d)*(mu-c)^2 + b )
    sample[m,] <- c(mu,sig2)
  }
   plot( density( sample[,1] ))
   plot( density( sample[,2] ))
}

and then use lapply over each seed value然后在每个种子值上使用lapply

output <- lapply(c(314159, 523626, 626789), function(x) {set.seed(x);apply_fun()})

where rigamma is rigamma在哪里

rigamma = function(n, a, b) return(1/rgamma(n, shape = a, rate = b))

You can just loop over seeds你可以循环种子

library(LearnBayes)
seeds <- c(314159,523626,626789)

for (seed in seeds) {
  set.seed(seed)
  x <- c(11, 5, 2, -5, 7, 2, -11, 9, -5, -5, -4, 17, 2, -10, -11, -10,
    -4, 2, 1, 13)
  a <- 0.1
  b <- 0.1
  c <- 0
  d <- 100^2

  M <- 1e3
  sample <- array(NA, dim=c(M,2))
  mu <- mean(x)
  sig2 <- var(x)
  for( m in 1:M ){
    mu <- rnorm(1, (length(x) + 1/d)^(-1) * (sum(x) + c/d),
      sqrt( sig2/(length(x) + 1/d) ))
    sig2 <- rigamma(1, .5*length(x)+a+.5,
      .5*sum( (x-mu)^2 ) + 1/(2*d)*(mu-c)^2 + b )
    sample[m,] <- c(mu,sig2)
  }
  plot( density( sample[,1] ))
  plot( density( sample[,2] ))
}

Created on 2020-01-12 by the reprex package (v0.3.0)reprex 包(v0.3.0) 于 2020 年 1 月 12 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM