-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnaive_bayes.py
246 lines (202 loc) · 7.96 KB
/
naive_bayes.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
import os
import nltk
from nltk import *
from nltk.corpus import wordnet as wn
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt
def parse_amazon_data(file_path):
'''
This function parses amazon data. It retrieves the reviews and good/bad label.
:param file_path: path to traing/testing files
-./data/test.ft.txt
-./data/train.ft.txt
:return: a tuple consisting of
1. a list of reviews (a list of strings)
2. a list of good/bad labels (stored as ints. 0 = bad, 1 = good)
'''
stopwords_set = set(stopwords.words('english'))
lemmatizer = WordNetLemmatizer().lemmatize
review_str_list = []
labels_list = []
with open(file_path, 'r') as f:
words = []
for line in f:
label_str, review_str = line.split(' ', 1)
label = int(label_str[-1]) - 1 # original data is labeled with 1 and 2. change to labels of 0 and 1
# words = [lemmatizer(w) for w in review_str.lower().split() if w not in stopwords_set] # get the words out
review_str_list.append(review_str_list.lower())
# Not too sure what the best DS is here but gonna store everything in list for now
# review_str_list.append(words)
labels_list.append(label)
return (review_str_list, labels_list)
def parse_amazon_data_count_matrix(file_path, count_vect, training):
'''
This function parses amazon data. It retrieves the reviews and good/bad label.
:param file_path: file_path: path to traing/testing files
-./data/test.ft.txt
-./data/train.ft.txt
:param count_vect: vectorizer
:param training: 1 if training data
0 if testing data
:return:
a sparse matrix w/ each row being a document and coluumn being a word
'''
review_str_list = []
labels_list = []
with open(file_path, 'r') as f:
words = []
for line in f:
label_str, review_str = line.split(' ', 1)
label = int(label_str[-1]) - 1 # original data is labeled with 1 and 2. change to labels of 0 and 1
words = review_str
# Not too sure what the best DS is here but gonna store everything in list for now
review_str_list.append(words)
labels_list.append(label)
if training:
X_counts = count_vect.fit_transform(review_str_list)
else:
X_counts = count_vect.transform(review_str_list)
return (X_counts, labels_list)
def parse_imdb_data(file_path):
'''
:param file_path: file_path: path to training/testing files
-./data/aclImdb/train
-./data/aclImdb/test
:return: a tuple consisting of
1. a list of reviews (a list of strings)
2. a list of good/bad labels (stored as ints. 0 = bad, 1 = good)
'''
stopwords_set = set(stopwords.words('english'))
lemmatizer = WordNetLemmatizer().lemmatize
review_str_list = []
labels_list = []
for folder_name in os.listdir(file_path):
if folder_name == "pos":
label = 1
elif folder_name == "neg":
label = 0
else:
# We are not interested in these data!!
continue
for file_name in os.listdir(file_path + "/" + folder_name):
with open(file_path + "/" + folder_name + "/" + file_name, 'r', errors='ignore') as f:
words = []
for line in f:
words += [lemmatizer(w) for w in line.lower().split() if w not in stopwords_set]
review_str_list.append(words)
labels_list.append(label)
return (review_str_list, labels_list)
def parse_imdb_data_count_matrix(file_path, count_vect, training):
'''
:param file_path: path to training/testing files
-./data/aclImdb/train
-./data/aclImdb/test
:param count_vect: vectorizer
:param training: 1 if training data
0 if testing data
:return:
a sparse matrix w/ each row being a document and coluumn being a word
'''
review_str_list = []
labels_list = []
for folder_name in os.listdir(file_path):
if folder_name == "pos":
label = 1
elif folder_name == "neg":
label = 0
else:
# We are not interested in these data!!
continue
for file_name in os.listdir(file_path + "/" + folder_name):
with open(file_path + "/" + folder_name + "/" + file_name, 'r', errors='ignore') as f:
words = ""
for line in f:
words += " " + line
review_str_list.append(words)
labels_list.append(label)
if training:
X_counts = count_vect.fit_transform(review_str_list)
else:
X_counts = count_vect.transform(review_str_list)
return (X_counts, labels_list)
def naive_bayes(x, y):
nb = MultinomialNB()
nb = nb.fit(x, y)
return nb
def run_naive_bayes(x_train, y_train, amazon_test_x, amazon_test_y, imdb_test_x, imdb_test_y):
x = []
amazon_testing_score = []
imdb_testing_score = []
for i in range(100000, x_train.shape[0], 100000):
x.append(i)
nb = naive_bayes(x_train[:i], y_train[:i])
amazon_pred_label = nb.predict(amazon_test_x)
amazon_score = metrics.accuracy_score(amazon_pred_label, amazon_test_y)
amazon_testing_score.append(amazon_score)
imdb_pred_label = nb.predict(imdb_test_x)
imdb_score = metrics.accuracy_score(imdb_pred_label, imdb_test_y)
imdb_testing_score.append(imdb_score)
x = np.array(x)
amazon_testing_score = np.array(amazon_testing_score)
imdb_testing_score = np.array(imdb_testing_score)
plt.plot(x, amazon_testing_score)
plt.plot(x, imdb_testing_score)
plt.legend(['Amazon testing accuracy', 'IMDB testing accuracy'], loc='upper left')
plt.title('Amazon vs. IMDB testing accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Training data size')
plt.show()
if __name__ == "__main__":
training_amazon = "./data/train.ft.txt"
testing_amazon = "./data/test.ft.txt"
training_imdb = "./data/aclImdb/train"
testing_imdb = "./data/aclImdb/test"
# train on amazon -> test on imdb
print("train on amazon, test on imdb")
# uncomment to run naive bayes
count_vect = CountVectorizer(stop_words='english')
amazon_training_x, amazon_training_y = parse_amazon_data_count_matrix(training_amazon, count_vect, 1)
print("loaded amazon training data")
amazon_testing_x, amazon_testing_y = parse_amazon_data_count_matrix(testing_amazon, count_vect, 0)
print("loaded amazon testing data")
imdb_testing_x, imdb_testing_y = parse_imdb_data_count_matrix(testing_imdb, count_vect, 0)
print("loaded imdb testing data")
run_naive_bayes(amazon_training_x, amazon_training_y, amazon_testing_x, amazon_testing_y, imdb_testing_x, imdb_testing_y)
nb1 = naive_bayes(amazon_training_x, amazon_training_y)
print("classifier trained")
amazon_pred_label1 = nb1.predict(amazon_testing_x)
print("amazon predictions made")
amazon_score1 = metrics.accuracy_score(amazon_pred_label1, amazon_testing_y)
print("amazon score = " + str(amazon_score1))
imdb_pred_label1 = nb1.predict(imdb_testing_x)
print("imdb predictions made")
imdb_score1 = metrics.accuracy_score(imdb_pred_label1, imdb_testing_y)
print("imdb score = " + str(imdb_score1))
#####################################################################################################
# train on imdb -> test on amazon
print("train on imdb, test on amazon")
# uncomment to run naive bayes
count_vect = CountVectorizer(stop_words='english')
imdb_training_x, imdb_training_y = parse_imdb_data_count_matrix(training_imdb, count_vect, 1)
print("loaded imdb training data")
imdb_testing_x, imdb_testing_y = parse_imdb_data_count_matrix(testing_imdb, count_vect, 0)
print("loaded imdb testing data")
amazon_testing_x, amazon_testing_y = parse_amazon_data_count_matrix(testing_amazon, count_vect, 0)
print("loaded amazon testing data")
run_naive_bayes(imdb_training_x, imdb_training_y, amazon_testing_x, amazon_testing_y, imdb_testing_x,
imdb_testing_y)
nb2 = naive_bayes(imdb_training_x, imdb_training_y)
print("classifier trained")
imdb_pred_label2 = nb2.predict(imdb_testing_x)
print("imdb predictions made")
imdb_score2 = metrics.accuracy_score(imdb_pred_label2, imdb_testing_y)
print("imdb score = " + str(imdb_score2))
amazon_pred_label2 = nb2.predict(amazon_testing_x)
print("amazon predictions made")
amazon_score2 = metrics.accuracy_score(amazon_pred_label2, amazon_testing_y)
print("amazon score = " + str(amazon_score2))