rstanarm (version 2.21.4)

predictive_error.stanreg: In-sample or out-of-sample predictive errors


This is a convenience function for computing \(y - y^{rep}\) (in-sample, for observed \(y\)) or \(y - \tilde{y}\) (out-of-sample, for new or held-out \(y\)). The method for stanreg objects calls posterior_predict internally, whereas the method for matrices accepts the matrix returned by posterior_predict as input and can be used to avoid multiple calls to posterior_predict.


# S3 method for stanreg
  newdata = NULL,
  draws = NULL,
  re.form = NULL,
  seed = NULL,
  offset = NULL,

# S3 method for matrix predictive_error(object, y, ...)

# S3 method for ppd predictive_error(object, y, ...)


A draws by nrow(newdata) matrix. If newdata is not specified then it will be draws by nobs(object).



Either a fitted model object returned by one of the rstanarm modeling functions (a stanreg object) or, for the matrix method, a matrix of draws from the posterior predictive distribution returned by posterior_predict.

newdata, draws, seed, offset, re.form

Optional arguments passed to posterior_predict. For binomial models, please see the Note section below if newdata will be specified.


Currently ignored.


For the matrix method only, a vector of \(y\) values the same length as the number of columns in the matrix used as object. The method for stanreg objects takes y directly from the fitted model object.

See Also

posterior_predict to draw from the posterior predictive distribution without computing predictive errors.


Run this code
if (.Platform$OS.type != "windows" || .Platform$r_arch != "i386") {
if (!exists("example_model")) example(example_model)
err1 <- predictive_error(example_model, draws = 50)

# Using newdata with a binomial model
nd <- data.frame(
 size = c(10, 20), 
 incidence = c(5, 10), 
 period = factor(c(1,2)), 
 herd = c(1, 15)
err2 <- predictive_error(example_model, newdata = nd, draws = 10, seed = 1234)

# stanreg vs matrix methods
fit <- stan_glm(mpg ~ wt, data = mtcars, iter = 300)
preds <- posterior_predict(fit, seed = 123)
  predictive_error(fit, seed = 123),
  predictive_error(preds, y = fit$y)

Run the code above in your browser using DataCamp Workspace