You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不重复拟合时捕获R中brms::brm()的模型拟合特定警告

Capture brms Model Warnings Without Resetting Global State or Refitting

Wrapper Function to Capture Warnings During Fitting

First, create a wrapper around brms::brm() that captures warnings during model fitting and stores them as an attribute directly on the model object:

fit_brm_with_warnings <- function(...) {
  captured_warnings <- list()
  
  # Capture warnings while allowing them to print normally
  model <- withCallingHandlers(
    brms::brm(...),
    warning = function(warn) {
      captured_warnings <<- c(captured_warnings, list(warn$message))
      return(NULL) # Let the warning print to console
    }
  )
  
  # Attach warnings to the model as an attribute
  attr(model, "brms_captured_warnings") <- captured_warnings
  return(model)
}

Retrieve Warnings with a Custom Function

Next, create the get_model_warnings() function to extract and display the stored warnings:

get_model_warnings <- function(model) {
  warnings <- attr(model, "brms_captured_warnings")
  
  if (is.null(warnings)) {
    message("No warnings captured for this model. Did you fit it using fit_brm_with_warnings()?")
    return(invisible(NULL))
  }
  
  # Print warnings in standard R format
  cat("Warning messages:\n")
  for (i in seq_along(warnings)) {
    cat(sprintf("%d: %s\n", i, warnings[[i]]))
  }
  
  # Return the list of warnings invisibly for further processing
  invisible(warnings)
}

Example Usage

Fit your model with the wrapper, then retrieve warnings anytime later:

# Fit the model (warnings will print during fitting as usual)
mdl <- fit_brm_with_warnings(
  Sepal.Length ~ Sepal.Width*Petal.Length*Petal.Width,
  data = iris,
  seed = 123
)

# Retrieve and display warnings at any time
get_model_warnings(mdl)

Advantages Over Your Current Approach

  • No global warning reset: This method only captures warnings from the specific brm() call, leaving all previous warnings in your script untouched.
  • Persistent warnings: Warnings are stored directly with the model object, so you don't need to capture them immediately after fitting—you can retrieve them days later without refitting.
  • Preserves real-time feedback: Warnings still print to the console during fitting, so you don't miss important alerts while the model runs.

Note on Existing Models

If you already fitted a model without using this wrapper, there's no way to retroactively recover its warnings (brms doesn't store warnings by default). You'll need to refit the model with fit_brm_with_warnings() if you want to capture its warnings.

内容的提问来源于stack exchange,提问作者mat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 17:52:49