-
Notifications
You must be signed in to change notification settings - Fork 17
/
bayesian-variational.Rmd
343 lines (250 loc) · 9.4 KB
/
bayesian-variational.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# Variational Bayes Regression
The following provides a function for estimating the parameters of a linear regression via variational inference. 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 target 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/DrugowitschLab/VBLinLogit/blob/master/src/vb_linear_fit.m) and [here](https://github.com/DrugowitschLab/VBLinLogit/blob/master/src/vb_linear_fit_ard.m) for his Matlab implementations.
- Bishop: Pattern Recognition and Machine Learning
## Data Setup
We can simulate some data as a starting point, in this case, basic tabular data used in the standard regression problem. Here, I explicitly note the intercept, as it is added to the model matrix within the <span class="func" style = "">vb_reg</span> function.
```{r vb-setup}
library(tidyverse)
set.seed(1234)
n = 100
d = 3
coefs = c(1, 2, 3, 5)
sigma = 2
X = replicate(d, rnorm(n)) # predictors
colnames(X) = paste0('X', 1:d)
y = cbind(1, X) %*% coefs + rnorm(n, sd = sigma) # target
df = data.frame(X, y)
```
We can also look at the higher dimension case as done in Drugowitsch section 2.6.2.
```{r vb-setup-high-dim}
n = 150
ntest = 50
d = 100
coefs = rnorm(d + 1)
sigma = 1
X_train = cbind(1, replicate(d, rnorm(n)))
y_train = X_train %*% coefs + rnorm(n, sd = sigma)
X_test = cbind(1, replicate(d, rnorm(ntest)))
y_test = X_test %*% coefs + rnorm(ntest, sd = sigma)
```
## Function
First, the main function. For this demo, automatic relevance determination is an argument rather than a separate function.
```{r vb_reg}
vb_reg <- 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 * c(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 * determinant(V, log = TRUE)$modulus + D/2 - lgamma(a0) + a0 * log(b0) - b0 * a_N / b_N +
lgamma(a_N) - a_N * log(b_N) + a_N - lgamma(c0) + c0*log(d0) +
lgamma(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)
append(res, warning('Maximum iterations reached.'))
else
res
}
```
## Estimation
First we can estimate the model using the smaller data.
```{r vbreg-est-small}
fit_small = vb_reg(X, y, tol = 1e-8, ard = FALSE)
glimpse(fit_small)
# With automatic relevance determination
fit_small_ard = vb_reg(X, y, tol = 1e-8, ard = TRUE)
glimpse(fit_small_ard)
lm_mod = lm(y ~ ., data = df)
```
Now with the higher dimensional data. We fit using the training data and will estimate the error on training and test using the <span class="pack" style = "">yardstick</span> package.
```{r vbreg-est-big}
fit_vb = vb_reg(X_train[,-1], y_train)
fit_glm = glm.fit(X_train, y_train)
# predictions
vb_pred_train = X_train %*% fit_vb[['coef']]
vb_pred_test = X_test %*% fit_vb[['coef']]
glm_pred_train = fitted(fit_glm)
glm_pred_test = X_test %*% coef(fit_glm)
# error
vb_train_error = yardstick::rmse_vec(y_train[,1], vb_pred_train[,1])
vb_test_error = yardstick::rmse_vec(y_test[,1], vb_pred_test[,1])
glm_train_error = yardstick::rmse_vec(y_train[,1], glm_pred_train)
glm_test_error = yardstick::rmse_vec(y_test[,1], glm_pred_test[,1])
```
## Comparison
For the smaller data, we will compare the coefficients.
```{r vbreg-compare-small, echo=FALSE}
tibble(no_ard = fit_small$coef[, 1],
ard = fit_small_ard$coef[, 1],
lm = coef(lm_mod)) %>%
kable_df()
```
For the higher dimensional data, we will compare root mean square error.
```{r vbreg-compare-big, echo=FALSE}
mse_results = data.frame(
vb = c(vb_train_error, vb_test_error),
glm = c(glm_train_error, glm_test_error)
)
rownames(mse_results) = c('train', 'test')
mse_results %>% kable_df()
```
## Visualization
In general the results are as expected where the standard approach overfits relative to VB regression. The following visualizes them, similar to Drugowitsch figure 1.
```{r vbreg-vis, echo=FALSE}
# create coefficient data set for plotting
gcoef = tibble(source = rep(c('true', 'vb', 'glm'), each = length(coefs)),
coef = rep(1:length(coefs), 3),
value = c(coefs, fit_vb$coef[,1], wGLM = coef(fit_glm)))
gcoef %>%
ggplot(aes(coef, value, color = source)) +
# geom_line(alpha = .2) +
geom_point(alpha = .5) +
scico::scale_color_scico_d(end = .6)
# same for predictions
gpred = tibble(
predGLM = c(X_test %*% coef(fit_glm)),
predVB = c(X_test %*% fit_vb$coef),
y = c(y_test)
) %>%
pivot_longer(-y, names_to = 'source', values_to = 'prediction')
gpred %>%
ggplot(aes(prediction, y)) +
geom_point(alpha = .5, color = '#ff5500') +
labs(x = 'Test Prediction', y = 'Observed') +
facet_grid(~source)
```
## Supplemental Example
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 have the code for consistency.
This will take a while to estimate, and without ARD, 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 vbreg-supp-setup}
set.seed(1234)
n = 500
ntest = 50
d = 1000
deff = 100
coefs = rnorm(deff + 1)
sigma = 1
X_train = cbind(1, replicate(d, rnorm(n)))
y_train = X_train %*% c(coefs, rep(0, d - deff)) + rnorm(n, sd = sigma)
X_test = cbind(1, replicate(d, rnorm(ntest)))
y_test = X_test %*% c(coefs, rep(0, d - deff)) + rnorm(ntest, sd = sigma)
```
```{r vbreg-supp-est}
fit_vb = vb_reg(X_train[,-1], y_train)
fit_vb_ard = vb_reg(X_train[,-1], y_train, ard = TRUE)
# fit_glm = glm(y_train ~ ., data = data.frame(X_train[,-1]))
```
```{r vbreg-supp-predict}
# predictions
vb_pred_train = X_train %*% fit_vb[['coef']]
vb_pred_test = X_test %*% fit_vb[['coef']]
#
vb_ard_pred_train = X_train %*% fit_vb_ard[['coef']]
vb_ard_pred_test = X_test %*% fit_vb_ard[['coef']]
# glm_pred_train = fitted(fit_glm)
# glm_pred_test = X_test %*% coef(fit_glm)
# error
vb_train_error = yardstick::rmse_vec(y_train[,1], vb_pred_train[,1])
vb_test_error = yardstick::rmse_vec(y_test[,1], vb_pred_test[,1])
# error
vb_ard_train_error = yardstick::rmse_vec(y_train[,1], vb_ard_pred_train[,1])
vb_ard_test_error = yardstick::rmse_vec(y_test[,1], vb_ard_pred_test[,1])
# glm_train_error = yardstick::rmse_vec(y_train[,1], glm_pred_train)
# glm_test_error = yardstick::rmse_vec(y_test[,1], glm_pred_test[,1])
```
```{r vbreg-supp-rmse}
mse_results = data.frame(
vb = c(vb_train_error, vb_test_error),
vbARD = c(vb_ard_train_error, vb_ard_test_error)#,
# glm = c(glm_train_error, glm_test_error)
)
rownames(mse_results) = c('train', 'test')
kable_df(mse_results)
```
Note how ARD correctly estimates (nearly) zero for irrelevant predictors.
```{r vbreg-supp-zero-coefs, echo=FALSE}
tidyext::num_summary(fit_vb_ard$coef[(deff + 1):d]) %>%
kable_df()
```
Visualized, as before.
```{r vbreg-supp-vis, echo=FALSE}
gcoef = tibble(source = rep(c('true', 'vb', 'vb_ard'), each = 1001),
coef = rep(1:1001, 3),
value = c(c(coefs, rep(0, d - deff)),
fit_vb$coef[, 1],
fit_vb_ard$coef[, 1]))
gcoef %>%
ggplot(aes(coef, value, color = source)) +
geom_point(alpha = .5) +
scico::scale_color_scico_d(end = .6)
```
## Source
Original code available at:
https://github.com/m-clark/Miscellaneous-R-Code/tree/master/ModelFitting/Bayesian/multinomial