How can I use the same function call to sample from posterior when data exists and only sample from prior when not?

I have a brms model where sometimes there is no data, in which case I want brms to sample from the prior just as it normally would the posterior.

Previously, I had code like this:

cond <- ...

if (sum(cond) == 0) {
  samplePrior <- "only"
  cond <- TRUE
} else {
  samplePrior <- "no"
}

model <- brm(
  y ~ . + 0,
  data = X[cond, ],
  samplePrior = samplePrior,
  backend = "cmdstanr",
  ...
)

This worked as of one year ago, or maybe two years. Now, I get:

Error in validate_data():
! All observations in the data were removed presumably because of NA values.
Run rlang::last_trace() to see where the error occurred.
Warning message:
Rows containing NAs were excluded from the model.

How can I dynamically sample from just the prior when I have no data to pass to the model?

What happens if you just give it empty data? If it’s just inheriting Stan’s behavior without imposing additional lower=1 constraints, then you should be able to set y and X to be zero size, at which point the posterior is equal to the prior.

More formally, suppose I have a joint model p(\theta, y, x) = p(y \mid \theta, x) \cdot p(\theta) where y is modeled data, x is unmodeled data/constants, and \theta parameters. If y is empty, then the boundary condition should be p(y \mid \theta, x) = 1, which is what Stan will give you (modulo any contributions from transforms). That’s because the boundary of an empty product is 1 (the multiplicative unit) and the boundary of an empty sum is 0 (the additive unit).

I think the argument name is sample_prior, but even if you fix that you might still get the same error. brms builds a so-called “model frame” from every variable in the model formula and it drops any row containing NAs. If that results in zero rows then you get that error: “All observations in the data were removed.” My guess is that y is NA when you’re getting that error? Is that right?

If that’s right then I think the simplest workaround is to give y a placeholder value. When you set sample_prior = "only" the y values don’t affect anything, they just have to be something. So you could try something like this:

no_data <- !any(cond)

dat <- if (no_data) X else X[cond, ]
if (no_data) dat$y <- 0   # ignored when sampling from the prior

model <- brm(
  y ~ . + 0,
  data = dat,
  prior = my_priors,
  sample_prior = if (no_data) "only" else "no", # sample_prior not samplePrior = ...
  backend = "cmdstanr",
  ...
)

Does that work?

Yes, I mistyped when transcribing my code, I was using sample_prior. I tried setting just the outcome variable y to be 0, leaving all of the feature columns NA, but brm still returns the same error. Is there any consequence to setting all of the X values to 0? In other words, if sample_prior = "only", it will make zero difference to the sampling algorithm what I set X (or y) to?

Edit: Yes, I set the row to all 1s (both X and y, couldn’t set y = 0 because I have gamma response) and now the model has compiled and is now sampling.

My follow-up question would be why does brm care what y (or X) is if it is only sampling from the prior?

brms drops any row with an NA in any variable in the formula and y ~ . makes every column of X a predictor. So if there are NAs anywhere in X the corresponding rows will be removed.

If you set sample_prior = "only" then the likelihood isn’t in the model block, so the values of y and X don’t affect the draws. I think setting them to 0 is ok as long as the prior-only model maintains the same parameters and priors. So I recommend:

  • Set all priors explicitly because I think some brms defaults priors are computed using y (maybe X too, I’m not sure)
  • If X has any factor columns those should be kept as factors with their full levels, and fill them with a valid level, not numeric 0, and use drop_unused_levels = FALSE. That way you don’t lose any coefficients from the model.
  • If drawing from the prior predictive distribution pass your real X variables via newdata

Out of curiosity, how are X and cond built when there’s no data? If X is all NA (e.g. from some kind of a join, or if cond is something like !is.na(y)), then it might be simpler/cleaner to create placeholder data separately. Maybe that could also explain why this behaved differently a year or two ago? I think brms has always dropped rows with NAs so that part wasn’t different.

Careful here, as brms in some cases uses data-dependent priors and model structures. @jonah mentioned this briefly, but it’s worth elaborating: even if you pass your priors explicitly, in brms the prior on the intercept is the prior when all continuous predictors are held at their sample means, not when all predictors are held at zero. Thus, the meaning of the explict intercept prior changes when the data changes. If desired, turn this off using the 0 + Intercept syntax.

Additionally, some model structures, such as spline bases, the width of windows for approximate gaussian process computation, etc are by default chosen in a data-dependent manner. Thus, the model and its prior can change significantly when the data changes, even if you intend to sample with sample_prior = "only".

X is a dataframe of games, some of which have been played, some not. cond filters to the games played, but obviously if no games have been played, then it is FALSE everywhere and X[cond] has zero rows.

I have already explicitly defined my priors and passed them to the stanvars and prior arguments.

Thanks, but I don’t quite understand. I shouldn’t be fitting any intercept at all, my formula is y ~ . + 0. (This is because I have already defined my own intercept-esque column in X, it’s complicated.) Do I still need 0 + Intercept?

I have two models. One is a gamma likelihood and the other is Poisson. Prior for each feature is gaussian in each cases (the prior for the shape of the gamma is itself gamma). So nothing fancy.

So maybe that explains the NAs because if y is missing for unplayed games then every row is dropped by brms when no games have been played.

I would think the unplayed games still have real predictor (X) values, right? So you should be able to pass those rows with just a placeholder y instead of zeroing out X too like I had suggested previously. However, you had mentioned that filling in y by itself still gave you the same error, which makes me think some X columns are also NA for unplayed games. Can you check this?

colSums(is.na(X[!cond, ]))

