-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
227 lines (197 loc) · 7.51 KB
/
main.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
220
221
222
223
224
225
226
227
import codecs
from nltk.corpus import reuters
from utils import Tokenizer, Paths, SingleFileCorpus
from gensim import corpora, models, similarities
from nltk.tokenize import word_tokenize, wordpunct_tokenize
from nltk.stem.porter import PorterStemmer
import numpy as np
import os
import logging
from nltk.stem.wordnet import WordNetLemmatizer
import random
import nltk
import time
import matplotlib.pyplot as plt
import wordcloud
import pandas as pd
# Preprocess script - build a single text file with cleaned, normalised documents
# - tokenised, stemmed, one document per line.
# Track fileids to retrieve document text later
def preProcess():
print 'PreProcess Reuters Corpus'
start_time = time.time()
docs = 0
bad = 0
tokenizer = Tokenizer()
if not os.path.isdir(Paths.base):
os.makedirs(Paths.base)
with open(Paths.text_index, 'w') as fileid_out:
with codecs.open(Paths.texts_clean, 'w', 'utf-8-sig') as out:
with codecs.open(Paths.reuter_test, 'w', 'utf-8-sig') as test:
for f in reuters.fileids():
contents = reuters.open(f).read()
try:
tokens = tokenizer.tokenize(contents)
docs += 1
if docs % 1000 == 0:
print "Normalised %d documents" % (docs)
out.write(' '.join(tokens) + "\n")
# if f.startswith("train"):
#
# else:
# test.write(' '.join(tokens) + "\n")
fileid_out.write(f + "\n")
except UnicodeDecodeError:
bad += 1
print "Normalised %d documents" % (docs)
print "Skipped %d bad documents" % (bad)
print 'Finished building train file ' + Paths.texts_clean
end_time = time.time()
print '(Time to preprocess Reuters Corpus: %s)' % (end_time - start_time)
# print 'Finished building test file ' + Paths.reuter_test
def buildCorpus():
start_time = time.time()
# Build corpus script - build gensim dictionary and corpus
dictionary = corpora.Dictionary()
print "Create dictionary and write out a processed file with one document per line"
#First pass: create dictionary and write out a processed file with
# one document per line
with codecs.open(Paths.texts_clean, 'r', 'utf-8') as f:
for doc in f:
tokens = doc.strip().split()
dictionary.doc2bow(tokens, allow_update=True)
print "Remove very rare and very common words"
# Remove very rare and very common words
dictionary.filter_extremes(no_below=1, no_above=0.8)
dictionary.save(Paths.dictionary)
print "Second pass over files to serialize corpus to file"
#Second pass over files to serialize corpus to file
corpus = SingleFileCorpus(Paths.texts_clean, dictionary)
corpora.MmCorpus.serialize(Paths.corpus, corpus)
end_time = time.time()
print '(Time to build dictionary and corpus: %s)' % (end_time - start_time)
def trainLDA(n_topics):
start_time = time.time()
print "Loading corpus and dictionary"
corpus = corpora.MmCorpus(Paths.corpus)
dictionary = corpora.Dictionary.load(Paths.dictionary)
print "extract %d LDA topics, using 20 full passes, no online updates" % (n_topics)
lda = models.LdaModel(corpus, id2word=dictionary, num_topics=n_topics, update_every=0, passes=20)
print "Saving LDA Model"
lda.save(Paths.lda_model)
print 'Finished train LDA Model %s ' + Paths.lda_model
end_time = time.time()
print '(Time to train LDA model: %s)' % (end_time - start_time)
def displayLDA(n_topics, num_words):
print "Loading LDA Model"
lda = models.LdaModel.load(Paths.lda_model)
i = 0
# ftt = open((Paths.final_topics), 'wb')
# for topic in lda.show_topics(num_topics=n_topics, num_words=num_words, log=False, formatted=True):
# # print '#' + str(i) + ': ' + topic
# i += 1
# ftt.close()
topics_matrix = lda.show_topics(formatted=False, num_words=num_words)
topics_matrix = np.array(topics_matrix)
topic_words = topics_matrix[:,:,1]
for topic in topic_words:
i += 1
print 'Topic: %d' % i
print([str(word) for word in topic])
i = 0
ftt = open((Paths.final_topics), 'wb')
for topic_prob in topics_matrix:
i += 1
for prob, word in topic_prob:
ftt.write("%d\t%s\t%s\n" % (i, word, prob))
ftt.close()
def showWordCloud():
ttdf = pd.read_csv((Paths.final_topics),sep="\t", skiprows=0, names=["topic_id", "term", "prob"])
topics = ttdf.groupby("topic_id").groups
for topic in topics.keys():
row_ids = topics[topic]
freqs = []
for row_id in row_ids:
row = ttdf.ix[row_id]
freqs.append((row["term"], row["prob"]))
wc = wordcloud.WordCloud()
elements = wc.fit_words(freqs)
plt.figure(figsize=(5, 5), dpi=100)
plt.imshow(wc)
plt.axis("off")
plt.show()
def load_stopwords():
print "Loading Stop Words List"
stopwords = {}
with open(Paths.stopword, 'rU') as f:
for line in f:
stopwords[line.strip()] = 1
return stopwords
def extract_lemmatized_nouns(new_review):
print "Start tagging to get Noun words"
stopwords = load_stopwords()
words = []
sentences = nltk.sent_tokenize(new_review.lower())
for sentence in sentences:
tokens = nltk.word_tokenize(sentence)
text = [word for word in tokens if word not in stopwords]
tagged_text = nltk.pos_tag(text)
for word, tag in tagged_text:
words.append({"word": word, "pos": tag})
lem = WordNetLemmatizer()
nouns = []
for word in words:
if word["pos"] in ["NN", "NNS"]:
nouns.append(lem.lemmatize(word["word"]))
print "Finish POS"
return nouns
def predict(new_topic):
print "Loading model and dictionary"
dictionary = corpora.Dictionary.load(Paths.dictionary)
lda = models.LdaModel.load(Paths.lda_model)
# transform into LDA space
print "Preprocessing new data"
tokens = extract_lemmatized_nouns(new_topic)
new_topic_bow = dictionary.doc2bow(tokens)
new_topic_lda = lda[new_topic_bow]
print(new_topic_lda)
# print the document's single most prominent LDA topic
print(lda.print_topic(max(new_topic_lda, key=lambda item: item[1])[0]))
def loadTestTopic(number_topic):
with open(Paths.reuter_test, 'r') as f:
data = f.read().split('\n')
random.shuffle(data)
return data[:number_topic]
def main():
oper = -1
while int(oper) != 0:
print('**************************************')
print('Choose one of the following: ')
print('1 - PreProcess Data')
print('2 - Build Corpus')
print('3 - Train LDA')
print('4 - Display LDA Topic')
print('5 - Show as Word Cloud')
print('0 - Exit')
print('**************************************')
oper = int(input("Enter your options: "))
if oper == 0:
exit()
elif oper == 1:
preProcess()
elif oper == 2:
buildCorpus()
elif oper == 3:
trainLDA(100)
elif oper == 4:
displayLDA(10, 100)
elif oper == 5:
# test_data = loadTestTopic(2)
# for new_topic in test_data:
# print new_topic
# print "-----------------"
# predict(new_topic)
# print "\n"
showWordCloud()
if __name__ == "__main__":
main()