Prediction of custom family in distributional modelling context

Please also provide the following information in addition to your question:

  • Operating System: Ubuntu 18.04.1
  • brms Version: 2.5.0


I fitted a serie of models using the following reparametrization of gamma distribution :

## Define the new family of distribution
gamma2 <- custom_family(
  "gamma2", dpars = c("mu", "phi"),
  links = c("log", "log"), lb = c(0, 0),
  type = "real"

## Reparametrize the gamma
stan_funs <- "
  real gamma2_lpdf(real y, real mu, real phi) {
    return gamma_lpdf(y | mu * mu / phi, mu / phi);
  real gamma2_rng(real mu, real phi) {
    return gamma_rng(mu * mu / phi, mu / phi);

Because I used this formulation to fit both simple and distributional models, I twicked the predict function like this :

predict_gamma2 <- function(i, draws, ...) {
    mu <- draws$dpars$mu[, i]
    phi <- draws$dpars$phi
    y <- draws$data$Y[i]
    gamma2_rng(mu, phi)
    mu <- draws$dpars$mu[, i]
    phi <- draws$dpars$phi[, i]
    y <- draws$data$Y[i]
    gamma2_rng(mu, phi)

Predict function worked perfectly this spring, but returns now the following error message :

pred <- posterior_predict(models[[trait_prep[1]]], newdata = NewD, robust = T,  allow_new_levels = T)

Error in gamma2_rng(mu, phi) : Expecting a single value: [extent=4000].

Do you have any idea what happen??

Thank you!

Your information is not sufficient to answer this question with certainty, but have you tried calling

expose_functions(<your model>, vectorize = TRUE)

If this does not solve your problem, please provide a minimal reproducible example.

Oh my god, so true, I forgot the “vectorize” argument!

Thank you!!