Как обнаружить предупреждения в R и запустить цикл while для функции во время вывода предупреждений? - PullRequest
0 голосов
/ 28 мая 2018

В настоящее время я использую такие функции, как stan_glm и stan_glmer из пакета rstan в R.Я вызываю каждую функцию 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, который перезапускает функцию доЯ сталкиваюсь с пробегом без предупреждения.Есть ли способ пометить или обнаружить такие предупреждающие сообщения, как указано выше?Спасибо.

1 Ответ

0 голосов
/ 28 мая 2018

Вы можете использовать функцию 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 
}
...