Some helps for running and evaluating Bayesian regression models

September 21, 2012
By

(This article was first published on Houses of Stones » R, and kindly contributed to R-bloggers)

Around two years ago, I suddenly realized my statistical training had a great big Bayes-shaped hole in it. My formal education in statistics was pretty narrow – I got my degree in anthropology, a discipline not exactly known for its rigorously systematic analytic methods. I learned the basics of linear models and principal components analysis and was mercifully spared too much emphasis on ANOVAs and chi-squares and other “tests.” I developed a large portion of my statistical skills while working for the Department of the Army…not because the Army is really into rigorous analysis (see here and here and here), but because a co-worker introduced me to R. (I’m convinced the best way to learn statistics is to get a minimalist introduction – just enough to avoid being intimidated by the jargon – and then devote a few months to doing two or three projects in R.) During all of this, I kind of knew there was a thing called Bayesian statistics out there, but I’d never really looked into it and didn’t have strong opinions about it.

That all changed. Through a lot of experiences I won’t detail here, I came to the view that p-values were pretty silly things to focus on, which view eventually turned into near-total disillusionment with the entire concept of statistical significance as it used in the context of null-hypothesis testing (see here for more). I can appreciate that that stuff has its uses when certain assumptions are met, but I don’t happen to be interested in any situations where those assumptions are very realistic.

I then happened upon Sharon McGrayne’s fun little read, The Theory that Would Not Die. I read it because I had the time and because it seemed like an interesting subject, but the book gave me enough information about Bayesian approaches to nudge me out of being complacent in my ignorance. I started looking for some resources on Bayesian statistics that were geared towards practical application rather than the underlying mathematics (I really enjoy the application part, and in most cases I’m content to trust other people that the math part has been taken care of pretty well). I came across John Kruschke’s book, Doing Bayesian Data Analysis. By the end of the first chapter, I was very interested. By the end of chapter 11, I was really mad that no one had ever told me about this stuff before. By the end the entire book, there was no turning back.

R has a lot of resources for doing all kinds of Bayesian stuff, but it seems that, traditionally, the main tool for doing Bayesian modeling has been BUGS, which can be accessed through R using various packages such as R2WinBugs, and more recently JAGS, which can be called through packages such as R2Jags. But two things kept me off the BUGS/JAGS route.

First, they have their own syntax – the way you specify a regression model in nearly every R package is not the way you specify a model in BUGS/JAGS. That’s not the fault of those programs – they weren’t designed to be R add-ons. It’s just that my list of syntaxes to learn is pretty long, and BUGS/JAGS syntax is not very high on that list. In the amount of time it would take me to learn BUGS syntax well I could learn a little Java or Python syntax and still get (in my opinion) a much greater return on my investment. But besides the syntax issue, BUGS and JAGS are known for being pretty slow. That’s not a bad thing in and of itself – some things just take time to do – but if a faster option exists that doesn’t require me to learn new syntax, that leaves me little reason to choose the slower tools.

So I was happy when I came across the MCMCglmm package. I was already familiar with generalized linear mixed-effects models (GLMMs), the syntax was very similar to what is used in other standard R functions such as glm() and the lme4 package’s glmer(), and according to comparisons run by MCMCglmm author Jarrod Hadfield, “on a 2.5Ghz dual core MacBook Pro with 2GB RAM, MCMCglmm took 7.6 minutes and WinBUGS took 4.8 hours to fit the [same] model.” Most of my projects have short deadlines, so 8 minutes looked a whole lot better than 5 hours.

I’ve used MCMCglmm for several projects, most recently a few analyses to inform decisions about market segmentation, and while I’m generally happy with it there are a few little things and one really, really big thing that I would like to be different. The little things have to do with defaults – I want to have options for default priors, because they’re useful and save time when exploring, and I don’t like the default of not saving the estimates for random effects when modeling and marginalizing across all random effects when predicting.

But like I said, those are really small things. It’s not hard to change the settings from the defaults. What I really, really don’t like is that the predict function for MCMCglmm can’t handle new data. I can run a model and then use the predict() function to get calculations of what the model says each of the original data points ought to be, but I can’t feed it a new set of data containing the same predictor variables as were used in the original model and have the model estimate what the response variable ought to be for those data points. I’m not blaming the package’s author for this shortcoming. It’s R: I’m already getting tons more than I pay for. I’m sure he’ll get around to doing it eventually. But for right, now, I need to be able to predict new data.

