-
Notifications
You must be signed in to change notification settings - Fork 8
/
CVBLDA.java
267 lines (262 loc) · 8.48 KB
/
CVBLDA.java
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
package com.topic.model;
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this
* program.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.topic.utils.FileUtil;
import com.topic.utils.FuncUtils;
/**
* TopicModel4J: A Java package for topic models
*
* Collapsed Variational Bayesian Inference for LDA
*
* Reference:
* Teh Y W, Newman D, Welling M. A collapsed variational Bayesian inference algorithm for latent Dirichlet allocation[C]//Advances in neural information processing systems. 2007: 1353-1360.
* Asuncion A, Welling M, Smyth P, et al. On smoothing and inference for topic models[C]//Proceedings of the twenty-fifth conference on uncertainty in artificial intelligence. AUAI Press, 2009: 27-34.
*
* @author: Yang Qian,Yuanchun Jian,Yidong Chai,Yezheng Liu,Jianshan Sun (HeFei University of Technology)
*/
public class CVBLDA
{
public double alpha; // Hyper-parameter alpha
public double beta; // Hyper-parameter beta
public int K; // number of topics
public int iterations; // number of iterations
public Map<String, Integer> wordToIndexMap = new HashMap<String, Integer>();; //word to index
public List<String> indexToWordMap = new ArrayList<String>(); //index to String word
public int M; // number of documents in the corpus
public int V; // number of words in the corpus
public int [][] docword;//word index array
//variational parameters
public double[][] nmk; //�ĵ�d������k���ɵĵ�����Ŀ(����)nmk+cmk
public double[] nm; //
public double[][] nkw; //����k�����ĵ���w����Ŀ(����) K*V
public double[] nkw_sum; //����k�������ܵ�����Ŀ(����)
public double[][][] gamma_word;
//output
public int topWordsOutputNumber;
public String outputFileDirectory;
public CVBLDA(String inputFile, String inputFileCode, int topicNumber,
double inputAlpha, double inputBeta, int inputIterations, int inTopWords,
String outputFileDir){
//read data
ArrayList<String> docLines = new ArrayList<String>();
FileUtil.readLines(inputFile, docLines,inputFileCode);
M = docLines.size();
docword = new int[M][];
int j = 0;
for(String line : docLines){
List<String> words = new ArrayList<String>();
FileUtil.tokenizeAndLowerCase(line, words);
docword[j] = new int[words.size()];
for(int i = 0; i < words.size(); i++){
String word = words.get(i);
if(!wordToIndexMap.containsKey(word)){
int newIndex = wordToIndexMap.size();
wordToIndexMap.put(word, newIndex);
indexToWordMap.add(word);
docword[j][i] = newIndex;
} else {
docword[j][i] = wordToIndexMap.get(word);
}
}
j++;
}
V = indexToWordMap.size();
alpha = inputAlpha;
beta = inputBeta;
K = topicNumber;
iterations = inputIterations;
topWordsOutputNumber = inTopWords;
outputFileDirectory = outputFileDir;
initialize();
}
/**
* Randomly initialize the parameter
*/
public void initialize(){
//�ĵ�����
int D = docword.length;
//variational parameters
nmk = new double[D][K];
nm = new double[D];
nkw = new double[K][V];
nkw_sum = new double[K];
gamma_word = new double[D][][];
//ѭ��ÿƪ�ĵ�
for (int d = 0; d < D; d++) {
// �ĵ���������
int Nd = docword[d].length;
gamma_word[d] = new double[Nd][K];
for(int n = 0; n < Nd; n ++) {
gamma_word[d][n] = FuncUtils.getGaussianSample(K, 0.5, 0.5);
double gamma_norm = 0;
for(int k = 0; k < K; k ++) {
gamma_norm += Math.exp(gamma_word[d][n][k]);
}
for(int k = 0; k < K; k ++) {
gamma_word[d][n][k] = Math.exp(gamma_word[d][n][k]) / gamma_norm;
nkw_sum[k] += gamma_word[d][n][k];
nmk[d][k] += gamma_word[d][n][k];
nkw[k][docword[d][n]] += gamma_word[d][n][k];
nm[d] += gamma_word[d][n][k];
}
}
}
}
public void CVBInference(){
for (int iter = 1; iter <= iterations; iter++) {
System.out.println("iteration : " + iter);
iterateCVB0Update();
}
// output the result
System.out.println("write topic word ..." );
writeTopWordsWithProbability();
System.out.println("write document topic ..." );
writeDocumentTopic();
writeTopWords();
}
public void iterateCVB0Update() {
int D = docword.length;
for(int d = 0; d < D; d ++) {
for(int n = 0; n < docword[d].length; n ++) {
double norm_w = 0;
double[] gamma_w = new double[K];
for(int k = 0; k < K; k ++) {
gamma_w[k] = gamma_word[d][n][k];
gamma_word[d][n][k] = (updateCount(d, n, k, 0, d) + alpha)*
(beta + updateCount(d, n, k, docword[d][n], -1))/(V * beta + updateCount(d, n, k, 0, -1));
norm_w += gamma_word[d][n][k];
}
for(int k = 0; k < K; k ++) {
gamma_word[d][n][k] /= norm_w;
//update
nkw_sum[k] += gamma_word[d][n][k] - gamma_w[k];
nmk[d][k] += gamma_word[d][n][k] - gamma_w[k];
nkw[k][docword[d][n]] += gamma_word[d][n][k] - gamma_w[k];
nm[d] += gamma_word[d][n][k] - gamma_w[k];
}
}
}
}
/**
* update the count
* expect the word d_n
* @param
* @return
*/
public double updateCount(int d, int n, int k, int wsdn, int doc) {
if(wsdn == 0 && doc == -1)
return nkw_sum[k] - gamma_word[d][n][k];
else if(doc == -1)
return nkw[k][wsdn] - gamma_word[d][n][k];
else
return nmk[doc][k] - gamma_word[d][n][k];
}
/**
* obtain the parameter Theta
*/
public double[][] estimateTheta() {
double[][] theta = new double[docword.length][K];
for (int d = 0; d < docword.length; d++) {
for (int k = 0; k < K; k++) {
theta[d][k] = (nmk[d][k] + alpha) / (nm[d] + K * alpha);
}
}
return theta;
}
/**
* obtain the parameter Phi
*/
public double[][] estimatePhi() {
double[][] phi = new double[K][V];
for (int k = 0; k < K; k++) {
for (int w = 0; w < V; w++) {
phi[k][w] = (nkw[k][w] + beta) / (nkw_sum[k] + V * beta);
}
}
return phi;
}
/**
* write top words with probability for each topic
*/
public void writeTopWordsWithProbability(){
StringBuilder sBuilder = new StringBuilder();
double[][] phi = estimatePhi();
int topicNumber = 1;
for (double[] phi_z : phi) {
sBuilder.append("Topic:" + topicNumber + "\n");
for (int i = 0; i < topWordsOutputNumber; i++) {
int max_index = FuncUtils.maxValueIndex(phi_z);
sBuilder.append(indexToWordMap.get(max_index) + " :" + phi_z[max_index] + "\n");
phi_z[max_index] = 0;
}
sBuilder.append("\n");
topicNumber++;
}
try {
FileUtil.writeFile(outputFileDirectory + "topic_word_CVB_" + K + ".txt", sBuilder.toString(),"gbk");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* write top words with probability for each topic
*/
public void writeTopWords(){
StringBuilder sBuilder = new StringBuilder();
double[][] phi = estimatePhi();
for (double[] phi_z : phi) {
for (int i = 0; i < topWordsOutputNumber; i++) {
int max_index = FuncUtils.maxValueIndex(phi_z);
sBuilder.append(indexToWordMap.get(max_index) + "\t");
phi_z[max_index] = 0;
}
sBuilder.append("\n");
}
try {
FileUtil.writeFile(outputFileDirectory + "topic_wordnop_CVB_" + K + ".txt", sBuilder.toString(),"gbk");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* write theta for each document
*/
public void writeDocumentTopic(){
double[][] theta = estimateTheta();
StringBuilder sBuilder = new StringBuilder();
for (int d = 0; d < theta.length; d++) {
StringBuilder doc = new StringBuilder();
for (int k = 0; k < theta[d].length; k++) {
doc.append(theta[d][k] + "\t");
}
sBuilder.append(doc.toString().trim() + "\n");
}
try {
FileUtil.writeFile(outputFileDirectory + "doc_topic_CVB_" + K + ".txt", sBuilder.toString(),"gbk");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]) throws Exception{
CVBLDA lda = new CVBLDA("data/rawdata_process", "gbk", 30, 0.1,
0.01, 200, 50, "data/ldaoutput/");
lda.CVBInference();
}
}