I am having trouble using the brms::kfold
function with models that have been fit with brms.backend = "cmdstanr"
. I get an error telling me that the model [is] not compiled. I only get this error when saving and loading models in two different R sessions.
Here is a minimal, reproducible example:
# Load packages
library(tidyverse)
library(brms)
# Options
options(
mc.cores = parallel::detectCores(),
brms.backend = "cmdstanr"
)
# Fit models
m1_fit <- brm(
count ~ 1 + (1|patient),
data = epilepsy,
family = poisson()
)
m2_fit <- brm(
count ~ 1 + zAge + zBase * Trt + (1|patient),
data = epilepsy,
family = poisson()
)
# Save results
write_rds(m1_fit, "m1_fit.rds")
write_rds(m2_fit, "m2_fit.rds")
After running this code, I restart R and run the following code in a new R session:
# Load packages
library(tidyverse)
library(brms)
# Options
options(
mc.cores = parallel::detectCores(),
brms.backend = "cmdstanr"
)
# Load results
m1_fit <- read_rds("m1_fit.rds")
m2_fit <- read_rds("m2_fit.rds")
# Compare models
kfold(
m1_fit,
m2_fit,
chains = 1
)
I get the following error message:
Fitting model 1 out of 10
Fitting model 2 out of 10
Fitting model 3 out of 10
Fitting model 4 out of 10
Fitting model 5 out of 10
Fitting model 6 out of 10
Fitting model 7 out of 10
Fitting model 8 out of 10
Fitting model 9 out of 10
Fitting model 10 out of 10
Start sampling
Error: Model not compiled. Try running the compile() method first.
I suspect that it has something to do with the issues described in the cmdstanr
documentation on the save_object
function:
This method is a wrapper around
base::saveRDS()
that ensures that all posterior draws and diagnostics are saved when saving a fitted model object. Because the contents of the CmdStan output CSV files are only read into R lazily (i.e., as needed), the$save_object()
method is the safest way to guarantee that everything has been read in before saving.
- Operating System: Windows 10 x64 (build 19043)
- brms Version: 2.15.0
Thank you in advance!