I mainly need that capability is for cross validation. There are many ways of evaluating a model. Most of the ways I see tend to focus on individual parameters instead of the model as a whole. It’s already very easy to get estimates of how much confidence a parameter estimate warrants and things like that. And it’s easy to see how well the model fits the data used to construct the model – but that’s the problem: while it’s better than nothing, it’s not a very rigorous measure of a model’s performance to see how well it post-dicts the data that were used to train the model in the first place. That’s where cross-validation comes in handy – randomly exclude a small portion of your data, build the model based on the larger portion, and then see how well the model predicts the omitted smaller portion. It’s a pretty straightforward way to see how much the model diverges from reality.

So I finally made some time to write some functions, most of them just tweaking the MCMCglmm functions, to allow me to cross-validate my models. You can find and/or edit the source code here and can load all the functions in R by entering:

```<br />
source(&quot;https://raw.github.com/schaunwheeler/tmt/master/R/mcmcglmm.R&quot;)<br />
```

For right now, I’m calling the set of functions mcmcglmm (all lowercase letters) because they’re really just a modification of the MCMCglmm functions, which are doing all the heavy lifting.

To start, I wrote a quick function called SplitData() that takes a data frame and splits it into a large subset and a small subset, so the large part can be used to fit the model and the small part can be used for cross validation.

```<br />
SplitData &lt;- function(data, percent = .8, ignore = NULL){</p>
<p>  facs &lt;- sapply(data,is.factor)<br />
data[,facs] &lt;- lapply(data[,facs],as.character)<br />
chars &lt;- sapply(data,is.character)<br />
ignore &lt;- colnames(data) %in% ignore<br />
look &lt;- chars &amp; !ignore</p>
<p>  num &lt;- round(nrow(data) * percent, 0)<br />
rows &lt;- sample(1:nrow(data), num)<br />
rowind &lt;- 1:nrow(data) %in% rows</p>
<p>  big &lt;- data[rowind,]<br />
small &lt;- data[!rowind,]</p>
<p>  bigind &lt;- 1:nrow(big)<br />
smallind &lt;- 1:nrow(small)</p>
<p>  bigvals &lt;- rep(NA,ncol(big))<br />
smallvals &lt;- rep(NA,ncol(small))<br />
bigvals[look] &lt;- lapply(big[,look],function(x)sort(unique(x)))<br />
smallvals[look] &lt;- lapply(small[,look],function(x)sort(unique(x)))</p>
<p>  matches &lt;- lapply(1:length(smallvals),<br />
function(x)smallvals[[x]] %in% bigvals[[x]])<br />
misses &lt;- which(sapply(matches, function(x)1-mean(x)) &gt; 0)<br />
missvals &lt;- lapply(1:length(smallvals),<br />
function(x)smallvals[[x]][!(smallvals[[x]] %in% bigvals[[x]])])</p>
<p>  if(length(misses) &gt; 0){<br />
for(i in misses){<br />
for(j in 1:length(missvals[[i]])){<br />
pulls &lt;- smallind[small[,i] == missvals[[i]][j]]<br />
take &lt;- ifelse(length(pulls) == 1, pulls,<br />
try(sample(pulls, 1), silent = T))<br />
if(is.numeric(take)){<br />
big &lt;- rbind(big,small[take,])<br />
small &lt;- small[-take,]<br />
}<br />
}<br />
}<br />
}</p>
<p>  list(&quot;large&quot; = big,<br />
&quot;small&quot; = small)<br />
}<br />
```

The default is to keep 80% of the original data for the model fitting. The function splits the data into the specified proportions, and then checks to see if the smaller subset has variable options not included in the bigger portion. It could be a problem if you trained a model with country-level predictors for the U.S., Russia, China, and Australia, and then tried to cross validate the prediction on data that included Argentina as a country option. SplitData() makes sure that if any subset is going to include variable options that the other one doesn’t, it’s going to be the bigger subset. So:

```<br />
df &lt;- as.data.frame(matrix(rnorm(200),ncol=2))<br />
df\$F1 &lt;- sample(LETTERS[1:3],100, replace = T)<br />
df\$F2 &lt;- sample(LETTERS[4:5],100, replace = T)<br />
df &lt;- rbind(df,c(0,0,&quot;X&quot;,&quot;Y&quot;))<br />
df\$V1 &lt;- as.numeric(df\$V1)<br />
df\$V2 &lt;- as.numeric(df\$V2)</p>
<p>table(as.data.frame(t(sapply(1:1000,function(&#8230;)sapply(SplitData(df),nrow)))))</p>
<p>     small<br />
large    19  20<br />
81   0 824<br />
82 176   0<br />
```

