Giter VIP home page Giter VIP logo

brms's Introduction

Build Status Coverage Status CRAN Version Codewake

brms

The brms package provides an interface to fit Bayesian generalized (non-)linear mixed models using Stan, which is a C++ package for obtaining Bayesian inference using the No-U-turn sampler (see http://mc-stan.org/). The formula syntax is very similar to that of the package lme4 to provide a familiar and simple interface for performing regression analyses.

How to use brms

library(brms)

As a simple example, we use poisson regression to model the seizure counts in epileptic patients to investigate whether the treatment (represented by variable Trt_c) can reduce the seizure counts. Three random intercepts are incorporated to account for the variance between patients and visits, as well as for the residual variance.

fit <- brm(count ~ log_Age_c + log_Base4_c * Trt_c + (1|patient) + (1|visit) + (1|obs), 
           data = epilepsy, family = "poisson")
#> Compiling the C++ model

The results (i.e. posterior samples) can be investigated using

summary(fit, waic = TRUE) 
#>  Family: poisson (log) 
#> Formula: count ~ log_Age_c + log_Base4_c * Trt_c + (1 | patient) + (1 | visit) + (1 | obs) 
#>    Data: epilepsy (Number of observations: 236) 
#> Samples: 4 chains, each with iter = 2000; warmup = 1000; thin = 1; 
#>          total post-warmup samples = 4000
#>    WAIC: 1146.37
#>  
#> Group-Level Effects: 
#> ~obs (Number of levels: 236) 
#>               Estimate Est.Error l-95% CI u-95% CI Eff.Sample Rhat
#> sd(Intercept)     0.37      0.04     0.29     0.46       1379    1
#> 
#> ~patient (Number of levels: 59) 
#>               Estimate Est.Error l-95% CI u-95% CI Eff.Sample Rhat
#> sd(Intercept)      0.5      0.07     0.37     0.65        996    1
#> 
#> ~visit (Number of levels: 4) 
#>               Estimate Est.Error l-95% CI u-95% CI Eff.Sample Rhat
#> sd(Intercept)     0.11      0.11        0     0.41        747    1
#> 
#> Population-Level Effects: 
#>                   Estimate Est.Error l-95% CI u-95% CI Eff.Sample Rhat
#> Intercept             1.56      0.11     1.34     1.77        581 1.01
#> log_Age_c             0.48      0.37    -0.25     1.24       1178 1.00
#> log_Base4_c           1.06      0.11     0.85     1.28       1218 1.00
#> Trt_c                -0.34      0.16    -0.65    -0.03       1128 1.00
#> log_Base4_c:Trt_c     0.35      0.22    -0.09     0.77        878 1.00
#> 
#> Samples were drawn using sampling(NUTS). For each parameter, Eff.Sample 
#> is a crude measure of effective sample size, and Rhat is the potential 
#> scale reduction factor on split chains (at convergence, Rhat = 1).

On the top of the output, some general information on the model is given, such as family, formula, number of iterations and chains, as well as the WAIC, which is an information criterion for Bayesian models. Next, random effects are displayed seperately for each grouping factor in terms of standard deviations and (in case of more than one random effect per grouping factor; not displayed here) correlations between random effects. On the bottom of the output, fixed effects are displayed. If incorporated, autocorrelation effects and family specific parameters (e.g., the residual standard deviation 'sigma' in normal models) are also given.

In general, every parameter is summarized using the mean ('Estimate') and the standard deviation ('Est.Error') of the posterior distribution as well as two-sided 95% Credible intervals ('l-95% CI' and 'u-95% CI') based on quantiles. The last two values ('Eff.Sample' and 'Rhat') provide information on how well the algorithm could estimate the posterior distribution of this parameter. If 'Rhat' is considerably greater than 1, the algorithm has not yet converged and it is necessary to run more iterations and / or set stronger priors.

To visually investigate the chains as well as the posterior distributions, you can use

plot(fit) 

An even more detailed investigation can be achieved by applying the shinystan package:

launch_shiny(fit) 

There are several methods to compute and visualize model predictions. Suppose that we want to predict responses (i.e. seizure counts) of a person in the treatment group (Trt_c = 0.5) and in the control group (Trt_c = -0.5) with average age and average number of previous seizures at the fourth visit. Than we can use

newdata <- data.frame(Trt_c = c(0.5, -0.5), log_Age_c = 0, 
                      log_Base4_c = 0, visit = 4)
predict(fit, newdata = newdata, allow_new_levels = TRUE, probs = c(0.05, 0.95))
#>   Estimate Est.Error 5%ile 95%ile
#> 1  4.73075  3.901161     0     12
#> 2  6.60975  5.264350     1     17

We need to set allow_new_levels = TRUE because we want to predict responses of a person that was not present in the data used to fit the model. While the predict method returns predictions of the responses, the fitted method returns predictions of the regression line.

fitted(fit, newdata = newdata, allow_new_levels = TRUE, probs = c(0.05, 0.95))
#>   Estimate Est.Error    5%ile   95%ile
#> 1 4.711550  3.268968 1.366518 10.79041
#> 2 6.582059  4.595984 1.966401 14.82510

Both methods return the same etimate (up to random error), while the latter has smaller variance, because the uncertainty in the regression line is smaller than the uncertainty in each response. If we want to predict values of the original data, we can just leave the newdata argument empty.

A related feature is the computation and visualization of marginal effects, which can help in better understanding the influence of the predictors on the response.

plot(marginal_effects(fit, probs = c(0.05, 0.95)))

For a complete list of methods to apply on brms models see

methods(class = "brmsfit") 
#>  [1] as.data.frame     as.matrix         as.mcmc           coef             
#>  [5] expose_functions  family            fitted            fixef            
#>  [9] formula           hypothesis        launch_shiny      logLik           
#> [13] LOO               marginal_effects  model.frame       ngrps            
#> [17] nobs              pairs             parnames          plot             
#> [21] posterior_samples predict           print             prior_samples    
#> [25] ranef             residuals         stancode          standata         
#> [29] stanplot          summary           update            VarCorr          
#> [33] vcov              WAIC             
#> see '?methods' for accessing help and source code

Details on formula syntax, families and link functions, as well as prior distributions can be found on the help page of the brm function:

help(brm) 

More instructions on how to use brms are given in the package's vignette.

vignette("brms") 

FAQ

How do I install brms?

To install the latest release version from CRAN use

install.packages("brms")

The current developmental version can be downloaded from github via

library(devtools)
install_github("paul-buerkner/brms")

Because brms is based on Stan, a C++ compiler is required. The program Rtools (available on https://cran.r-project.org/bin/windows/Rtools/) comes with a C++ compiler for Windows. On Mac, you should install Xcode. For further instructions on how to get the compilers running, see the prerequisites section on https://github.com/stan-dev/rstan/wiki/RStan-Getting-Started.

Can I avoid compiling models?

When you fit your model for the first time with brms, there is currently no way to avoid compilation. However, if you have already fitted your model and want to run it again, for instance with more samples, you can do this without recompilation by using the update method (type help(update.brmsfit) in R for more details).

What is the difference between brms and rstanarm?

rstanarm is an R package similar to brms that also allows to fit regression models using Stan for the backend estimation. Contrary to brms, rstanarm comes with precompiled code to save the compilation time (and the need for a C++ compiler) when fitting a model. However, as brms generates its Stan code on the fly, it offers more flexibility in model specification than rstanarm. Also, multilevel models are currently fitted a bit more efficiently in brms. For a detailed comparison of brms with other common R packages implementing multilevel models, type vignette("brms") in R.

What is the best way to ask a question or propose a new feature?

Questions can be asked on codewake. To propose a new feature or report a bug, please open an issue on github. Of course, you can always write me an email ([email protected]).

brms's People

Contributors

mages avatar paul-buerkner avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.