-
Notifications
You must be signed in to change notification settings - Fork 35
/
plsa.py
219 lines (193 loc) · 6.32 KB
/
plsa.py
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
from numpy import zeros, int8, log
from pylab import random
import sys
import jieba
import re
import time
import codecs
# segmentation, stopwords filtering and document-word matrix generating
# [return]:
# N : number of documents
# M : length of dictionary
# word2id : a map mapping terms to their corresponding ids
# id2word : a map mapping ids to terms
# X : document-word matrix, N*M, each line is the number of terms that show up in the document
def preprocessing(datasetFilePath, stopwordsFilePath):
# read the stopwords file
file = codecs.open(stopwordsFilePath, 'r', 'utf-8')
stopwords = [line.strip() for line in file]
file.close()
# read the documents
file = codecs.open(datasetFilePath, 'r', 'utf-8')
documents = [document.strip() for document in file]
file.close()
# number of documents
N = len(documents)
wordCounts = [];
word2id = {}
id2word = {}
currentId = 0;
# generate the word2id and id2word maps and count the number of times of words showing up in documents
for document in documents:
segList = jieba.cut(document)
wordCount = {}
for word in segList:
word = word.lower().strip()
if len(word) > 1 and not re.search('[0-9]', word) and word not in stopwords:
if word not in word2id.keys():
word2id[word] = currentId;
id2word[currentId] = word;
currentId += 1;
if word in wordCount:
wordCount[word] += 1
else:
wordCount[word] = 1
wordCounts.append(wordCount);
# length of dictionary
M = len(word2id)
# generate the document-word matrix
X = zeros([N, M], int8)
for word in word2id.keys():
j = word2id[word]
for i in range(0, N):
if word in wordCounts[i]:
X[i, j] = wordCounts[i][word];
return N, M, word2id, id2word, X
def initializeParameters():
for i in range(0, N):
normalization = sum(lamda[i, :])
for j in range(0, K):
lamda[i, j] /= normalization;
for i in range(0, K):
normalization = sum(theta[i, :])
for j in range(0, M):
theta[i, j] /= normalization;
def EStep():
for i in range(0, N):
for j in range(0, M):
denominator = 0;
for k in range(0, K):
p[i, j, k] = theta[k, j] * lamda[i, k];
denominator += p[i, j, k];
if denominator == 0:
for k in range(0, K):
p[i, j, k] = 0;
else:
for k in range(0, K):
p[i, j, k] /= denominator;
def MStep():
# update theta
for k in range(0, K):
denominator = 0
for j in range(0, M):
theta[k, j] = 0
for i in range(0, N):
theta[k, j] += X[i, j] * p[i, j, k]
denominator += theta[k, j]
if denominator == 0:
for j in range(0, M):
theta[k, j] = 1.0 / M
else:
for j in range(0, M):
theta[k, j] /= denominator
# update lamda
for i in range(0, N):
for k in range(0, K):
lamda[i, k] = 0
denominator = 0
for j in range(0, M):
lamda[i, k] += X[i, j] * p[i, j, k]
denominator += X[i, j];
if denominator == 0:
lamda[i, k] = 1.0 / K
else:
lamda[i, k] /= denominator
# calculate the log likelihood
def LogLikelihood():
loglikelihood = 0
for i in range(0, N):
for j in range(0, M):
tmp = 0
for k in range(0, K):
tmp += theta[k, j] * lamda[i, k]
if tmp > 0:
loglikelihood += X[i, j] * log(tmp)
return loglikelihood
# output the params of model and top words of topics to files
def output():
# document-topic distribution
file = codecs.open(docTopicDist,'w','utf-8')
for i in range(0, N):
tmp = ''
for j in range(0, K):
tmp += str(lamda[i, j]) + ' '
file.write(tmp + '\n')
file.close()
# topic-word distribution
file = codecs.open(topicWordDist,'w','utf-8')
for i in range(0, K):
tmp = ''
for j in range(0, M):
tmp += str(theta[i, j]) + ' '
file.write(tmp + '\n')
file.close()
# dictionary
file = codecs.open(dictionary,'w','utf-8')
for i in range(0, M):
file.write(id2word[i] + '\n')
file.close()
# top words of each topic
file = codecs.open(topicWords,'w','utf-8')
for i in range(0, K):
topicword = []
ids = theta[i, :].argsort()
for j in ids:
topicword.insert(0, id2word[j])
tmp = ''
for word in topicword[0:min(topicWordsNum, len(topicword))]:
tmp += word + ' '
file.write(tmp + '\n')
file.close()
# set the default params and read the params from cmd
datasetFilePath = 'dataset.txt'
stopwordsFilePath = 'stopwords.dic'
K = 10 # number of topic
maxIteration = 30
threshold = 10.0
topicWordsNum = 10
docTopicDist = 'docTopicDistribution.txt'
topicWordDist = 'topicWordDistribution.txt'
dictionary = 'dictionary.dic'
topicWords = 'topics.txt'
if(len(sys.argv) == 11):
datasetFilePath = sys.argv[1]
stopwordsFilePath = sys.argv[2]
K = int(sys.argv[3])
maxIteration = int(sys.argv[4])
threshold = float(sys.argv[5])
topicWordsNum = int(sys.argv[6])
docTopicDist = sys.argv[7]
topicWordDist = sys.argv[8]
dictionary = sys.argv[9]
topicWords = sys.argv[10]
# preprocessing
N, M, word2id, id2word, X = preprocessing(datasetFilePath, stopwordsFilePath)
# lamda[i, j] : p(zj|di)
lamda = random([N, K])
# theta[i, j] : p(wj|zi)
theta = random([K, M])
# p[i, j, k] : p(zk|di,wj)
p = zeros([N, M, K])
initializeParameters()
# EM algorithm
oldLoglikelihood = 1
newLoglikelihood = 1
for i in range(0, maxIteration):
EStep()
MStep()
newLoglikelihood = LogLikelihood()
print("[", time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), "] ", i+1, " iteration ", str(newLoglikelihood))
if(oldLoglikelihood != 1 and newLoglikelihood - oldLoglikelihood < threshold):
break
oldLoglikelihood = newLoglikelihood
output()