So I created a data set with 101 rows and four columns. The first two rows were numeric and the last two were categorical – the first categorical variable included a random sample of A’s, B’s, and C’s and then had one X in the last row. The second categorical variable included a random sample of D’s and E’s and then had one Y in the last row. I ran SplitData() 1000 times on that data set and, as you can see, approximately 80% of the time, the X and Y row ended up in the bigger subset – with 81 variables in that subset and 20 variables in the smaller subset. About 20% of the time, the X and Y row ended up in the smaller subset, and was therefore moved to the larger subset.

All the rest of the functions either wrap, modify, or take input from a call to MCMCglmm().

The mcmcglmm() function takes all the same inputs as the function it wraps, but it starts by evaluating all discrete variables in the data set and recording what the range of possible values was for each variable. It inserts that list, called “datalevels”, into the model output at the end of the function. Most of the wrapper is devoted to creating default priors. The function allows for two variants of two default priors on the covariance matrices. The two defaults are “InvW” for an inverse-Wishart prior, which sets the degrees of freedom parameter equal to the dimension of each covariance matrix, and “InvG” for an inverse-Gamma prior, which sets the degrees of freedom parameter to 0.002 more than one less than the dimensions of the covariance matrix. “-pe” can be added to the call for either of these priors to use parameter expansion (see section 5.2 of this). For more specific prior specification, you can just feed a list to the “prior” argument, as explained in the pretty extensive (for R) MCMCglmm documentation.

I also wrote a little function called QuickSummary() that brings together most of my preferred methods for assessing individual parameters. Given the model output, the function calculates the posterior mean, the highest posterior density intervals for a given probability (set through the “prob” option), the “type S” error (probability that the estimate actually is of the opposite sign of the posterior mean), and the “type M” error (probability that the estimate is the same sign but substantially smaller than the posterior mean – this defaults to measuring the probability that the estimate is less than one half the size of the mean). The function also allows for rounding of the output for convenience. It defaults to four decimal places.

But the real work was with the predict.MCMCglmm function. I couldn’t just make a wrapper for this function, partially because I had to insert the new data into specific parts of the function, and partly because as the predict.MCMGlmm function is currently written, this happens:

```<br />
predict(model,newdata=df2)<br />
Error in predict.MCMCglmm(model, newdata = df2) :<br />
sorry newdata not implemented yet<br />
In predict.MCMCglmm(model, newdata = df2) :<br />
predict.MCMCglmm is still developmental &#8211; be careful<br />
```

So I had to go in and take out the line that stops the function whenever new data is inserted. I also removed the warning statement about the function being development (I’m tired of seeing it) and changed the marginalization defaults. After that, there was the matter of creating design matrices for the new data that matched the design matrices used in the original model. When just fitting the original data, that’s easy:

```<br />
object\$Sol &lt;- object\$Sol[, c(1:object\$Fixed\$nfl, object\$Fixed\$nfl +<br />
keep), drop = FALSE]<br />
W &lt;- cBind(object\$X, object\$Z)<br />
W &lt;- W[, c(1:object\$Fixed\$nfl, object\$Fixed\$nfl + keep),<br />
drop = FALSE]<br />
```

“Object” is the placeholder for the model output in general and the “Sol” is a list of the MCMC estimates for each predictor, while “X” is the design matrix for the fixed effects and “Z” is the design matrix for the random effects.  So in normal data fitting, the predict function just puts the two design matrices together and then cuts the simulation output and combined design matrix to only keep those variables that were not marginalized. So the MCMCglmm() function did all the hard work already. That’s not the case with new data:

