mjskay / tidybayes

Bayesian analysis + tidy data + geoms (R package)
http://mjskay.github.io/tidybayes
GNU General Public License v3.0
718 stars 59 forks source link

Error on predicted_draws on dirichlet distribution #164

Closed andremrsantos closed 5 years ago

andremrsantos commented 5 years ago

Hi staff,

I am performing some analysis with a Dirichlet regression with the brms package. Unfortunately, when I use add_predicted_draws or predicted_draws the resulting prediction returns NA.

Checking the function in the source, I have found the following step in the fitted_predicted_draws_brmsfit_ function that forces the predicted value into factor.

# predicted_draws.R
  (...)
  prediction_levels = attr(fits_preds, "levels", exact = TRUE)
  if (!is.null(prediction_levels)) {
    fits_preds_df[[output_name]] = factor(
      fits_preds_df[[output_name]],
      levels = seq_along(prediction_levels),
      labels = prediction_levels
    )
  }

Maybe you could consider add an flag variable to check if we wish to convert it into factors.

Here is a code snippet to replicate the error.

library(brms)
library(modelr)
library(tidyverse)

dt <- data.frame(x = rep(c("A", "B"), each = 100))
dt$ANC <- as.matrix(rdirichlet(200, c(1,2,1)))

md <- brm(ANC ~ x, family = dirichlet(), data = dt,
  chains = 2, cores = 2)

predicted_draws(md, data_grid(dt, x))

Thanks for everything

mjskay commented 5 years ago

Oh yeah, that makes sense. Looks like it's an issue with the heuristic I used to identify when categorical models are being used. I should be able to fix this so that the correct output is given without needing you to set a flag manually. Thanks for the legwork tracking down the source of the issue and for the clear report.

It might be a few days until I put a fix out for this as my primary laptop died last night :/

mjskay commented 5 years ago

This should be fixed on the dev branch now. If you want to test it you can install it using this command:

devtools::install_github("mjskay/tidybayes", ref = "dev")

Let me know if you run into any issues.

andremrsantos commented 5 years ago

It worked like a charm, thank you for your quick response