Estimating Regularized Linear Models with rstanarm
Jonah Gabry and Ben Goodrich
2026-03-09
Source:vignettes/lm.Rmd
lm.RmdIntroduction
This vignette explains how to estimate linear models using the
stan_lm function in the rstanarm
package.
Steps 3 and 4 are covered in more depth by the vignette entitled “How to Use the rstanarm Package”. This vignette focuses on Step 1 when the likelihood is the product of independent normal distributions.
The goal of the rstanarm package is to make Bayesian estimation of common regression models routine. That goal can be partially accomplished by providing interfaces that are similar to the popular formula-based interfaces to frequentist estimators of those regression models. But fully accomplishing that goal sometimes entails utilizing priors that applied researchers are unaware that they prefer. These priors are intended to work well for any data that a user might pass to the interface that was generated according to the assumptions of the likelihood function.
It is important to distinguish between priors that are easy for applied researchers to specify and priors that are easy for applied researchers to conceptualize. The prior described below emphasizes the former but we outline its derivation so that applied researchers may feel more comfortable utilizing it.
Likelihood
The likelihood for one observation under a linear model can be written as a conditionally normal PDF where is a linear predictor and is the standard deviation of the error in predicting the outcome, . The likelihood of the entire sample is the product of individual likelihood contributions.
It is well-known that the likelihood of the sample is maximized when the sum-of-squared residuals is minimized, which occurs when where is a vector that contains the sample means of the predictors, is a matrix of centered predictors, is a -vector of outcomes and is the sample mean of the outcome.
QR Decomposition
The lm function in R actually performs a QR
decomposition of the design matrix,
,
where
and
is upper triangular. Thus, the OLS solution for the coefficients can be
written as
.
The lm function utilizes the QR decomposition for numeric
stability reasons, but the QR decomposition is also useful for thinking
about priors in a Bayesian version of the linear model. In addition,
writing the likelihood in terms of
allows it to be evaluated in a very efficient manner in Stan.
Priors
The key innovation in the stan_lm function in the
rstanarm package is the prior for the parameters in the
QR-reparameterized model. To understand this prior, think about the
equations that characterize the maximum likelihood solutions before
observing the data on
and especially
.
What would the prior distribution of be? We can write its -th element as where is the correlation between the th column of and the outcome, is the standard deviation of the outcome, and is the standard deviation of the column of . Then let where is a unit vector that is uniformly distributed on the surface of a hypersphere. Consequently, is the familiar coefficient of determination for the linear model.
An uninformative prior on would be standard uniform, which is a special case of a Beta distribution with both shape parameters equal to . A non-uniform prior on is somewhat analogous to ridge regression, which is popular in data mining and produces better out-of-sample predictions than least squares because it penalizes , usually after standardizing the predictors. An informative prior on effectively penalizes , which encourages to be closer to the origin.
Lewandowski, Kurowicka, and Joe (2009) derives a distribution for a
correlation matrix that depends on a single shape parameter
,
which implies the variance of one variable given the remaining
variables is
.
Thus, the
is distributed
and any prior information about the location of
can be used to choose a value of the hyperparameter
.
The R2(location, what) function in the
rstanarm package supports four ways of choosing
:
-
what = "mode"andlocationis some prior mode on the interval. This is the default but since the mode of a distribution is the mode only exists if . If , then the user must specify something else forwhat. -
what = "mean"andlocationis some prior mean on the interval, where the mean of a distribution is . -
what = "median"andlocationis some prior median on the interval. The median of a distribution is not available in closed form but if it is approximately equal to . Regardless of whether , theR2function can numerically solve for the value of that is consistent with a given prior median utilizing the quantile function. -
what = "log"andlocationis some (negative) prior value for , where is thedigammafunction. Again, given a prior value for the left-hand side it is easy to numerically solve for the corresponding value of .
There is no default value for the location argument of
the R2 function. This is an informative prior on
,
which must be chosen by the user in light of the research project.
However, specifying location = 0.5 is often safe, in which
case
regardless of whether what is "mode",
"mean", or "median". In addition, it is
possible to specify NULL, in which case a standard uniform
on
is utilized.
We set where is the sample standard deviation of the outcome and is an unknown scale parameter to be estimated. The only prior for that does not contravene Bayes’ theorem in this situation is Jeffreys prior, , which is proportional to a Jeffreys prior on the unknown , . This parameterization and prior makes it easy for Stan to work with any continuous outcome variable, no matter what its units of measurement are.
It would seem that we need a prior for , but our prior beliefs about are already implied by our prior beliefs about and . That only leaves a prior for . The default choice is an improper uniform prior, but a normal prior can also be specified such as one with mean zero and standard deviation .
Posterior
The previous sections imply a posterior distribution for , , , and . The parameters of interest can then be recovered as generated quantities:
The implementation actually utilizes an improper uniform prior on . Consequently, if , then the marginal standard deviation of the outcome implied by the model is the same as the sample standard deviation of the outcome. If , then the marginal standard deviation of the outcome implied by the model exceeds the sample standard deviation, so the model overfits the data. If , then the marginal standard deviation of the outcome implied by the model is less than the sample standard deviation, so the model underfits the data or that the data-generating process is nonlinear. Given the regularizing nature of the prior on , a minor underfit would be considered ideal if the goal is to obtain good out-of-sample predictions. If the model badly underfits or overfits the data, then you may want to reconsider the model.
Example
We will utilize an example from the HSAUR3 package by Brian S. Everitt and Torsten Hothorn, which is used in their 2014 book A Handbook of Statistical Analyses Using R (3rd Edition) (Chapman & Hall / CRC). This book is frequentist in nature and we will show how to obtain the corresponding Bayesian results.
The model in section 5.3.1 analyzes an experiment where clouds were
seeded with different amounts of silver iodide to see if there was
increased rainfall. This effect could vary according to covariates,
which (except for time) are interacted with the treatment
variable. Most people would probably be skeptical that cloud hacking
could explain very much of the variation in rainfall and thus the prior
mode of the
would probably be fairly small.
The frequentist estimator of this model can be replicated by executing
data("clouds", package = "HSAUR3")
ols <- lm(rainfall ~ seeding * (sne + cloudcover + prewetness + echomotion) +
time, data = clouds)
round(coef(ols), 3)Note that we have not looked at the estimated
or
for the ordinary least squares model. We can estimate a Bayesian version
of this model by prepending stan_ to the lm
call, specifying a prior mode for
,
and optionally specifying how many cores the computer may utilize:
library(rstanarm)
post <-
stan_lm(
rainfall ~ seeding * (sne + cloudcover + prewetness + echomotion) + time,
data = clouds,
prior = R2(location = 0.2),
seed = 12345
)
postIn this case, the “Bayesian point estimates”, which are represented
by the posterior medians, appear quite different from the ordinary least
squares estimates. However, the log-fit_ratio
(i.e. )
is quite small, indicating that the model only slightly overfits the
data when the prior derived above is utilized. Thus, it would be safe to
conclude that the ordinary least squares estimator considerably overfits
the data since there are only
observations to estimate
parameters with and no prior information on the parameters.
Also, it is not obvious what the estimated average treatment effect
is since the treatment variable, seeding, is interacted
with four other correlated predictors. However, it is easy to estimate
or visualize the average treatment effect (ATE) using
rstanarm’s posterior_predict function.
clouds_cf <- clouds
clouds_cf$seeding[] <- "yes"
y1_rep <- posterior_predict(post, newdata = clouds_cf)
clouds_cf$seeding[] <- "no"
y0_rep <- posterior_predict(post, newdata = clouds_cf)
qplot(x = c(y1_rep - y0_rep), geom = "histogram", xlab = "Estimated ATE")As can be seen, the treatment effect is not estimated precisely and is as almost as likely to be negative as it is to be positive.
Alternative Approach
The prior derived above works well in many situations and is quite
simple to use since it only requires the user to specify the
prior location of the
.
Nevertheless, the implications of the prior are somewhat difficult to
conceptualize. Thus, it is perhaps worthwhile to compare to
another estimator of a linear model that simply puts independent Cauchy
priors on the regression coefficients. This simpler approach can be
executed by calling the stan_glm function with
family = gaussian() and specifying the priors:
simple <-
stan_glm(
rainfall ~ seeding * (sne + cloudcover + prewetness + echomotion) + time,
data = clouds,
family = gaussian(),
prior = cauchy(),
prior_intercept = cauchy(),
seed = 12345
)We can compare the two approaches using an approximation to
Leave-One-Out (LOO) cross-validation, which is implemented by the
loo function in the loo package.
(loo_post <- loo(post))
loo_compare(loo_post, loo(simple))The results indicate that the first approach is expected to produce better out-of-sample predictions but the Warning messages are at least as important. Many of the estimated shape parameters for the Generalized Pareto distribution are above in the model with Cauchy priors, which indicates that these estimates are only going to converge slowly to the true out-of-sample deviance measures. Thus, with only observations, they should not be considered reliable. The more complicated prior derived above is stronger — as evidenced by the fact that the effective number of parameters is about half of that in the simpler approach and for the maximum likelihood estimator — and only has a few of the Pareto shape estimates in the “danger zone”. We might want to reexamine these observations
plot(loo_post, label_points = TRUE)because the posterior is sensitive to them but, overall, the results seem tolerable.
In general, we would expect the joint prior derived here to work better when there are many predictors relative to the number of observations. Placing independent, heavy-tailed priors on the coefficients neither reflects the beliefs of the researcher nor conveys enough information to stabilize all the computations.
Conclusion
This vignette has discussed the prior distribution utilized in the
stan_lm function, which has the same likelihood and a
similar syntax as the lm function in R but adds the ability
to expression prior beliefs about the location of the
,
which is the familiar proportion of variance in the outcome variable
that is attributable to the predictors under a linear model. Since the
is a well-understood bounded scalar, it is easy to specify prior
information about it, whereas other Bayesian approaches require the
researcher to specify a joint prior distribution for the regression
coefficients (and the intercept and error variance).
However, most researchers have little inclination to specify all
these prior distributions thoughtfully and take a short-cut by
specifying one prior distribution that is taken to apply to all the
regression coefficients as if they were independent of each other (and
the intercept and error variance). This short-cut is available in the
stan_glm function and is described in more detail in other
rstanarm vignettes for Generalized Linear Models
(GLMs), which can be found by navigating up one level.
We are optimistic that this prior on the
will greatly help in accomplishing our goal for
rstanarm of making Bayesian estimation of regression
models routine. The same approach is used to specify a prior in ANOVA
models (see stan_aov) and proportional-odds models for
ordinal outcomes (see stan_polr).
Finally, the stan_biglm function can be used when the
design matrix is too large for the qr function to process.
The stan_biglm function inputs the output of the
biglm function in the biglm package, which
utilizes an incremental QR decomposition that does not require the
entire dataset to be loaded into memory simultaneously. However, the
biglm function needs to be called in a particular way in
order to work with stan_biglm. In particular, The means of
the columns of the design matrix, the sample mean of the outcome, and
the sample standard deviation of the outcome all need to be passed to
the stan_biglm function, as well as a flag indicating
whether the model really does include an intercept. Also, the number of
columns of the design matrix currently cannot exceed the number of rows.
Although stan_biglm should run fairly quickly and without
much memory, the resulting object is a fairly plain stanfit
object rather than an enhanced stanreg object like that
produced by stan_lm. Many of the enhanced capabilities of a
stanreg object depend on being able to access the full
design matrix, so doing posterior predictions, posterior checks, etc.
with the output of stan_biglm would require some custom R
code.