```<br />
if(!is.null(newdata)){<br />
chars &lt;- sapply(newdata,is.character)<br />
newdata[,chars] &lt;- lapply(newdata[,chars],as.factor)</p>
<p>  vars.o &lt;- paste(as.character(object\$Fixed[[1]]),<br />
as.character(object\$Random[[1]]), collapse = &quot; &quot;)<br />
vars.o &lt;- gsub(&quot;~|(us|idh|cor)\(|[+]|\):|\b1\b&quot;,&quot; &quot;, vars.o)<br />
vars.o &lt;- unlist(strsplit(vars.o, split = &quot;\s+&quot;))<br />
vars.o &lt;- unique(vars.o[vars.o != &quot;&quot;])<br />
if(any(vars.o %in% colnames(newdata)) == F){<br />
stop(&quot;&#8217;newdata&#8217; is missing variables needed for the model&quot;)<br />
}</p>
<p>  facs &lt;- sapply(newdata,is.factor)<br />
facs.o &lt;- vars.o[facs]</p>
<p>  for(i in 1:length(facs.o)){<br />
newdata[,facs.o[i]] &lt;- factor(newdata[,facs.o[i]],<br />
levels=sort(unique(c(levels(newdata[,facs.o[i]]),<br />
object\$datalevels[[facs.o[i]]]))),<br />
labels = object\$datalevels[[facs.o[i]]])<br />
}</p>
<p>  fixef &lt;- sparse.model.matrix(object\$Fixed[[1]], newdata)<br />
rterms &lt;- split.direct.sum(as.character(object\$Random[[1]])[2])</p>
<p>  ranef &lt;- lapply(rterms,function(x, df = newdata){<br />
covms &lt;- grepl(&quot;\w{2,3}\([[:print:]]+\):&quot;,x)</p>
<p>    ints &lt;- grepl(&quot;\w{2,3}\((1 [+])?([[:print:]]+)\):([[:print:]]+)&quot;, x)</p>
<p>    if(covms == T &amp; ints == T){<br />
full &lt;- sparse.model.matrix(as.formula(<br />
gsub(&quot;\w{2,3}\(1 [+] ([[:print:]]+)\):([[:print:]]+)&quot;,<br />
&quot;~ 0 + \1 : \2&quot;, x)),df)</p>
<p>      binary &lt;- full!=0<br />
matching &lt;- vector(&quot;logical&quot;,length(colnames(df)))</p>
<p>      for(j in 1:length(colnames(df))){<br />
matching[j] &lt;- grepl(paste(&quot;:&quot;,colnames(df)[j],sep=&quot;&quot;), x)<br />
}</p>
<p>    matchvar &lt;- colnames(df)[matching]<br />
firstvar &lt;- gsub(&quot;\w{2,3}\(1 [+] ([[:print:]]+)\):([[:print:]]+)&quot;,<br />
&quot;\1&quot;, x)</p>
<p>    colnames(binary) &lt;- paste(matchvar, &quot;(Intercept)&quot;, matchvar,<br />
sort(object\$datalevels[[matchvar]]),sep=&quot;.&quot;)</p>
<p>    colnames(full) &lt;- paste(matchvar, firstvar, matchvar,<br />
sort(object\$datalevels[[matchvar]]),sep=&quot;.&quot;)</p>
<p>    out &lt;- cBind(binary,full)<br />
}</p>
<p>    if(covms == T &amp; ints == F){<br />
full &lt;- sparse.model.matrix(as.formula(<br />
gsub(&quot;\w{2,3}\(([[:print:]]+)\):([[:print:]]+)&quot;,<br />
&quot;~ 0 + \1 : \2&quot;, x)),df)</p>
<p>      matching &lt;- vector(&quot;logical&quot;,length(colnames(df)))</p>
<p>      for(j in 1:length(colnames(df))){<br />
matching[j] &lt;- grepl(paste(&quot;:&quot;,colnames(df)[j],sep=&quot;&quot;), x)<br />
}</p>
<p>      matchvar &lt;- colnames(df)[matching]<br />
firstvar &lt;- gsub(&quot;\w{2,3}\(1 [+] ([[:print:]]+)\):([[:print:]]+)&quot;,<br />
&quot;\1&quot;, rterms[i])</p>
<p>      colnames(full) &lt;- paste(matchvar, firstvar, matchvar,<br />
sort(unique(as.character(object\$datalevels[[matchvar]]))),<br />
sep=&quot;.&quot;)<br />
out &lt;- full<br />
}</p>
<p>    if(covms == F &amp; ints == F){<br />
matchvar &lt;- colnames(df)[colnames(df) %in% x]<br />
full &lt;- sparse.model.matrix(as.formula(paste(&quot;~ 0 +&quot;, x, sep= &quot;&quot;)),df)</p>
<p>      colnames(full) &lt;- paste(x,sort(unique(as.character(object\$datalevels[[matchvar]]))),<br />
sep=&quot;.&quot;)<br />
out &lt;- full<br />
}<br />
out<br />
})</p>
<p>  ranef &lt;- do.call(&quot;cBind&quot;,ranef)</p>
<p>  Wn &lt;- cBind(fixef,ranef)</p>
<p>  object\$X &lt;- fixef[,match(colnames(object\$X),colnames(fixef))]<br />
object\$Z &lt;- ranef[,match(colnames(object\$Z),colnames(ranef))]<br />
object\$error.term &lt;- object\$error.term[1:nrow(Wn)]</p>
<p>  W &lt;- Wn[,match(colnames(W),colnames(Wn))]<br />
W &lt;- W[, c(1:object\$Fixed\$nfl, object\$Fixed\$nfl + keep),<br />
drop = FALSE]<br />
}<br />
```

