The BAS
package provides easy to use functions to implement Bayesian Model Averaging in linear models and generalized linear models. Prior distributions on coefficients are based on Zellner’s g-prior or mixtures of g-priors, such as the Zellner-Siow Cauchy prior or mixtures of g-priors from Liang et al (2008) for linear models, as well as other options including AIC, BIC, RIC and Empirical Bayes methods. Extensions to Generalized Linear Models are based on the mixtures of g-priors in GLMs of Li and Clyde (2015) using an integrated Laplace approximation.
BAS
uses an adaptive sampling algorithm to sample without replacement from the space of models or MCMC sampling which is recommended for sampling problems with a large number of predictors. See Clyde, Littman & Ghosh for more details for the sampling algorithms.
The stable version can be installed easily in the R
console like any other package:
install.packages('BAS')
On the other hand, I welcome everyone to use the most recent version of the package with quick-fixes, new features and probably new bugs. To get the latest development version from GitHub, use the devtools
package from CRAN and enter in R
:
# devtools::install_github('merliseclyde/BAS')
As the package does depend on BLAS and LAPACK, installing from GitHub will require that you have FORTRAN and C compilers on your system.
We will use the UScrime data to illustrate some of the commands and functionality.
library(MASS)
data(UScrime)
Following other analyses, we will go ahead and log transform all of the variables except column 2, which is the indicator variable of the state being a southern state.
UScrime[,-2] = log(UScrime[,-2])
To get started, we will use BAS
with the Zellner-Siow Cauchy prior on the coefficients.
library(BAS)
crime.ZS = bas.lm(y ~ .,
data=UScrime,
prior="ZS-null",
modelprior=uniform(), initprobs="eplogp")
BAS
uses a model formula similar to lm
to specify the full model with all of the potential predictors. Here we are using the shorthand .
to indicate that all remaining variables in the data frame will be included. BAS
require a data frame as the input for the data
argument. Different prior distributions on the regression coefficients may be specified using the prior
argument, and include
where the default is the Zellner-Siow prior, ZS-null, where all Bayes factors are compared to the null model.
By default, BAS
will try to enumerate all models, in this case \(2^{15}\) using the default method="BAS"
. The prior distribution over the models is a uniform()
distribution which assigns equal probabilities to all models. The last optional argument initprobs = eplogp
provides a way to initialize the sampling algorithm and order the variables in the tree structure that represents the model space in BAS. The eplogp
option uses the Bayes factor calibration of p-values \(-e p \log(p)\) to provide an approximation to the marginal inclusion probability that the coefficient of each predictor is zero, using the p-values from the full model. Other options for initprobs
include
The option “marg-eplogp” uses p-values from the p simple linear regressions (useful for large p or highly correlated variables). The numeric provides a way to force variables to always be included if the initialprob is 1.
Since we are enumerating under all possible models these options are not important.
Some graphical summaries of the output may be obtained by the plot
function
plot(crime.ZS, ask=F)
which produces a panel of four plots. The first is a plot of residuals and fitted values under Bayesian Model Averaging. Ideally, of our model assumptions hold, we will not see outliers or non-constant variance. The second plot shows the cumulative probability of the models in the order that they are sampled. This plot indicates that the cumulative probability is leveling off as each additional model adds only a small increment to the cumulative probability, which earlier, there are larger jumps corresponding to sampling high probability models. The third plot shows the dimension of each model (the number of regression coefficients including the intercept) versus the log of the marginal likelihood of the model. The last plot shows the marginal posterior inclusion probabilities (pip) for each of the covariates, with marginal pips greater than 0.5 shown in red. The variables with pip > 0.5 correspond to what is known as the median probability model. Variables with high inclusion probabilities are generally important for explaining the data or prediction, but marginal inclusion probabilities may be small if there predictors are correlated, similar to how p-values may be large in the presence of mullticollinearity.
Individual plots may be obtained using the which
option.
plot(crime.ZS, which = 4, ask=FALSE, caption="", sub.caption="")
BAS
has print
and summary
methods defined for objects of class bas
. Typing the objects name
crime.ZS
##
## Call:
## bas.lm(formula = y ~ ., data = UScrime, prior = "ZS-null", modelprior = uniform(),
## initprobs = "eplogp")
##
##
## Marginal Posterior Inclusion Probabilities:
## Intercept M So Ed Po1 Po2
## 1.0000 0.8536 0.2737 0.9747 0.6652 0.4490
## LF M.F Pop NW U1 U2
## 0.2022 0.2050 0.3696 0.6944 0.2526 0.6149
## GDP Ineq Prob Time
## 0.3601 0.9965 0.8992 0.3718
returns a summary of the marginal inclusion probabilities, while the summary
function provides
options(width = 80)
summary(crime.ZS)
## P(B != 0 | Y) model 1 model 2 model 3 model 4 model 5
## Intercept 1.0000000 1.00000 1.0000000 1.0000000 1.000000 1.0000000
## M 0.8535720 1.00000 1.0000000 1.0000000 1.000000 1.0000000
## So 0.2737083 0.00000 0.0000000 0.0000000 0.000000 0.0000000
## Ed 0.9746605 1.00000 1.0000000 1.0000000 1.000000 1.0000000
## Po1 0.6651553 1.00000 1.0000000 0.0000000 1.000000 1.0000000
## Po2 0.4490097 0.00000 0.0000000 1.0000000 0.000000 0.0000000
## LF 0.2022374 0.00000 0.0000000 0.0000000 0.000000 0.0000000
## M.F 0.2049659 0.00000 0.0000000 0.0000000 0.000000 0.0000000
## Pop 0.3696150 0.00000 0.0000000 0.0000000 1.000000 0.0000000
## NW 0.6944069 1.00000 1.0000000 1.0000000 1.000000 0.0000000
## U1 0.2525834 0.00000 0.0000000 0.0000000 0.000000 0.0000000
## U2 0.6149388 1.00000 1.0000000 1.0000000 1.000000 1.0000000
## GDP 0.3601179 0.00000 0.0000000 0.0000000 0.000000 0.0000000
## Ineq 0.9965359 1.00000 1.0000000 1.0000000 1.000000 1.0000000
## Prob 0.8991841 1.00000 1.0000000 1.0000000 1.000000 1.0000000
## Time 0.3717976 1.00000 0.0000000 0.0000000 0.000000 0.0000000
## BF NA 1.00000 0.9416178 0.6369712 0.594453 0.5301269
## PostProbs NA 0.01820 0.0172000 0.0116000 0.010800 0.0097000
## R2 NA 0.84200 0.8265000 0.8229000 0.837500 0.8046000
## dim NA 9.00000 8.0000000 8.0000000 9.000000 7.0000000
## logmarg NA 23.65111 23.5909572 23.2000822 23.130999 23.0164741
This lists the top 5 models (in terms of posterior probability) with the zero-one indicators for variable inclusion. The other columns in the summary are the Bayes factor of each model to the highest probability model (hence its Bayes factor is 1), the posterior probabilities of the models, the ordinary \(R^2\) of the models, the dimension of the models (number of coefficients including the intercept) and the log marginal likelihood under the selected prior distribution.
To see beyond the first five models, we can represent the collection of the models via an image
plot. By default this shows the top 20 models.
image(crime.ZS, rotate=F)
This image has rows that correspond to each of the variables and intercept, with labels for the variables on the y-axis. The x-axis corresponds to the possible models. These are sorted by their posterior probability from best at the left to worst at the right with the rank on the top x-axis.
Each column represents one of the 16 models. The variables that are excluded in a model are shown in black for each column, while the variables that are included are colored, with the color related to the log posterior probability. The color of each column is proportional to the log of the posterior probabilities (the lower x-axis) of that model. Models that are the same color have similar log posterior probabilities which allows us to view models that are clustered together that have marginal likelihoods where the differences are not “worth a bare mention”.
This plot indicates that the police expenditure in the two years do not enter the model together, and is an indication of the high correlation between the two variables.
To examine the marginal distributions of the two coefficients for the police expenditures, we can extract the coefficients estimates and standard deviations under BMA.
coef.ZS = coef(crime.ZS)
an optional argument, n.models
to coef
will use only the top n.models
for BMA and may be more computationally efficient for large problems.
Plots the posterior distributions averaging over all of the models are obtained using the plot
method.
plot(coef.ZS, subset=c(5:6), ask=F)
The vertical bar represents the posterior probability that the coefficient is 0 while the bell shaped curve represents the density of plausible values from all the models where the coefficient is non-zero. This is scaled so that the height of the density for non-zero values is the probability that the coefficient is non-zero.
Omitting the subset
argument provides all of the marginal distributions
plot(coef.ZS, ask=FALSE)
To obtain credible intervals for coefficients, BAS
includes a confint
method to create Highest Posterior Density intervals from the summaries from coef
.
confint(coef.ZS)
## 2.5% 97.5% beta
## Intercept 6.666881492 6.781856337 6.72493620
## M 0.000000000 2.168513586 1.14359433
## So -0.058941484 0.307627686 0.03547522
## Ed 0.663193215 3.189942841 1.85848834
## Po1 0.000000000 1.445031766 0.60067372
## Po2 -0.153770477 1.424994594 0.31841766
## LF -0.424332808 1.095768249 0.05933737
## M.F -2.200882242 1.950326031 -0.02702786
## Pop -0.121973870 0.009230376 -0.02248283
## NW 0.000000000 0.166754098 0.06668437
## U1 -0.497716492 0.368577771 -0.02456854
## U2 -0.000482762 0.659985906 0.20702927
## GDP -0.033065600 1.209058560 0.20625063
## Ineq 0.646698675 2.093391882 1.39012647
## Prob -0.411865094 0.000000000 -0.21536203
## Time -0.531255680 0.048004857 -0.08433479
## attr(,"Probability")
## [1] 0.95
## attr(,"class")
## [1] "confint.bas"
where the third column is the posterior mean. This uses Monte Carlo sampling to draw from the mixture model over coefficient where models are sampled based on their posterior probabilities.
We can also plot these via
plot(confint(coef.ZS, parm=2:16))
## NULL
using the parm
argument to select which coefficients to plot (the intercept is parm=1
).
For estimation under selection, BAS
supports additional arguments via estimator
. The default is estimator="BMA"
which uses all models or n.models
. Other options include estimation under the highest probability model
plot(confint(coef(crime.ZS, estimator="HPM")))
## NULL
or the median probability model
plot(confint(coef(crime.ZS, estimator="MPM")))
## NULL
where variables that are excluded have distributions that are point masses at zero under selection.
BAS
has methods defined to return fitted values, fitted
, using the observed design matrix and predictions at either the observed data or potentially new values, predict
, as with lm
.
muhat.BMA = fitted(crime.ZS, estimator="BMA")
BMA = predict(crime.ZS, estimator="BMA")
# predict has additional slots for fitted values under BMA, predictions under each model
names(BMA)
## [1] "fit" "Ybma" "Ypred" "postprobs" "se.fit"
## [6] "se.pred" "se.bma.fit" "se.bma.pred" "df" "best"
## [11] "bestmodel" "prediction" "estimator"
Plotting the two sets of fitted values,
par(mar=c(9, 9, 3, 3))
plot(muhat.BMA, BMA$fit,
pch=16,
xlab=expression(hat(mu[i])), ylab=expression(hat(Y[i])))
abline(0,1)
we see that they are in perfect agreement. That is always the case as the posterior mean for the regression mean function at a point \(x\) is the expected posterior predictive value for \(Y\) at \(x\). This is true not only for estimators such as BMA, but the expected values under model selection.
In addition to using BMA, we can use the posterior means under model selection. This corresponds to a decision rule that combines estimation and selection. BAS
currently implements the following options
highest probability model:
HPM = predict(crime.ZS, estimator="HPM")
# show the indices of variables in the best model where 0 is the intercept
HPM$bestmodel
## [1] 0 1 3 4 9 11 13 14 15
A little more interpretable version with names:
(crime.ZS$namesx[HPM$bestmodel +1])[-1]
## [1] "M" "Ed" "Po1" "NW" "U2" "Ineq" "Prob" "Time"
median probability model:
MPM = predict(crime.ZS, estimator="MPM")
(crime.ZS$namesx[attr(MPM$fit, 'model') +1])[-1]
## [1] "M" "Ed" "Po1" "NW" "U2" "Ineq" "Prob"
This is the model where all predictors have an inclusion probability greater than or equal to 0.5. This coincides with the HPM if the predictors are all mutually orthogonal, and in this case is the best predictive model under squared error loss.
Note that we can also extract the best model from the attribute in the fitted values as well.
best predictive model:
In general, the HPM or MPM are not the best predictive models, which from a Bayesian decision theory perspective would be the model that is closest to BMA predictions under squared error loss.
BPM = predict(crime.ZS, estimator="BPM")
(crime.ZS$namesx[attr(BPM$fit, 'model') +1])[-1]
## [1] "M" "So" "Ed" "Po1" "Po2" "M.F" "NW" "U2" "Ineq" "Prob"
Let’s see how they compare:
GGally::ggpairs(data.frame(HPM = as.vector(HPM$fit), #this used predict so we need to extract fitted values
MPM = as.vector(MPM$fit), # this used fitted
BPM = as.vector(BPM$fit), # this used fitted
BMA = as.vector(BMA$fit))) # this used predict
Using the se.fit = TRUE
option with predict
we can also calculate standard deviations for prediction or for the mean and use this as input for the confint
function for the prediction object.
BPM = predict(crime.ZS, estimator="BPM", se.fit=TRUE)
crime.conf.fit = confint(BPM, parm="mean")
crime.conf.pred = confint(BPM, parm="pred")
plot(crime.conf.fit)
## NULL
plot(crime.conf.pred)
## NULL
For prediction at new points, we can supply a new dataframe to the predict function as in lm
.
new.pred = predict(crime.ZS, newdata=UScrime, estimator="MPM")
BAS
has several options for sampling from the model space with or without enumeration. The (current) default method="BAS"
samples models without replacement using estimates of the marginal inclusion probabilities using the algorithm described in http://dx.doi.org/10.1198/jcgs.2010.09049. The initial sampling probabilities provided by initprobs
are updated based on the sampled models, every update
iterations. This can be more efficient in some cases if a large fraction of the model space has been sampled, however, in cases of high correlation and a large number of predictors, this can lead to biased estimates http://dx.doi.org/10.1093/biomet/ass040, in which case MCMC is preferred. The method="MCMC"
is described below and is better for large \(p\).
A deterministic sampling scheme is also available for enumeration;
system.time(
for (i in 1:10) {
crime.ZS <- bas.lm(y ~ .,
data=UScrime,
prior="ZS-null", method="BAS",
modelprior=uniform(), initprobs="eplogp")
}
)
## user system elapsed
## 1.539 0.022 1.565
system.time(
for (i in 1:10) {
crime.ZS <- bas.lm(y ~ .,
data=UScrime,
prior="ZS-null", method="deterministic",
modelprior=uniform(), initprobs="eplogp")
}
)
## user system elapsed
## 1.146 0.024 1.174
which is faster for enumeration than the default method=“BAS”.
Many problems are too large to enumerate all possible models. In such cases we may use the method="BAS"
to sample without replacement or the method="MCMC"
option to sample models using Markov Chain Monte Carlo sampling to sample models based on their posterior probabilities. For spaces where the number of models greatly exceeds the number of models to sample, the MCMC option is recommended as it provides estimates with low bias compared to the sampling without replacement of BAS (Clyde and Ghosh 2011).
crime.ZS = bas.lm(y ~ .,
data=UScrime,
prior="ZS-null",
modelprior=uniform(),
method = "MCMC")
This will run the MCMC sampler until the number of unique sampled models exceeds n.models
which is \(2^p\) (if \(p < 19\)) by default or until MCMC.iterations
has been exceeded, where MCMC.iterations = n.models*2
by default.
With MCMC sampling there are two estimates of the marginal inclusion probabilities: object$probne0
which are obtained by using the re-normalized posterior odds from sampled models to estimate probabilities and the estimates based on Monte Carlo frequencies object$probs.MCMC
. These should be in close agreement if the MCMC sampler has run for enough iterations.
BAS
includes a diagnostic function to compare the two sets of estimates of posterior inclusion probabilities and posterior model probabilities
diagnostics(crime.ZS, type="pip", pch=16)
diagnostics(crime.ZS, type="model", pch=16)
In the left hand plot of pips, each point represents one posterior inclusion probability for the 15 variables estimated under the two methods. The two estimators are in pretty close agreement. The plot of the model probabilities suggests that we should use more MCMC.iterations
if we want more accurate estimates of the posterior model probabilities.
crime.ZS = bas.lm(y ~ .,
data=UScrime,
prior="ZS-null",
modelprior=uniform(),
method = "MCMC", MCMC.iterations = 10^6)
# Don't run diagnostics(crime.ZS, type="model", pch=16)
BAS can also be used for exploring mean shift or variance inflation outliers by adding indicator variables for each case being an outlier (the mean is not given by the regression) or not. This is similar to the MC3.REG function in BMA, although here we are using a g-prior or mixture of g-priors for the coefficients for the outlier means.
Using the Stackloss data, we can add an identify matrix to the original dataframe, where each column is an indicator that the ith variable is an outlier.
data("stackloss")
stackloss$out.ind = diag(nrow(stackloss))
stack.bas = bas.lm(stack.loss ~ ., data=stackloss,
method="MCMC", initprobs="marg-eplogp",
prior="ZS-null",
modelprior=tr.poisson(4,10),
MCMC.iterations=200000
)
The above call introduces using truncated prior distributions on the model space; in this case the distribution of the number of variables to be included has a Poisson distribution, with mean 4 (under no truncation), and the truncation point is at 10, so that all models with more than 10 (one half of cases rounded down) will have probability zero. This avoids exploration of models that are not full rank.
Looking at the summaries
knitr::kable(as.data.frame(summary(stack.bas)))
P(B != 0 | Y) | model 1 | model 2 | model 3 | model 4 | model 5 | |
---|---|---|---|---|---|---|
Intercept | 1.000000 | 1.00000 | 1.0000000 | 1.0000000 | 1.0000000 | 1.0000000 |
Air.Flow | 0.999670 | 1.00000 | 1.0000000 | 1.0000000 | 1.0000000 | 1.0000000 |
Water.Temp | 0.469075 | 1.00000 | 0.0000000 | 1.0000000 | 1.0000000 | 0.0000000 |
Acid.Conc. | 0.092670 | 0.00000 | 0.0000000 | 0.0000000 | 0.0000000 | 0.0000000 |
out.ind1 | 0.601460 | 1.00000 | 1.0000000 | 1.0000000 | 1.0000000 | 1.0000000 |
out.ind2 | 0.167565 | 0.00000 | 0.0000000 | 1.0000000 | 0.0000000 | 0.0000000 |
out.ind3 | 0.630325 | 1.00000 | 1.0000000 | 1.0000000 | 1.0000000 | 1.0000000 |
out.ind4 | 0.953880 | 1.00000 | 1.0000000 | 1.0000000 | 1.0000000 | 1.0000000 |
out.ind5 | 0.069770 | 0.00000 | 0.0000000 | 0.0000000 | 0.0000000 | 0.0000000 |
out.ind6 | 0.076070 | 0.00000 | 0.0000000 | 0.0000000 | 0.0000000 | 0.0000000 |
out.ind7 | 0.061750 | 0.00000 | 0.0000000 | 0.0000000 | 0.0000000 | 0.0000000 |
out.ind8 | 0.064290 | 0.00000 | 0.0000000 | 0.0000000 | 0.0000000 | 0.0000000 |
out.ind9 | 0.067290 | 0.00000 | 0.0000000 | 0.0000000 | 0.0000000 | 0.0000000 |
out.ind10 | 0.065585 | 0.00000 | 0.0000000 | 0.0000000 | 0.0000000 | 0.0000000 |
out.ind11 | 0.062130 | 0.00000 | 0.0000000 | 0.0000000 | 0.0000000 | 0.0000000 |
out.ind12 | 0.083205 | 0.00000 | 0.0000000 | 0.0000000 | 0.0000000 | 0.0000000 |
out.ind13 | 0.339305 | 0.00000 | 1.0000000 | 0.0000000 | 1.0000000 | 0.0000000 |
out.ind14 | 0.186770 | 0.00000 | 0.0000000 | 0.0000000 | 0.0000000 | 0.0000000 |
out.ind15 | 0.074990 | 0.00000 | 0.0000000 | 0.0000000 | 0.0000000 | 0.0000000 |
out.ind16 | 0.058250 | 0.00000 | 0.0000000 | 0.0000000 | 0.0000000 | 0.0000000 |
out.ind17 | 0.066400 | 0.00000 | 0.0000000 | 0.0000000 | 0.0000000 | 0.0000000 |
out.ind18 | 0.061165 | 0.00000 | 0.0000000 | 0.0000000 | 0.0000000 | 0.0000000 |
out.ind19 | 0.090100 | 0.00000 | 0.0000000 | 0.0000000 | 0.0000000 | 0.0000000 |
out.ind20 | 0.130455 | 0.00000 | 0.0000000 | 0.0000000 | 0.0000000 | 0.0000000 |
out.ind21 | 0.985760 | 1.00000 | 1.0000000 | 1.0000000 | 1.0000000 | 1.0000000 |
BF | NA | 1.00000 | 0.3397571 | 0.5555328 | 0.5779604 | 0.2016282 |
PostProbs | NA | 0.06490 | 0.0232000 | 0.0211000 | 0.0200000 | 0.0189000 |
R2 | NA | 0.98920 | 0.9873000 | 0.9922000 | 0.9923000 | 0.9803000 |
dim | NA | 7.00000 | 7.0000000 | 8.0000000 | 8.0000000 | 6.0000000 |
logmarg | NA | 23.82319 | 22.7436630 | 23.2353597 | 23.2749373 | 22.2218573 |
BAS
includes other prior distributions on coefficients and models, as well as bas.glm
for fitting Generalized Linear Models. The syntax for bas.glm and bas.lm are not yet the same, particularly for how some of the priors on coefficients are represented, so please see the documentation for more features and details until this is updated!
For issues or feature requests please submit via the package’s github page merliseclyde/BAS