-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain_a5.py
557 lines (415 loc) · 19.8 KB
/
main_a5.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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
"""
UserWarning: The twython library has not been installed.
Some functionality from the twitter package will not be available.
This warning is due to various version of Python.
"""
import nltk
import os
import sys
import time
import joblib
import numpy as np
import nltk.sentiment
from nltk.text import Text
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import sentiwordnet as swn
from nltk.corpus import movie_reviews
#from sklearn.externals import joblib
from sklearn.naive_bayes import MultinomialNB
from sklearn.tree import DecisionTreeClassifier
def mpqa_decode(path):
"""
decode MPQA Subjectivity lexicon data file as a dict
input: the path of dataset
output: apqa dict {word:(neg or pos)}
"""
mpqa = {}
fr = open(path,"r")
lines = fr.readlines()
for line in lines:
mpqa[line.split()[2].split('=')[1]] = line.split()[-1].split('=')[1][:3]
fr.close()
return mpqa
class Vocabulary():
"""
class to store the information of our dataset's vocabulary
the vocabulary is build from our dataset without stopwords
also used to findout the pos of word
"""
def __init__(self, tokens_list):
# building a reference dict for finding pos of word
self.words_reference = {}
# build a vocabulary set
self.words = set()
for index, tokens in enumerate(tokens_list):
for token in tokens.words_list:
self.words.add(token)
# change set to list, used to count the pos of words
self.words = list(self.words)
for index, word in enumerate(self.words):
self.words_reference[word] = index
self.size = len(self.words_reference.keys())
def __str__(self):
return f'<Vocabulary size=this voc contain {self.size} words>'
def __len__(self):
return self.size
def __getitem__(self, index):
return self.words[index]
def pos(self, word):
return self.words_reference[word]
def reset_vocabulary_by_stopwordlist(self):
new_words = set()
self.words_reference = {}
for word in self.words:
if word not in STOPLIST:
new_words.add(word)
new_words = list(new_words)
for index, word in enumerate(new_words):
self.words_reference[word] = index
self.words = new_words
self.size = len(self.words_reference.keys())
def reset_vocabulary_by_sentiwordnet(self):
"""
reset vocabulary by sentiwordnet
"""
self.words_reference = {}
new_words = set()
for word in self.words:
senti_score = list(swn.senti_synsets(word, 'a'))
# reset our vocabulary by words' senti score
# check word is in senti dataset first
if senti_score and (senti_score[0].pos_score()>0.5 or senti_score[0].neg_score()>0.5):
new_words.add(word)
new_words = list(new_words)
for index, word in enumerate(new_words):
self.words_reference[word] = index
self.words = new_words
self.size = len(self.words_reference.keys())
def sentiwordnet_encode(self):
"""
using sentiwordnet pos and neg score to encode vocabulary
return the encode array
"""
# we only consider the highest score and donesn't care about its pos or neg
words_encode = np.zeros([len(self.words)], dtype = "float32")
for index, word in enumerate(self.words):
senti_score = list(swn.senti_synsets(word, 'a'))
if senti_score:
words_encode[index] = max(senti_score[0].pos_score(), senti_score[0].neg_score())
return words_encode
def reset_vocabulary_by_english_vocabulary(self):
new_words = set()
self.words_reference = {}
for word in self.words:
if word in ENGLISH_VOCABULARY:
new_words.add(word)
new_words = list(new_words)
for index, word in enumerate(new_words):
self.words_reference[word] = index
self.words = new_words
self.size = len(self.words_reference.keys())
def reset_vocabulary_by_MPQA(self):
new_words = set()
self.words_reference = {}
for word in self.words:
if word in MPQA_VOCABULARY:
new_words.add(word)
new_words = list(new_words)
for index, word in enumerate(new_words):
self.words_reference[word] = index
self.words = new_words
self.size = len(self.words_reference.keys())
class Tokens():
"""
class to store the tokens from text file
take file path as input
"""
def __init__(self, path, readed = False):
if not readed:
with open(path) as fr:
self.words_list = fr.read().split()
else:
self.words_list = path.split()
self.size = len(self.words_list)
self.name = path.split('/')[-1]
def __str__(self):
return f"<Tokens size={self.size} name={self.name}>"
def __len__(self):
return self.size
def negation_mark(self):
#reset tokens_list with negation
#like --> like_NEG
self.words_list = nltk.sentiment.util.mark_negation(self.words_list)
def frequence(self, vocabulary):
# build a np array for frequence features
# note: int8 is not enough for this dataset, when vaule more than 127 it will cause neg value
frequence_array = np.zeros([len(vocabulary)], dtype='int16')
join_set = set(self.words_list) & set(vocabulary.words)
for token in self.words_list:
# only count the words in vocabulary
if token in join_set:
index = vocabulary.pos(token)
frequence_array[index] += 1
return frequence_array
def binary(self, vocabulary):
# build a np array for binary features
binary_array = np.zeros([len(vocabulary)], dtype='int16')
join_set = set(self.words_list) & set(vocabulary.words)
for token in join_set:
index = vocabulary.pos(token)
binary_array[index] = 1
return binary_array
def most_frequent_token(self, vocabulary):
# return the first most frequent words in vocabulary
# return the frequence of the most frequent word
frequence_array = self.frequence(vocabulary)
most_frequent_index = np.argmax(frequence_array)
token_frequence = np.max(frequence_array)
return vocabulary.words[most_frequent_index], token_frequence
def dataset_builder(tokens_list, vocabulary, frequence = True):
dataset_array = np.zeros([2000, len(vocabulary)], dtype='int16')
if frequence:
for index, tokens in enumerate(tokens_list):
dataset_array[index] = tokens.frequence(vocabulary)
else:
for index, tokens in enumerate(tokens_list):
dataset_array[index] = tokens.binary(vocabulary)
return dataset_array
def train_test_split(dataset_array, labels, test_size=0.2):
rand_list = list(range(2000))
np.random.shuffle(rand_list)
split_number = int(test_size*2000)
test_X = dataset_array[rand_list[:split_number]]
test_Y = labels[rand_list[:split_number]]
train_X = dataset_array[rand_list[split_number:]]
train_Y = labels[rand_list[split_number:]]
return train_X, train_Y, test_X, test_Y
def model_save_info_print(model_type, train_auc, test_auc, file_path, model, elapsed):
os.makedirs(os.path.dirname(file_path), exist_ok=True)
joblib.dump(model, file_path)
print(f'Creating {model_type} in {file_path}')
print(f' Elapsed time: {elapsed}s')
print(f' TRAIN Accuracy: {train_auc}')
print(f' TEST Accuracy: {test_auc}')
print('#########################################################')
print('#########################################################')
def nb_model(train_X, train_Y, test_X, test_Y):
'''
train and test a nb model
return the model, running time and train test auc
'''
start = time.clock()
model = MultinomialNB()
model.fit(train_X, train_Y)
y_train_pred = model.predict(train_X)
y_test_pred = model.predict(test_X)
train_auc = (train_Y == y_train_pred).sum()/train_X.shape[0]
test_auc = (test_Y == y_test_pred).sum()/test_X.shape[0]
elapsed = (time.clock() - start)
return model, train_auc, test_auc, elapsed
def tree_model(train_X, train_Y, test_X, test_Y):
start = time.clock()
model = DecisionTreeClassifier(random_state=0, max_depth=8)
model.fit(train_X, train_Y)
y_train_pred = model.predict(train_X)
y_test_pred = model.predict(test_X)
train_auc = (train_Y == y_train_pred).sum()/train_X.shape[0]
test_auc = (test_Y == y_test_pred).sum()/test_X.shape[0]
elapsed = (time.clock() - start)
return model, train_auc, test_auc, elapsed
def menu():
print('Choose a model')
print('1 - all words raw counts')
print('2 - all words binary')
print('3 - SentiWordNet words')
print('4 - Subjectivity Lexicon words')
print('5 - all words plus Negation')
# NLTK stoplist with 3136 words
STOPLIST = set(nltk.corpus.stopwords.words())
# Vocabulary with 234,377 English words from NLTK
ENGLISH_VOCABULARY = set(w.lower() for w in nltk.corpus.words.words())
# about 8000 words associated with parts of speech and a subjectivity score.
MPQA_VOCABULARY = mpqa_decode('data/subjectivity_clues_hltemnlp05/subjclueslen1-HLTEMNLP05.tff')
def main():
"""
the main func
"""
length = len(sys.argv)
# Using the raw data, because I implemented all basic functions myself
# it is better for me to use raw data
documents = [(movie_reviews.raw(fileid), category)
for category in movie_reviews.categories()
for fileid in movie_reviews.fileids(category)]
if length == 2:
# data list
tokens_list = []
# the label list of data
labels = []
for document in documents:
tokens = Tokens(document[0], True)
tokens_list.append(tokens)
labels.append(document[1])
## The first NB model
## The most basic one with all words
print('The first NB model with all words and words frequence')
# build the basic vocabulary set for our data
vocabulary = Vocabulary(tokens_list)
# get features from tokens_list
dataset_array = dataset_builder(tokens_list, vocabulary, True)
labels = np.array(labels)
train_X, train_Y, test_X, test_Y = train_test_split(dataset_array, labels, test_size=0.1)
model, train_auc, test_auc, elapsed = nb_model(train_X, train_Y, test_X, test_Y)
# saving model and print result
model_save_info_print('Bayes classifier', train_auc, test_auc, 'classifiers/bayes-all-words.jbl', model, elapsed)
## The first tree model
print('The first Tree model with all words and words frequence')
print('Using the same training set and testing set for the tree model')
model, train_auc, test_auc, elapsed = tree_model(train_X, train_Y, test_X, test_Y)
# saving model and print result
model_save_info_print('Decision tree classifier', train_auc, test_auc, 'classifiers/decision-tree-all-words.jbl', model, elapsed)
## The second NB model
## words only from sentiwordnet which pos and neg score more than 0.5
print('The second NB model with words in sentiwordnet and binary features')
print("update vocabulary dataset")
vocabulary.reset_vocabulary_by_sentiwordnet()
dataset_array = dataset_builder(tokens_list, vocabulary, False)
train_X, train_Y, test_X, test_Y = train_test_split(dataset_array, labels, test_size=0.1)
model, train_auc, test_auc, elapsed = nb_model(train_X, train_Y, test_X, test_Y)
# saving model and print result
model_save_info_print('Bayes classifier', train_auc, test_auc, 'classifiers/bayes-sentiwordnet-words.jbl', model, elapsed)
## The second tree model
print('The second Tree model with words in sentiwordnet and words frequence')
model, train_auc, test_auc, elapsed = tree_model(train_X, train_Y, test_X, test_Y)
# saving model and print result
model_save_info_print('Decision tree classifier', train_auc, test_auc, 'classifiers/decision-tree-sentiwordnet-words.jbl', model, elapsed)
## The third NB model
## All words with binary features
print('The third NB model with all words and binary features')
# build the basic vocabulary set for our data
vocabulary = Vocabulary(tokens_list)
dataset_array = dataset_builder(tokens_list, vocabulary, False)
train_X, train_Y, test_X, test_Y = train_test_split(dataset_array, labels, test_size=0.1)
model, train_auc, test_auc, elapsed = nb_model(train_X, train_Y, test_X, test_Y)
# saving model and print result
model_save_info_print('Bayes classifier', train_auc, test_auc, 'classifiers/bayes-all-words-binary.jbl', model, elapsed)
## The third tree model
print('The third Tree model with all words and binary features')
model, train_auc, test_auc, elapsed = tree_model(train_X, train_Y, test_X, test_Y)
# saving model and print result
model_save_info_print('Decision tree classifier', train_auc, test_auc, 'classifiers/decision-tree-all-words-binary.jbl', model, elapsed)
## The fourth NB model
## Words from MPQA dataset
print('The fourth NB model with MPQA dataset and binary features')
vocabulary.reset_vocabulary_by_MPQA()
dataset_array = dataset_builder(tokens_list, vocabulary, False)
train_X, train_Y, test_X, test_Y = train_test_split(dataset_array, labels, test_size=0.1)
model, train_auc, test_auc, elapsed = nb_model(train_X, train_Y, test_X, test_Y)
# saving model and print result
model_save_info_print('Bayes classifier', train_auc, test_auc, 'classifiers/bayes-MPQA.jbl', model, elapsed)
## The fourth tree model
print('The fourth Tree model with MPQA dataset and binary features')
model, train_auc, test_auc, elapsed = tree_model(train_X, train_Y, test_X, test_Y)
# saving model and print result
model_save_info_print('Decision tree classifier', train_auc, test_auc, 'classifiers/decision-tree-MPQA.jbl', model, elapsed)
## The fiveth NB model
## All words with negation 'don't like it. -> don't like_NEG it_NEG'
print('The fiveth model, All words with negation')
print('rebuild an dataset which consider negation words')
# data list
tokens_list = []
# the label list of data
labels = []
for document in documents:
tokens = Tokens(document[0], True)
tokens.negation_mark()
tokens_list.append(tokens)
labels.append(document[1])
vocabulary = Vocabulary(tokens_list)
dataset_array = dataset_builder(tokens_list, vocabulary, False)
labels = np.array(labels)
train_X, train_Y, test_X, test_Y = train_test_split(dataset_array, labels, test_size=0.1)
model, train_auc, test_auc, elapsed = nb_model(train_X, train_Y, test_X, test_Y)
# saving model and print result
model_save_info_print('Bayes classifier', train_auc, test_auc, 'classifiers/bayes-all-words-negition-binary.jbl', model, elapsed)
## The fiveth tree model
print('The fiveth Tree model with all words with negation')
model, train_auc, test_auc, elapsed = tree_model(train_X, train_Y, test_X, test_Y)
# saving model and print result
model_save_info_print('Decision tree classifier', train_auc, test_auc, 'classifiers/decision-tree-all-words-negition-binary.jbl', model, elapsed)
elif length == 4:
model_name = sys.argv[2]
filename = sys.argv[3]
menu()
number = input("Type a number:")
# data list
tokens_list = []
for document in documents:
tokens = Tokens(document[0], True)
if number == '5':
tokens.negation_mark()
tokens_list.append(tokens)
vocabulary = Vocabulary(tokens_list)
if model_name == 'bayes' or model_name == 'tree':
if number == '1':
dataset_array = np.zeros([1, len(vocabulary)], dtype='int16')
if model_name == 'bayes':
model = joblib.load('classifiers/bayes-all-words.jbl')
if model_name == 'tree':
model = joblib.load('classifiers/decision-tree-all-words.jbl')
tokens = Tokens(filename, False)
token_array = tokens.frequence(vocabulary)
dataset_array[0] = token_array
print(model.predict(dataset_array)[0])
elif number == '2':
dataset_array = np.zeros([1, len(vocabulary)], dtype='int16')
if model_name == 'bayes':
model = joblib.load('classifiers/bayes-all-words-binary.jbl')
if model_name == 'tree':
model = joblib.load('classifiers/decision-tree-all-words-binary.jbl')
tokens = Tokens(filename, False)
token_array = tokens.binary(vocabulary)
dataset_array[0] = token_array
print(model.predict(dataset_array)[0])
elif number == '3':
vocabulary.reset_vocabulary_by_sentiwordnet()
dataset_array = np.zeros([1, len(vocabulary)], dtype='int16')
if model_name == 'bayes':
model = joblib.load('classifiers/bayes-sentiwordnet-words.jbl')
if model_name == 'tree':
model = joblib.load('classifiers/decision-tree-sentiwordnet-words.jbl')
tokens = Tokens(filename, False)
token_array = tokens.binary(vocabulary)
dataset_array[0] = token_array
print(model.predict(dataset_array)[0])
elif number == '4':
vocabulary.reset_vocabulary_by_MPQA()
dataset_array = np.zeros([1, len(vocabulary)], dtype='int16')
if model_name == 'bayes':
model = joblib.load('classifiers/bayes-MPQA.jbl')
if model_name == 'tree':
model = joblib.load('classifiers/decision-tree-MPQA.jbl')
tokens = Tokens(filename, False)
token_array = tokens.binary(vocabulary)
dataset_array[0] = token_array
print(model.predict(dataset_array)[0])
elif number == '5':
dataset_array = np.zeros([1, len(vocabulary)], dtype='int16')
if model_name == 'bayes':
model = joblib.load('classifiers/bayes-all-words-negition-binary.jbl')
if model_name == 'tree':
model = joblib.load('classifiers/decision-tree-all-words-negition-binary.jbl')
tokens = Tokens(filename, False)
tokens.negation_mark()
token_array = tokens.binary(vocabulary)
dataset_array[0] = token_array
print(model.predict(dataset_array)[0])
else:
print("number out of range")
else:
print('Please select bayes or tree')
else:
print("Running example: ")
print("for training : python3 main_a5.py --train ")
print("for text testing : python3 main_a5.py --run 'bayes'|'tree' <filename>")
if __name__ == "__main__":
main()