-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocess.py
237 lines (193 loc) · 7.53 KB
/
process.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
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
import sys
import time
from collections import Counter
import pickle
import itertools
from sklearn.metrics import confusion_matrix
from wordcloud import WordCloud
# Plot method from:
# http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
# python process.py rt
# python process.py fisher
def main():
if len(sys.argv) != 2:
print('Usage: python %s data_folder' % (sys.argv[0]))
exit()
data_folder = sys.argv[1]
global start_time
# load trained dictionaries
positive = {}
negative = {}
with open('pos_' + data_folder + '_train_dict.pkl', 'rb') as f:
positive = pickle.load(f)
with open('neg_' + data_folder + '_train_dict.pkl', 'rb') as f:
negative = pickle.load(f)
with open('pos_'+data_folder+'_train_count.pkl', 'rb') as f:
pos_count = pickle.load(f)
with open('neg_'+data_folder+'_train_count.pkl', 'rb') as f:
neg_count = pickle.load(f)
# print("--- %s seconds --- load " % (time.time() - start_time))
# start_time = time.time()
pos_class_prob = float(pos_count)/(pos_count+neg_count)
neg_class_prob = float(neg_count)/(pos_count+neg_count)
# transform number of occurence to probability with Laplace Smoothing
# total number of words in docs from pos/neg class
positive_sum = 0.0
negative_sum = 0.0
for x in positive:
positive_sum += positive[x]
for x in negative:
negative_sum += negative[x]
# make pos/neg set have the same keys to apply smoothing
diff_pos = set(negative.keys()) - set(positive.keys())
diff_neg = set(positive.keys()) - set(negative.keys())
for x in diff_pos:
positive[x] = 0.0
for x in diff_neg:
negative[x] = 0.0
# total number of unique words
unique_counter = Counter(positive) + Counter(negative)
unique_words = len(unique_counter)
# print ('unique_words',unique_words)
for x in positive:
positive[x] = (positive[x]+1.0) / (positive_sum+unique_words)
for x in negative:
negative[x] = (negative[x]+1.0) / (negative_sum+unique_words)
# print("--- %s seconds --- preprocess " % (time.time() - start_time))
# start_time = time.time()
# print positive
# print negative
total_test_words = 0
total_skip_words = 0
total_count_words = 0
test_count = 0
correct_count = 0
test = []
pred = []
# read training data
with open(data_folder + '_test.txt', 'r') as f:
for i, line in enumerate(f):
test_count+=1
# positive review
if line[:1] == '1':
test.append(1)
test_dict = dict(x.split(':') for x in line[2:].split(' '))
for x in test_dict:
test_dict[x] = int(test_dict[x])
total_test_words+=1
# guess test_dict is pos or neg
pos_prob = np.log(pos_class_prob)
neg_prob = np.log(neg_class_prob)
for x in test_dict:
if (x not in positive) or (x not in negative):
total_skip_words+=1
continue
total_count_words+=1
pos_prob += np.log(positive[x])
neg_prob += np.log(negative[x])
# evaluate correct or not
if pos_prob > neg_prob:
correct_count += 1
pred.append(1)
else:
pred.append(-1)
# negative review
else:
test.append(-1)
test_dict = dict(x.split(':') for x in line[3:].split(' '))
for x in test_dict:
test_dict[x] = int(test_dict[x])
total_test_words+=1
# guess test_dict is pos or neg
pos_prob = np.log(pos_class_prob)
neg_prob = np.log(neg_class_prob)
for x in test_dict:
if (x not in positive) or (x not in negative):
total_skip_words+=1
continue
total_count_words+=1
pos_prob += np.log(positive[x])
neg_prob += np.log(negative[x])
# evaluate correct or not
if neg_prob > pos_prob:
correct_count += 1
pred.append(-1)
else:
pred.append(1)
# print('total_test_words', total_test_words)
# print('total_skip_words', total_skip_words)
# print('total_count_words', total_count_words)
# print("--- %s seconds --- done " % (time.time() - start_time))
# start_time = time.time()
# print 'correct_count', correct_count
# print 'test_count', test_count
print ('accuracy:', 100.0*correct_count/test_count, '%')
print ('class1 top 10 words:')
for l in Counter(positive).most_common(10):
print(l[0], end=' ')
print()
print ('class2 top 10 words:')
for l in Counter(negative).most_common(10):
print(l[0], end=' ')
print()
odds_ratio = {}
for x in positive:
if x in negative:
odds_ratio[x] = positive[x]/negative[x]#max(positive[x]/negative[x], negative[x]/positive[x])
print ('top 10 words regards odds_ratio class1/class2:')
for l in Counter(odds_ratio).most_common(10):
print(l[0], end=' ')
print()
# # print and draw confusion matrix
# class_names = ['class1','class2']
# cnf_matrix = confusion_matrix(test, pred)
# np.set_printoptions(precision=2)
# # Plot non-normalized confusion matrix
# # plt.figure()
# # plot_confusion_matrix(cnf_matrix, classes=class_names,
# # title='Confusion matrix, without normalization')
# # Plot normalized confusion matrix
# plt.figure()
# plot_confusion_matrix(cnf_matrix, classes=class_names, normalize=True,
# title='Normalized confusion matrix '+data_folder)
# plt.savefig('confusion_matrix_'+data_folder+'.png', bbox_inches='tight')
# plt.figure()
# # Read the whole text.
# text = open(data_folder+'_test.txt').read()
# wordcloud = WordCloud().generate(text)
# # Open a plot of the generated image.
# plt.imshow(wordcloud)
# plt.axis("off")
# plt.savefig('wordcloud_'+data_folder+'.png', bbox_inches='tight')
# # plt.show()
if __name__ == '__main__':
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))