-
Notifications
You must be signed in to change notification settings - Fork 82
/
variationalBayesRegression.Rmd
245 lines (191 loc) · 7.87 KB
/
variationalBayesRegression.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
---
title: "Variational Bayes Regression"
author: "MC"
output: html_document
---
### Intro
The following provides a function for estimating the parameters of a linear regression via variational inference. See the corresponding .R file for the R code only, and my other scripts for Stan implementation via Hamiltonian Monte Carlo. See Drugowitsch (2014) for an overview of the method outlined in Bishop (2006).
For the primary function I will use the notation used in the Drugowitsch article in most cases. Here w, represents the coefficients, and τ the precision (inverse variance). The likelihood for response y is N(Xw, τ<sup>-1</sup>). Priors for w and tau are normal inverse gamma N(0, (τα)<sup>-1</sup>) Gamma(a0, b0).
#### References
Drugowitsch: <http://arxiv.org/abs/1310.5438> See [here](https://github.com/jdrugo/vb_linear/blob/master/vb_linear_fit.m) and [here](https://github.com/jdrugo/vb_linear/blob/master/vb_linear_fit_ard.m) for his matlab implementation.
Bishop: Pattern Recognition and Machine Learning
First, the main function. Here automatic relevance determination is an argument rather than a separate function.
```{r vbreg, cache=TRUE}
vbreg = function(X, y, a0=10e-2, b0=10e-4, c0=10e-2, d0=10e-4, tol=1e-8, maxiter=1000, ard=F){
# X: model matrix
# y: the response
# a0, b0 prior parameters for tau
# c0, d0 hyperprior parameters for alpha
# tol: tolerance value to end iterations
# maxiter: alternative way to end iterations
# initializations
X = cbind(1, X)
D = ncol(X)
N = nrow(X)
w = rep(0, D)
XX = crossprod(X)
Xy = crossprod(X,y)
a_N = a0 + N/2
if(!ard){
c_N = c0 + D/2
E_alpha = c0/d0
} else {
c_N = c0 + 1/2
E_alpha = rep(c0/d0, D)
}
tolCurrent = 1
iter = 0
LQ = 0
while(iter < maxiter && tolCurrent > tol ){
iter = iter + 1
# wold = w
if(!ard){
b_N = b0 + 1/2*(crossprod(y - X%*%w) + E_alpha * crossprod(w))
VInv = diag(E_alpha, D) + XX
V = solve(VInv)
w = V %*% Xy
E_wtau = a_N/b_N*crossprod(w) + sum(diag(V))
d_N = d0 + 1/2*E_wtau
E_alpha = c(c_N/d_N)
} else {
b_N = b0 + 1/2*(crossprod(y - X%*%w) + t(w) %*% diag(E_alpha) %*% w)
VInv = diag(E_alpha) + XX
V = solve(VInv)
w = V %*% Xy
E_wtau = a_N/b_N*crossprod(w) + sum(diag(V))
d_N = d0 + 1/2*(c(w)^2 * a_N/b_N + diag(V))
E_alpha = c(c_N/d_N)
}
LQ_old = LQ
suppressWarnings({
LQ = -N/2*log(2*pi) - 1/2*(a_N/b_N * crossprod(y- crossprod(t(X), w)) + sum(XX * V))
+ 1/2 * log(det(V)) + D/2
- log(gamma(a0)) + a0*log(b0) - b0*a_N/b_N + log(gamma(a_N)) - a_N*log(b_N) + a_N
- log(gamma(c0)) + c0*log(d0) + log(gamma(c_N)) - sum(c_N*log(d_N))
})
tolCurrent = abs(LQ - LQ_old)
# alternate tolerance, comment out LQ_old up to this line if using
# tolCurrent = sum(abs(w - wold))
}
res = list(coef=w, sigma=sqrt(1/(E_wtau/crossprod(w))), LQ=LQ, iterations=iter, tol=tolCurrent)
if (iter>=maxiter) {
res = append(res, warning('Maximum iterations reached.'))
} else {res}
}
```
With function in place, we can simulate some data and see how it performs. Note that here, I explicitly note the intercept, as it is added to the model matrix within the vbreg function.
```{r dataPrep, cache=TRUE}
### Data set up
set.seed(1234)
n = 100
d = 3
coefs = c(1, 2, 3, 5)
sigma = 2
X = replicate(d, rnorm(n))
colnames(X) = paste0('X', 1:d)
y = cbind(1, X) %*% coefs + rnorm(n, sd=sigma)
### Run
res = vbreg(X, y, tol=1e-8, ard = F)
res
# With automatic relevance determination
res = vbreg(X, y, tol=1e-8, ard = T)
res
```
We can also look at the higher dimension case as done in Drugowitsch section 2.6.2.
```{r higherdim, cache=TRUE}
n = 150
ntest = 50
d = 100
coefs = rnorm(d + 1)
sigma = 1
Xtrain = cbind(1, replicate(d, rnorm(n)))
ytrain = Xtrain %*% coefs + rnorm(n, sd=sigma)
Xtest = cbind(1, replicate(d, rnorm(ntest)))
ytest = Xtest %*% coefs + rnorm(ntest, sd=sigma)
vbResult = vbreg(Xtrain[,-1], ytrain)
glmResult = glm.fit(Xtrain, ytrain)
vbTrainError = mean((ytrain - Xtrain %*% vbResult[['coef']])^2)
vbTestError = mean((ytest - Xtest %*% vbResult[['coef']])^2)
glmTrainError = mean((ytrain - Xtrain %*% glmResult[['coefficients']])^2)
glmTestError = mean((ytest - Xtest %*% glmResult[['coefficients']])^2)
mseResults = data.frame(vb=rbind(vbTrainError, vbTestError),
glm=rbind(glmTrainError, glmTestError))
rownames(mseResults) = c('train', 'test')
mseResults
```
In general the results are as expected where the standard approach overfits relative to vb reg. We can visualize the results as well, as in Drugowitsch figure 1.
```{r visResults}
library(ggvis)
# create coefficient data set for plotting
gcoef = data.frame(wGLM=coef(glmResult),
wVB=vbResult$coef,
w=coefs)
gcoef = reshape2::melt(gcoef, 'w')
# same for predictions
gpred = data.frame(predGLM = Xtest %*% coef(glmResult),
predVB = Xtest %*% vbResult$coef,
y = ytest)
gpred = reshape2::melt(gpred, 'y')
gcoef %>%
ggvis(~w, ~value) %>%
layer_lines(~w, ~w, strokeOpacity:=.5) %>%
layer_points(fill=~variable, fillOpacity:=.5)
gpred %>%
ggvis(~y, ~value) %>%
layer_lines(~y, ~y, strokeOpacity:=.5) %>%
layer_points(fill=~variable, fillOpacity:=.75)
```
And now for a notably higher dimension case with irrelevant predictors as in Drugowitsch section 2.6.3. This is problematic for the glm with having more covariates than data points (rank deficient), and as such it will throw a warning, as will the predict function. It's really not even worth looking at but I do so for consistency with the article's approach.
This will take a while for the standard vbreg, and even bumping up the iterations to 2000, it will still likely hit the max before reaching the default tolerance level. However, the results appear very similar to that of Drugowitsch Figure 2.
```{r ardDemo, cache=TRUE}
n = 500
ntest = 50
d = 1000
deff = 100
coefs = rnorm(deff+1)
sigma = 1
Xtrain = cbind(1, replicate(d, rnorm(n)))
ytrain = Xtrain %*% c(coefs, rep(0, d-deff)) + rnorm(n, sd=sigma)
Xtest = cbind(1, replicate(d, rnorm(ntest)))
ytest = Xtest %*% c(coefs, rep(0, d-deff)) + rnorm(ntest, sd=sigma)
vbResult = vbreg(Xtrain[,-1], ytrain, maxiter=2000)
vbARDResult = vbreg(Xtrain[,-1], ytrain, ard=T)
glmResult = glm(ytrain~., data=as.data.frame(Xtrain[,-1]))
vbTrainError = mean((ytrain - Xtrain %*% vbResult[['coef']])^2)
vbTestError = mean((ytest - Xtest %*% vbResult[['coef']])^2)
vbARDTrainError = mean((ytrain - Xtrain %*% vbARDResult[['coef']])^2)
vbARDTestError = mean((ytest - Xtest %*% vbARDResult[['coef']])^2)
glmTrainError = mean((ytrain - predict(glmResult))^2)
glmTestError = mean((ytest - predict(glmResult, as.data.frame(Xtest)))^2)
mseResults = data.frame(vb=rbind(vbTrainError, vbTestError),
vbARD=rbind(vbARDTrainError, vbARDTestError),
glm=rbind(glmTrainError, glmTestError))
rownames(mseResults) = c('train', 'test')
mseResults
```
Note how ARD correctly estimates zero for nonrelevant predictors.
```{r sumzerocoefs, cache=TRUE}
psych::describe(vbARDResult$coef[(deff+1):d])
```
Visualized, as before.
```{r visResults2}
library(ggvis)
gcoef = data.frame(wGLM=coef(glmResult),
wVB=vbResult$coef,
wVBARd = vbARDResult$coef,
w=c(coefs, rep(0,d-deff)))
gcoef = reshape2::melt(gcoef, 'w')
gpred = data.frame(predGLM = predict(glmResult, as.data.frame(Xtest)),
predVB = Xtest %*% vbResult$coef,
predVBARD = Xtest %*% vbARDResult$coef,
y = ytest)
gpred = reshape2::melt(gpred, 'y')
gcoef %>%
ggvis(~w, ~value) %>%
layer_lines(~w, ~w, strokeOpacity:=.5) %>%
layer_points(fill=~variable, fillOpacity:=.5)
gpred %>%
ggvis(~y, ~value) %>%
layer_lines(~y, ~y, strokeOpacity:=.5) %>%
layer_points(fill=~variable, fillOpacity:=.75)
```