-
Notifications
You must be signed in to change notification settings - Fork 17
/
bayesian-topic-model.Rmd
450 lines (347 loc) · 12.2 KB
/
bayesian-topic-model.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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# Topic Model
An implementation of Gibbs sampling for topic models for the example in section
4 of [Steyvers and Griffiths (2007)](http://cocosci.berkeley.edu/tom/papers/SteyversGriffiths.pdf). A very clear intro in my opinion. The core of the function's code comprises mostly cosmetic
changes to that found [here](https://bcomposes.wordpress.com/2012/05/29/gibbs-sampler-for-toy-topic-model-example/). Added are the creation of a function with several arguments, plotting etc.
## Data Setup
```{r tm-setup}
library(tidyverse)
vocab = factor(c("river", "stream", "bank", "money", "loan"))
K = 2 # n of topics
v = length(vocab) # number of unique words
d = 16 # number of documents
```
Topic 1 gives equal probability to money loan and bank (zero for river and stream).
Topic 2 gives equal probability to river stream and bank (zero for money and loan).
Next we create a document term matrix. Each doc consists of a mix of 16 tokens of the vocab-
the first few regard financial banks, the last several water banks, and the docs in between possess a mixed vocab.
```{r tm-setup2}
dtm = matrix(c(0,0,4,6,6,
0,0,5,7,4,
0,0,7,5,4,
0,0,7,6,3,
0,0,7,2,7,
0,0,9,3,4,
1,0,4,6,5,
1,2,6,4,3,
1,3,6,4,2,
2,3,6,1,4,
2,3,7,3,1,
3,6,6,1,0,
6,3,6,0,1,
2,8,6,0,0,
4,7,5,0,0,
5,7,4,0,0), ncol = v, byrow = TRUE)
rownames(dtm) = paste0('doc', 1:d)
colnames(dtm) = vocab
```
Next we create additional objects to initialize the setup.
```{r tm-setup3}
# matrix of words in each document
wordmat = t(apply(dtm, 1, function(row) rep(vocab, row)))
# initialize random topic assignments to words
T0 = apply(wordmat, c(1, 2), function(token) sample(1:2, 1))
# word by topic matrix of counts containing the number of times word w is
# assigned to topic j
C_wt = sapply(vocab, function(word) cbind(sum(T0[wordmat == word] == 1),
sum(T0[wordmat == word] == 2)))
C_wt = t(C_wt)
rownames(C_wt) = vocab
# topic by document matrix of counts containing the number of times topic j is
# assigned to a word in document d
C_dt = t(apply(T0, 1, table))
```
## Function
Note that this function is not self contained in that it uses some of the objects created above, assuming they are in the global environment. It has the capacity for a pseudo-visualization which can be instructive, but isn't shown for this document (and it requries <span class="pack" style = "">corrplot</span>), and I haven't tested it recently.
```{r tm-function}
topic_model <- function(
alpha,
beta,
nsim = 2000,
warmup = nsim / 2,
thin = 10,
verbose = TRUE,
plot = FALSE,
dotsortext = 'dots'
) {
# Arguments:
# alpha and beta: hyperparameters
# nsim: the total number of simulations
# warmup: the number of initial sims to discard
# thin: keep every thin simulation after warmup
# verbose: to print every 100th iteration and total time
# plot: to visualize every x sim; the plot will show current estimates of
# theta, phi, and topic assignments for each term in the docs; can be
# visualized as dots or the actual terms; for the latter you may need to
# fiddle with your viewing area size so that terms don't appear to run
# together; plotting will increase runtime
# requires corrplot for visualizations, and abind to create arrays from the
# lists.
# initialize
Z = T0 # topic assignments
saveSim = seq(warmup + 1, nsim, thin) # iterations to save
theta_list = list() # saved theta estimates
phi_list = list() # saved phi estimates
p = proc.time()
# for every simulation...
for (s in 1:nsim) {
if(verbose && s %% 100 == 0) { # paste every 100th iteration if desired
secs = round((proc.time() - p)[3],2)
min = round(secs/60, 2)
message(paste0(
'Iteration number: ',
s,
'\n',
'Total time: ',
ifelse(secs <= 60, paste(secs, 'seconds'), paste(min, 'minutes'))
))
}
# Visualization
if(plot > 0 && s >1 && s %% plot == 0) { # plot every value of argument
require(corrplot)
layout(matrix(c(1, 1, 2, 2, 3, 3, 3, 3, 3, 3), ncol = 10))
corrplot(
theta,
is.corr = FALSE,
method = 'color',
tl.cex = .75,
tl.col = 'gray50',
cl.pos = 'n',
addgrid = NA
)
corrplot(
phi,
is.corr = FALSE,
method = 'color',
tl.cex = 1,
tl.col = 'gray50',
cl.pos = 'n',
addgrid = NA
)
if (dotsortext == 'dots') {
Zplot = Z
Zplot[Zplot == 2] = -1
corrplot(
Zplot,
is.corr = FALSE,
method = 'circle',
tl.cex = .75,
tl.col = 'gray50',
cl.pos = 'n',
addgrid = NA
)
} else {
cols = apply(Z, c(1, 2), function(topicvalue)
ifelse(topicvalue == 1, '#053061', '#67001F'))
plot(
1:nrow(wordmat),
1:ncol(wordmat),
type = "n",
axes = FALSE,
xlab = '',
ylab = ''
)
text(col(wordmat),
rev(row(wordmat)),
wordmat,
col = cols,
cex = .75)
}
}
# for every document and every word in the document
for (i in 1:d) {
for (j in 1:length(wordmat[i,])) {
word.id = which(vocab == wordmat[i, j])
topic.old = Z[i, j]
# Decrement counts before computing equation (3) in paper noted above
C_dt[i, topic.old] = C_dt[i, topic.old] - 1
C_wt[word.id, topic.old] = C_wt[word.id, topic.old] - 1
# Calculate equation (3) for each topic
vals = prop.table(C_wt + beta, 2)[word.id,] * prop.table(C_dt[i,] + alpha)
# Sample the new topic from the results for (3);
# note, sample function does not require you to have the probs sum to 1
# explicitly, i.e. prob=c(1,1,1) is the same as prob = c(1/3, 1/3, 1/3)
Z.new = sample(1:K, 1, prob = vals)
# Set the new topic and update counts
Z[i,j] = Z.new
C_dt[i, Z.new] = C_dt[i, Z.new] + 1
C_wt[word.id, Z.new] = C_wt[word.id, Z.new] + 1
}
}
theta = prop.table(C_dt + alpha,1) # doc topic distribution
phi = prop.table(C_wt + beta,2) # word topic distribution
# save simulations
if (s %in% saveSim){
theta_list[[paste(s)]] = theta
phi_list[[paste(s)]] = phi
}
}
layout(1) # reset plot window
list(
theta = theta,
phi = phi,
theta_sims = abind::abind(theta_list, along = 3),
phi_sims = abind::abind(phi_list, along = 3)
)
}
```
## Estimation
We use the values of alpha and beta as suggested in paper. The following will result in 500 posterior sample points, so bump if you want more than that. These settings take around 20 seconds.
```{r tm-est}
set.seed(1234)
alpha = K/50
beta = .01
fit_tm = topic_model(
alpha = alpha,
beta = beta,
nsim = 1000,
warmup = 500,
thin = 1,
verbose = FALSE,
plot = FALSE
)
```
## Comparison
First we can explore the results, in particular topic assignment probabilities and term topic probabilities.
```{r tm-inspect}
str(fit_tm, 1)
purrr::map(fit_tm[1:2], round, 2)
```
Now we can compare our result to reported paper estimates for $\phi$ and <span class="pack" style = "">topicmodels</span> package (note delta is the beta above; the vignette actually references Steyvers & Griffiths paper).
```{r tm-LDA}
library(topicmodels)
fit_lda = LDA(
dtm,
k = 2,
method = 'Gibbs',
control = list(
alpha = alpha,
delta = .01,
iter = 5500,
burnin = 500,
thin = 10,
initialize = 'random'
)
)
```
Start with $\phi$ estimates. Note that the labels of what is topic 1 vs. topic 2 is arbitrary, the main thing is the separation of the words that should go to different topics, while bank is probable for both topics.
```{r tm-compare-phi, echo=FALSE}
phi_estimates = data.frame(
fit = round(fit_tm$phi, 2),
paper = cbind(c(0, 0, .39, .32, .29), c(.25, .4, .35, 0, 0)),
ldapack = round(t(posterior(fit_lda)$terms), 2)
)
# make arbitrary labels consistent?
# if (sum(abs(phi_estimates$fit.1 - phi_estimates$paper.1)) > .5) {
# phi_estimates = phi_estimates %>%
# mutate(
# fit.1 = phi_estimates$fit.2,
# fit.2 = phi_estimates$fit.1
# )
# }
kable_df(phi_estimates)
```
Interval estimates for term probabilities for each topic.
```{r tm-phi-interval}
library(coda)
phi_estimates_topic_1 = as.mcmc(t(fit_tm$phi_sims[, 1, ]))
phi_estimates_topic_2 = as.mcmc(t(fit_tm$phi_sims[, 2, ]))
# summary(phi_estimates_topic_1)
```
```{r tm-phi-interval-show, echo=FALSE}
map_df(list(
`Topic 1` = round(phi_estimates_topic_1, 2),
`Topic 2` = round(phi_estimates_topic_2, 2)
), function(x)
data.frame(HPDinterval(x)), .id = 'Topic') %>%
rownames_to_column() %>%
kable_df()
```
Symmetrized or mean [Kullback-Liebler divergence](https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence) for topic (dis)similarity.
```{r tm-kldiv-topic}
kl_divergence = .5 * sum(
apply(
fit_tm$phi,
1, function(row) row[1] * log2(row[1] / row[2]) + row[2] * log2(row[2] / row[1])
)
)
kl_divergence
```
We can compare with various other packages for KL-divergence (not shown).
```{r tm-kldiv-topic-compare, eval = FALSE}
mean(c(
entropy::KL.empirical(fit_tm$phi[,1], fit_tm$phi[,2], unit = 'log2'),
entropy::KL.empirical(fit_tm$phi[,2], fit_tm$phi[,1], unit = 'log2')
))
```
Symmetrized or mean Kullback-Liebler divergence for document (dis)similarity.
```{r tm-kldiv-doc}
# example
docs2compare = c(1, 16)
.5 * sum(apply(fit_tm$theta[docs2compare, ], 2,
function(topicprob)
topicprob[1] * log(topicprob[1] / topicprob[2]) +
topicprob[2] * log(topicprob[2] / topicprob[1])))
```
Let's create a function to work on theta to produce Kullback-Liebler or Jensen-Shannon divergence.
```{r tm-kldiv-doc-func}
divergence <- function(input, method = 'KL') {
if (method == 'KL') {
.5 * sum(apply(fit_tm$theta[input, ], 2,
function(topicprob)
topicprob[1] * log2(topicprob[1] / topicprob[2]) +
topicprob[2] * log2(topicprob[2] / topicprob[1])))
}
else {
.5 * sum(apply(fit_tm$theta[input, ], 2,
function(topicprob)
topicprob[1] * log2(topicprob[1] / mean(topicprob)) +
topicprob[2] * log2(topicprob[2] / mean(topicprob))))
}
}
```
Now apply to all pairs of documents.
```{r tm-kldiv-doc-all}
# Now do for all
docpairs = combn(1:d, 2)
kl_divergence = apply(docpairs, 2, divergence)
mat0 = matrix(0, d, d)
mat0[lower.tri(mat0)] = kl_divergence
kl_divergence = mat0 + t(mat0)
dimnames(kl_divergence) = list(rownames(dtm))
```
We can visualizes as follows, red implies documents are more dissimilar.
```{r tm-kldiv-doc-all-vis, echo = FALSE}
heatmaply::heatmaply_cor(
kl_divergence,
Rowv = FALSE,
Colv = FALSE,
limits = NULL,
main = 'Kullback-Liebler Divergence'
)
```
Likewise, we can visualize [Jensen-Shannon divergence](https://en.wikipedia.org/wiki/Jensen%E2%80%93Shannon_divergence).
```{r tm-js-div-doc-all}
js_divergence = apply(docpairs, 2, divergence, method = 'JS')
```
```{r tm-js-div-doc-all-vis, echo = FALSE}
mat0 = matrix(0, d, d)
mat0[lower.tri(mat0)] = js_divergence
js_divergence = mat0 + t(mat0)
dimnames(js_divergence) = list(rownames(dtm))
heatmaply::heatmaply_cor(
js_divergence,
Rowv = FALSE,
Colv = FALSE,
limits = NULL,
main = 'Jensen-Shannon Divergence'
)
```
Here are examples of diagnostics with the word topic probability estimates. These use the <span class="" style = "">bayesplot</span> package.
```{r tm-bayes-diagnostics}
library(bayesplot)
mcmc_combo(phi_estimates_topic_1)
mcmc_acf(phi_estimates_topic_1)
```
## Source
Original code available at:
https://github.com/m-clark/Miscellaneous-R-Code/blob/master/ModelFitting/Bayesian/topicModelgibbs.R