-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCombined.py
433 lines (347 loc) · 14.9 KB
/
Combined.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
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
# coding: utf-8
# imports:
import time;
import urllib.request
import csv
import os
import itertools
import logging
import json
import numpy as np
import gensim
from bs4 import BeautifulSoup
from urllib.parse import urlencode
from gensim.utils import smart_open, simple_preprocess
from gensim.corpora.wikicorpus import _extract_pages, filter_wiki
from gensim.parsing.preprocessing import STOPWORDS
from xml.etree.cElementTree import iterparse
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn import neighbors
from sklearn import svm
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO)
logging.root.level = logging.INFO
id2word_wiki=gensim.corpora.Dictionary()
# List Categories:
#category_list = ["Mathematics","Technology","Music"]
category_list = ["Mathematics","Technology","Music","History","Geography","Arts","Health","Nature","Religion","Literature"]
#category_list = ["1977 introductions", "Language" ,"Arts", "Asia", "Asthma", "Automobiles", "BRICS nation", "Belief", "Climate", "Crime", "Culture", "Dance", "Deserts", "Dolls", "Earth", "Engines", "Fishing", "Folklore", "Games", "Geography", "Glass", "Government agencies", "Health", "History", "Humans", "Hygiene", "India", "Industry", "Internet", "Law", "Life", "Literature", "Mathematics", "Matter", "Millionaires", "Music", "Nature", "Nothing", "Parties", "Peace", "Politics", "Religion", "Sexology", "Society", "Songs", "Space", "Technology", "Television", "Transport", "Water sports"]
test_folder = "./test/"
root_folder = "./Simplex/"
list.sort(category_list)
folder_name=''.join([x[0]+x[1]+x[2] for x in category_list])
root_folder='./'+folder_name+'/'
print("Checking folder : "+folder_name)
if not os.path.exists(root_folder):
os.mkdir(root_folder)
wiki_bow_path = root_folder+'wiki_bow.mm'
wiki_dict_path = root_folder+'wiki_dict.dict'
# Download Page Ids:
#https://petscan.wmflabs.org/?language=en&project=wikipedia&depth=1&format=csv&categories=mathematics&doit=Do it!
print ("Scanning CSV")
for cat in category_list:
if not os.path.exists(root_folder+cat+".csv"):
url="https://petscan.wmflabs.org/?language=en&project=wikipedia&depth=1&format=csv&doit=Do%20it!&categories="+cat
urllib.request.urlretrieve(url, root_folder+cat+".csv")
print("Downloading ",cat+".csv")
# CSV to XML Download data:
def get_data(ids,output_file):
url="https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&pageids="+ids
req = urllib.request.urlopen(url)
if req.getcode() == 200:
soup = BeautifulSoup(req.read(), 'html.parser')
s = soup.find_all('page')
for si in s:
output_file.write(str(si))
def batch_train(file):
output_file = open(file.replace(".csv",".xml"), 'a', encoding="utf8")
output_file.write("<pages>")
csvReader = csv.reader(open(file,'r'))
totalRecords = sum(1 for row in csv.reader(open(file,'r',encoding="UTF-8")) )
print (file.replace(".csv",".xml"),totalRecords)
start = 0
end = start + 50
while (start <= totalRecords):
pageIds = ""
for row in itertools.islice(csv.reader(open(file,'r',encoding="UTF-8")),start,end):
pageIds = pageIds + row[2] + "|"
get_data(pageIds,output_file)
start = end + 1
end = start + 50
if end> totalRecords:
end=totalRecords
output_file.write("</pages>")
for path, subdirs, files in os.walk(root_folder):
for file in files:
if file.endswith('.csv'):
if not os.path.exists(root_folder+file.replace(".csv",".xml")):
print("Downloading ",root_folder+file.replace(".csv",".xml"))
batch_train(path + file)
print ("Done downloading")
# Train Model
def head(stream, n=10):
"""Convenience fnc: return the first `n` elements of the stream, as plain list."""
return list(itertools.islice(stream, n))
def my_extract_pages(f):
elems = (elem for _, elem in iterparse(f, events=("end",)))
page_tag = "rev"
for elem in elems:
if elem.tag == page_tag and elem.text != None:
text = elem.text
yield text
elem.clear()
def tokenize(text):
return [token for token in simple_preprocess(text) if token not in STOPWORDS]
def iter_wiki(dump_file):
for text in my_extract_pages(smart_open(dump_file)):
text = filter_wiki(text)
tokens = tokenize(text)
if len(tokens) < 50:
continue # ignore short articles and various meta-articles
yield tokens
print("Training Model")
class WikiCorpus(object):
def __init__(self, dump_file, dictionary, clip_docs=None):
"""
Parse the first `clip_docs` Wikipedia documents from file `dump_file`.
Yield each document in turn, as a list of tokens (unicode strings).
"""
self.dump_file = dump_file
self.dictionary = dictionary
self.clip_docs = clip_docs
def __iter__(self):
for tokens in itertools.islice(iter_wiki(self.dump_file), self.clip_docs):
yield self.dictionary.doc2bow(tokens)
def __len__(self):
return self.clip_docs
if not (os.path.exists(wiki_bow_path) and os.path.exists(wiki_dict_path)):
for path, subdirs, files in os.walk(root_folder):
del subdirs[:]
for file in files:
if file.endswith('.xml'):
doc_path = path + file
stream = iter_wiki(doc_path)
doc_stream = (tokens for tokens in iter_wiki(doc_path))
id2word_wiki.merge_with(gensim.corpora.Dictionary(doc_stream))
id2word_wiki.filter_extremes(no_below=10, no_above=0.1)
# create a stream of bag-of-words vectors
wiki_corpus = WikiCorpus(doc_path, id2word_wiki)
id2word_wiki.save(wiki_dict_path)
gensim.corpora.MmCorpus.serialize(wiki_bow_path, wiki_corpus)
id2word_wiki = gensim.corpora.Dictionary.load(wiki_dict_path)
mm_corpus = gensim.corpora.MmCorpus(wiki_bow_path)
clipped_corpus = gensim.utils.ClippedCorpus(mm_corpus, 8000)
lda_model = gensim.models.LdaModel(clipped_corpus, num_topics=len(category_list), id2word=id2word_wiki, passes=10, alpha='asymmetric')
print("done")
tfidf_model = gensim.models.TfidfModel(mm_corpus, id2word=id2word_wiki)
lsi_model = lsi_model = gensim.models.LsiModel(tfidf_model[mm_corpus], id2word=id2word_wiki, num_topics=len(category_list))
print("done")
def calculate_centroid(topic_docs):
test_doc = [tokens for tokens in iter_wiki(topic_docs)]
part = [lda_model[id2word_wiki.doc2bow(tokens)] for tokens in test_doc]
topic_dic={}
for i in range(len(category_list)):
topic_dic[i]=0
for doc in part:
for p in doc:
topic_dic[p[0]] += p[1]
centroid = [(x, topic_dic[x]/len(part)) for x in range(len(category_list))]
return centroid
print("Calcuating centroid")
centroids_dict={}
for path, subdirs, files in os.walk(root_folder):
del subdirs[:]
for file in files:
if file.endswith('.xml'):
doc_path = path + file
centroid = calculate_centroid(doc_path)
centroids_dict[file.replace(".xml","")]=centroid
print("Centroid calculation done")
km=None
def get_values(l):
g=[0]*len(category_list)
for i in l:
g[i[0]]=i[1]
return g
def calculate_kmeans(part):
km = KMeans(n_clusters=len(category_list), init='k-means++', max_iter=500, n_init=1)
km.fit(part)
return km
print("Calculating KMeans ")
for path, subdirs, files in os.walk(root_folder):
del subdirs[:]
part=[]
for file in files:
if file.endswith('.xml'):
doc_path = path + file
test_doc = [tokens for tokens in iter_wiki(doc_path)]
part+=[get_values(lda_model[id2word_wiki.doc2bow(tokens)]) for tokens in test_doc]
km = calculate_kmeans(part)
y=[]
X=[]
for path, subdirs, files in os.walk(root_folder):
del subdirs[:]
for file in files:
if file.endswith('.xml'):
doc_path = path + file
topic = file.replace(".xml","")
test_doc = [tokens for tokens in iter_wiki(doc_path)]
X+=[get_values(lda_model[id2word_wiki.doc2bow(tokens)]) for tokens in test_doc]
y+=[category_list.index(topic)]*len(test_doc)
print("Feeding data to KNeighborsClassifier")
n_neighbors = 15
# we create an instance of Neighbours Classifier and fit the data.
clf = neighbors.KNeighborsClassifier(n_neighbors, weights='distance')
clf.fit(X, y)
print("Feeding data to SVC")
C = 1.0 # SVM regularization parameter
svc = svm.SVC(kernel='linear', C=C).fit(X, y)
rbf_svc = svm.SVC(kernel='rbf', gamma=0.7, C=C).fit(X, y)
poly_svc = svm.SVC(kernel='poly', degree=3, C=C).fit(X, y)
lin_svc = svm.LinearSVC(C=C).fit(X, y)
def draw_graph(x_label,y,file,text_data,topic):
x = np.arange(len(x_label)) # the x locations for the groups
width = 0.1 # the width of the bars
fig, ax = plt.subplots()
fig.set_figheight(6)
fig.set_figwidth(8)
rects = ax.bar(x, y, width, color='blue')
ax.set_ylabel('Probabilities')
ax.set_xlabel('Categories')
ax.set_title('Topic Distribution of: ' + topic)
ax.title.set_position([.5, 1.2])
ax.set_ylim([0,1])
def autolabel(rects):
"""
Attach a text label above each bar displaying its height
"""
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() - rect.get_width()*2, 1.05 * height,round(height,2))
autolabel(rects)
plt.tight_layout(pad=6)
plt.xticks(x,category_list,rotation=90)
plt.savefig(file.replace(".xml","_")+str(len(category_list))+'.png')
plt.close('all')
# Test LDA - Cosine
model_name="LDA-Cosine"
if not os.path.exists(root_folder+model_name):
os.mkdir(root_folder+model_name)
def get_part(testFile):
test_doc = [tokens for tokens in iter_wiki(testFile)]
part = [lda_model[id2word_wiki.doc2bow(tokens)] for tokens in test_doc]
return part
results=""
print("Testing results")
for path, subdirs, files in os.walk(test_folder):
for file in files:
if file.endswith('.xml'):
doc_path = test_folder + file
path=get_part(doc_path)
results+=file.replace(".xml","")+"\n\n"
graph_data=[]
text_data=""
for topic in category_list:
cos_dis=np.mean([gensim.matutils.cossim(p1, p2) for p1, p2 in zip([centroids_dict[topic]], path)])
text_data +=topic+":"+str(cos_dis)+"\n"
graph_data.append(np.mean([gensim.matutils.cossim(p1, p2) for p1, p2 in zip([centroids_dict[topic]], path)]))
results+=text_data+"\n\n\n\n"
draw_graph(list(centroids_dict.keys()),graph_data,root_folder+model_name+'/'+file,text_data,file)
output_file = open(root_folder+model_name+"/"+model_name+str(len(category_list))+".txt", 'w', encoding="utf8")
output_file.write(results)
output_file.close()
print(" Done ")
# Test LDA- KMeans
model_name="LDA-KMeans"
if not os.path.exists(root_folder+model_name):
os.mkdir(root_folder+model_name)
def get_part(testFile):
test_doc = [tokens for tokens in iter_wiki(testFile)]
part = [get_values(lda_model[id2word_wiki.doc2bow(tokens)]) for tokens in test_doc]
return part
results=""
print("Testing results")
for path, subdirs, files in os.walk(test_folder):
for file in files:
if file.endswith('.xml'):
doc_path = test_folder + file
results+=file.replace(".xml","")+": "
part=get_part(doc_path)
results+=category_list[km.predict(part)[0]]
results += "\n\n"
output_file = open(root_folder+model_name+"/"+model_name+str(len(category_list))+".txt", 'w', encoding="utf8")
output_file.write(results)
output_file.close()
print(" Done ")
#Test LDA _ KNN
model_name="LDA-KNN"
if not os.path.exists(root_folder+model_name):
os.mkdir(root_folder+model_name)
def get_part(testFile):
test_doc = [tokens for tokens in iter_wiki(testFile)]
part = [get_values(lda_model[id2word_wiki.doc2bow(tokens)]) for tokens in test_doc]
return part
results=""
print("Testing results")
for path, subdirs, files in os.walk(test_folder):
for file in files:
if file.endswith('.xml'):
doc_path = test_folder + file
results+=file.replace(".xml","")+": "
part=get_part(doc_path)
results+=category_list[clf.predict(part)[0]]
results += "\n\n"
output_file = open(root_folder+model_name+"/"+model_name+str(len(category_list))+".txt", 'w', encoding="utf8")
output_file.write(results)
output_file.close()
print(" Done ")
#LDA Linear Classifier
model_name="LDA-Linear Classifier"
if not os.path.exists(root_folder+model_name):
os.mkdir(root_folder+model_name)
print("Testing results")
for path, subdirs, files in os.walk(test_folder):
for file in files:
if file.endswith('.xml'):
doc_path = test_folder + file
results+=file.replace(".xml","")+": "
part=get_part(doc_path)
for i, clf in enumerate((svc, lin_svc, rbf_svc, poly_svc)):
#print(category_list[clf.predict(part)[0]])
results+=category_list[clf.predict(part)[0]]
results += "\n\n"
output_file = open(root_folder+model_name+"/"+model_name+str(len(category_list))+".txt", 'w', encoding="utf8")
output_file.write(results)
output_file.close()
print(" Done ")
model_name="LSI-Cosine"
if not os.path.exists(root_folder+model_name):
os.mkdir(root_folder+model_name)
# Test
def get_part(testFile):
test_doc = [tokens for tokens in iter_wiki(testFile)]
part = [lsi_model[id2word_wiki.doc2bow(tokens)] for tokens in test_doc]
return part
results=""
print("Testing results")
for path, subdirs, files in os.walk(test_folder):
for file in files:
if file.endswith('.xml'):
doc_path = test_folder + file
path=get_part(doc_path)
results+=file.replace(".xml","")+"\n\n"
graph_data=[]
text_data=""
graph_topic=[]
for topic in category_list:
cos_dis=np.mean([gensim.matutils.cossim(p1, p2) for p1, p2 in zip([centroids_dict[topic]], path)])
text_data += topic+":"+str(cos_dis)+"\n"
if(np.mean([gensim.matutils.cossim(p1, p2) for p1, p2 in zip([centroids_dict[topic]], path)])>0):
graph_data.append(np.mean([gensim.matutils.cossim(p1, p2) for p1, p2 in zip([centroids_dict[topic]], path)]))
graph_topic.append(topic)
results+=text_data+"\n\n\n\n"
draw_graph(graph_topic,graph_data,root_folder+model_name+'/'+file,text_data,file)
output_file = open(root_folder+model_name+"/"+model_name+str(len(category_list))+".txt", 'w', encoding="utf8")
output_file.write(results)
output_file.close()
print(" Done ")