MCMCglmm specifies predictors in several different ways. If wrapped in a us(), idh(), or cor() function (among others), a predictor in the random-effects formula represents a covariance matrix, and therefore each level of that variable gets a column in the design matrix (if the variable is discrete). But if the variable in the function is discrete, that represents a random-slope specification and gets only one column. But if the function contains a “1 + {variable}”, that indicates a random intercept and random slope specification that gets two columns. So most of the stuff I added pulls apart the model formulas and matches up the pieces with types of specifications and then constructs the appropriate number of columns by referencing the “datalevels” list that mcmcglmm() added to the MCMCglmm() output. All of this leads up to the new data design matrices replacing the old data design matrices, all of which is wrapped up in an object “W”, is the name of the object used by the original predict.MCMCglmm function to do the rest of the prediction.

The only other part I changed was, I think, an error in the original code. For example, this happens with the original function:

```<br />
df &lt;- as.data.frame(matrix(rnorm(20),ncol=2))<br />
df\$F1 &lt;- sample(LETTERS[1:3],10, replace = T)<br />
df\$F2 &lt;- sample(LETTERS[4:5],10, replace = T)</p>
<p>model &lt;- mcmcglmm(V1~V2+F2,random=~us(1+V2):F1+F2,pr=T,data=df)</p>
<p>predict(model,interval=&quot;prediction&quot;,marginal=~F2)<br />
Error in vpred[, cnt][which(object\$error.term == i &amp; object\$error.term ==  :<br />
subscript out of bounds<br />
```

The original function only breaks when you try to do a posterior predictive check – simulating draws from the posterior distribution instead of just calculating estimates based on parameter means – at the same time that you try to marginalize some but not all of the random variables. Even when not marginalizing, I noticed in practice that the credibility intervals for the posterior predictions were much larger than I expected. It looks like a couple lines of code inadvertently cut the the random-effects design matrix incorrectly, duplicating some columns and leaving others out. That not only messes us the predictions but also, when marginalizing some but not all random variables, creates matrices that don’t make sense given subsequent subscript calls. So I fixed that. So here’s how the new function compares. Assuming the same 20-row data frame and mcmcglmm() call that I showed in the last code snippet, and assuming no marginalization, here is what the original predict.MCMCglmm does:

```<br />
predict(model,marginal=NULL)<br />
[,1]<br />
1  -0.93093304<br />
2  -0.14137582<br />
3   0.78776897<br />
4   0.46296440<br />
5   0.75096633<br />
6   0.10049595<br />
7   0.20339204<br />
8   0.17401375<br />
9  -0.06092788<br />
10  0.36310427Warning message:<br />
In predict.MCMCglmm(model) :<br />
predict.MCMCglmm is still developmental &#8211; be careful&lt;/pre&gt;<br />
```

And here’s PredictNew()

```<br />
PredictNew(model)<br />
[,1]<br />
1  -0.93093304<br />
2  -0.14137582<br />
3   0.78776897<br />
4   0.46296440<br />
5   0.75096633<br />
6   0.10049595<br />
7   0.20339204<br />
8   0.17401375<br />
9  -0.06092788<br />
10  0.36310427<br />
```

And here’s PredictNew() passing the original data frame, but in reverse order, as a new data frame:

```<br />
PredictNew(model,newdata=df[10:1,])<br />
[,1]<br />
1   0.36310427<br />
2  -0.06092788<br />
3   0.17401375<br />
4   0.20339204<br />
5   0.10049595<br />
6   0.75096633<br />
7   0.46296440<br />
8   0.78776897<br />
9  -0.14137582<br />
10 -0.93093304<br />
```

So the output of NewPredict() matches the output of predict.MCMCglmm, and passing new data gives predictions that match what they would have been if they had been the original data. Calculating confidence intervals also gives consistent results across both functions and with new data. Calculating estimates and intervals for posterior predictive checks aren’t the same, but there’s no way they could be, since they’re derived computationally instead of analytically.

So I’m pretty happy now with the tools I currently have for Bayesian modeling. I do wish I could use a scaled inverse-Wishart or separation strategy prior (see here) – if there’s a way to do that in MCMCglmm I haven’t figured it out – and the Stan program/package created by Andrew Gelman and others looks cool enough that it might actually entice me to learn BUGS-esque syntax, but for the time being I feel pretty ok about my regression tools.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...