Because y ~ . uses every column of X, I recommend making sure that only the intended columns are in there (or naming them explicitly in the formula).

A few other things:

sample_prior = "only" removes brms’s likelihood, but I’m pretty sure that any custom code you add to the model block with stanvars is still included. If that code only affects priors that’s fine, but if any of it is for the likelihood then that could potentially interfere with getting the intended sample_prior = "only" behavior.

One other idea, not sure if it will work in your case but could be worth trying. If you use all games with formula y | weights(played) ~ ..., where played is 1 for played games and 0 otherwise (with a placeholder y for unplayed ones), then I think you may be able use that same call in both cases without switching sample_prior. brms multiplies each log-likelihood term by its weight, so if there are no games played you should just get the prior. I haven’t tested this though.

Defining your own intercept column in X is the same as doing 0 + Intercept. The latter is just naming a specific column in the data, whereas your formula with the . includes all columns already. So you don’t need to do both.

I realize I have no idea what’s going on with brms until reading @Jonah and @jsocolar’s responses. Why is something called a “prior” when it’s data dependent? Is this some kind of empirical Bayes method? Do prior predictive checks even make sense in this context?

In case anyone’s confused by the ongoing discussion, I meant setting them to be containers of size zero. Not setting them to have value 0.

What are sample means in this context and how are they available before sampling? How does holding predictors (I assume you’re using that Gelman style to be synonymous with covariate) at zero inform priors? Is there a writeup somewhere about the priors in brms?

We still recommend people set their own priors, in which case none of the data dependent stuff applies. The data dependent part is a way to make sure defaults (which for better or worse are used frequently) are somewhat reasonable / weakly informative. It’s written up in Regression and Other Stories (if I recall correctly) and also in an rstanarm vignette and I think Andrew has written about it other places. I’m not sure if brms does exactly what rstanarm does, but roughly speaking rstanarm uses the scale of the data as part of an adjustment to help make default prior scales more reasonable. Andrew has said he considers it an approximation to a hierarchical model. But you’re right that, strictly speaking, this default prior is not fully “prior”.

I suggested setting y values to 0 because the user’s NAs were causing issues. The 0 isn’t used in this case (when sampling from the prior) so it doesn’t affect anything. Setting y to a zero sized container would require manually editing the brms Stan code (I think).

X is just centered (column means subtracted) before fitting (by default, it can be turned off). This only affects what the prior on the intercept refers to, i.e. the intercept is then the value when X is at its sample average, not when X is 0. Depending on the modeling problem it may be more or less intuitive to think of specifying a prior for the intercept with X centered, so it’s the default but optional. It’s described in that same rstanarm vignette I linked to above. Not sure if there’s a brms specific write up but that rstanarm vignette describes what rstanarm does for priors and I think it’s similar. I think Regression and Other Stories has info on this too. At least those rstanarm priors were decided as part of that book project.

Thanks, @Jonah, that’s really helpful. For the last point, I was assuming sample means were posterior samples, but now I see what’s going on. The problem I often have from looking at data, is that I can detect the rough scale of things, but I have no idea of the uncertainty I’m going to have left in the posterior, which is the real thing we need to scale.

This is true. Which X are zero or non-zero is known before the game, but the actual X values themselves are not. I suppose I could fill in with a dummy value. Or, per your later response, just 0 everything out, assuming that truly won’t affect anything. X only contains columns that should be used in the model (the y column and all features).

So my “full” pipeline is this:

  if (sum(cond) == 0) {
    samplePrior <- "only"
    Xfilt <- X[TRUE, ]
    Xfilt[, ] <- 1
  } else {
    samplePrior <- "no"
    Xfilt <- X[cond, ]
  }

  initFunction <- function() {
    list(
      shape = rgamma(1, phiShape, rate = phiRate),
      b = rmvnorm(1, mean = priorMean, sigma = priorVcov)[1, ]
    )
  }

  stanvars <- stanvar(priorMean) + stanvar(priorVcov)
  brmsPriors <-
    eval(call("prior",
      sprintf("gamma(%f, %f)", priors$phiShape, priors$phiRate),
      class = "shape"
    )) + set_prior("multi_normal(priorMean, priorVcov)")

  modelBayes <- brm(
    y ~ . + 0,
    data = Xfilt,
    family = Gamma(link = "identity"),
    prior = brmsPriors,
    stanvars = stanvars,
    init = initFunction,
    sample_prior = samplePrior,
    chains = 4, threads = threading(2),
    backend = "cmdstanr",
    stan_model_args = list(stanc_options = list("O1")),
    iter = 1125, warmup = 500, cores = 6, refresh = 125
  )

This compiles properly and seems to produce reasonable samples, whether cond is all False or not. A bit clunky but it’ll have to do. You can see the priors for every column, plus the shape, are passed explicitly. Based on the conversation above, it seems like there should be no hidden implicit behavior here, but just want to confirm. Thanks for the help!

That looks OK to me.

In stanvars you’re only passing priorMean and priorVcov as data, so that should be fine (my earlier concern about stanvars affecting the likelihood doesn’t apply). And it doesn’t look like you’re using any data-dependent default priors.

A few small things:

  • If any X variable is a factor or character variable then Xfilt[, ] <- 1 may not work as intended. If that’s the case you can use valid level when filling up those columns, keep the full set of levels, and also use drop_unused_levels = FALSE, like I mentioned in a previous message. But if all X variables are numeric then I think your code should be fine.
  • If you do prior predictive checks using posterior_predict() on the prior-only fit, by default it’s going to use the X that’s all 1s. To avoid that just pass the real X variables via newdata.