Skip to content

Instantly share code, notes, and snippets.

@mrecos
Created January 22, 2020 03:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrecos/db6efbc884de6f54e677606d612fd86d to your computer and use it in GitHub Desktop.
Save mrecos/db6efbc884de6f54e677606d612fd86d to your computer and use it in GitHub Desktop.
Example of brms model for fitting Bayesian (Stan) categorical model in R
library(brms)
library(tidyverse)
library(caret)
rstan_options(auto_write=TRUE)
options(mc.cores=parallel::detectCores ()) # Run on multiple cores
set.seed(3875)
ir <- data.frame (scale (iris[, -5]), Species=iris[, 5])
system.time (b2 <- brm (Species ~ Petal.Length + Petal.Width + Sepal.Length + Sepal.Width,
data=ir, family="categorical",
prior=c(set_prior("normal (0, 8)"))))
pred <- predict(b2)
pred2 <- as.data.frame(pred) %>%
mutate(actual = as.character(ir$Species),
pred = colnames(pred)[max.col(pred,ties.method="first")],
pred = str_remove(pred,"P\\(Y = "),
pred = str_remove(pred,"\\)"),
actual = factor(actual),
pred = factor(pred))
confusionMatrix(pred2$pred, pred2$actual)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment