我目前正在从R
的rstan
包中运行stan_glm
和stan_glmer
等函数。我对每个函数调用了1000次,结果发现大约75%的运行都会产生如下警告:
Warning messages:
1: There were 184 divergent transitions after warmup. Increasing adapt_delta above 0.95 may help. See
http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup
2: There were 1 chains where the estimated Bayesian Fraction of Missing Information was low. See
http://mc-stan.org/misc/warnings.html#bfmi-low
3: Examine the pairs() plot to diagnose sampling problems
4: Markov chains did not converge! Do not analyze results!
我想创建一个while循环来重新运行这个函数,直到我遇到一个没有警告的运行。有没有办法标记或检测上面这样的警告消息?谢谢。
发布于 2018-05-28 10:22:00
您可以使用tryCatch()函数来捕获错误和警告,并根据结果调整您的工作流,即:
x = -3.5
repeat{
x <- x + 0.6
print( paste("Current value of x is", x) )
result <- tryCatch( log( x ),
error = function(e) e,
warning = function(w) w )
if (inherits(result,"warning")) next # For warnings - continue the next iteration
if (inherits(result,"error")) stop( result ) # For errors - stop
print( paste0(" log(",x,")=", result))
break
}
# [1] "Current value of x is -2.9"
# [1] "Current value of x is -2.3"
# [1] "Current value of x is -1.7"
# [1] "Current value of x is -1.1"
# [1] "Current value of x is -0.5"
# [1] "Current value of x is 0.1"
# [1] " log(0.1)=-2.30258509299404"
但是,要非常小心使用repeat和while循环,因为您可能最终会创建无限循环。检查循环执行了多少次迭代并在迭代次数过多的情况下中止它可能是一个好主意:
x = -3.5
iter <- 0
while (iter < 100) {
x <- x + 0.6
iter <- iter + 1
print( paste("Current value of x is", x) )
result <- tryCatch( log( x ),
error = function(e) e,
warning = function(w) w )
if (inherits(result,"warning")) next # For warnings - continue the next iteration
if (inherits(result,"error")) stop( result ) # For errors - stop
print( paste0(" log(",x,")=", result))
break
}
https://stackoverflow.com/questions/50557228
复制相似问题