-
Notifications
You must be signed in to change notification settings - Fork 0
/
CS180MP3_THR_Lee.py
353 lines (316 loc) · 11.4 KB
/
CS180MP3_THR_Lee.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
########################################
# Spam Filtering using Naive Bayes #
# #
# LEE, Kristine-Clair #
# CS180 #
########################################
import sys
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
import string
from bs4 import BeautifulSoup
import os, os.path
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.svm import SVC, NuSVC, LinearSVC
from sklearn.metrics import accuracy_score, precision_score,f1_score
import numpy as np
import csv
np.set_printoptions(threshold=np.nan)
words = set(nltk.corpus.words.words())
stopWords = set(stopwords.words('english'))
ps = PorterStemmer()
###########################################################################
# Traverse through all the preprocessed files to stem the words inside it #
# preprocessed/ --- directory where all the preprocessed emails are #
# located #
###########################################################################
def stemEmails():
fileList = []
fileDir = "preprocessed/"
for filename in os.listdir(fileDir):
fileList.append(os.path.join(fileDir, filename))
for filePath in fileList:
newList = []
with open(filePath, "r") as textFile:
for line in textFile:
words = word_tokenize(line)
for word in words:
newList.append(ps.stem(word))
with open(filePath, "w") as outFile:
for i in range(len(newList)):
outFile.write(newList[i] + " ")
##################################################################
# Traverse through all the words in the dictionary and stem them #
##################################################################
def stemDictionary():
newList = []
with open("dictionary.txt", "r") as textFile:
for line in textFile:
words = word_tokenize(line)
for word in words:
newList.append(ps.stem(word))
with open("stemDictionary.txt", "w") as outFile:
for i in range(len(newList)):
outFile.write(newList[i])
outFile.write("\n")
################################################
# Remove common stop words from the dictionary #
################################################
def removeStopWords():
filteredWords = []
with open("dictionary.txt", "r") as dictionaryText:
for line in dictionaryText:
if line.rstrip() not in stopWords:
filteredWords.append(line.rstrip())
with open("removedStopWordsDictionary.txt", "w") as filteredText:
for word in filteredWords:
filteredText.write(word)
filteredText.write("\n")
#####################################################################
# Create a CSV file for easier access of the labels of the test set #
#####################################################################
def getLabelsTest():
testList = []
testDir = "test/"
for testName in os.listdir(testDir):
testList.append(os.path.join(testDir, testName))
count = 0
labelsMatrix = np.zeros(len(testList))
labelsDir = "testLabels.txt"
with open(labelsDir, "r") as labels:
for count, line in enumerate(labels):
words = line.split()
check = words[0]
email = words[1].split("../data/")
email = email[1]
if check == 'ham':
labelsMatrix[count] = 1
else:
labelsMatrix[count] = 0
csvFile = open("dataset-test-labels.csv", "w", newline='')
writer = csv.writer(csvFile)
writer.writerow(labelsMatrix.astype(int))
return labelsMatrix
############################################################
# Create a CSV file of the feature vector for the test set #
############################################################
def getFeaturesMatrixTest(dictionary):
testList = []
testDir = "test/"
for testName in os.listdir(testDir):
testList.append(os.path.join(testDir, testName))
featuresMatrix = np.zeros((len(testList), len(dictionary)))
for testIndex, testFile in enumerate(testList):
with open(testFile, "r") as textTest:
#print(trainIndex, trainFile)
for line in textTest:
#print(trainIndex, line)
words = line.split()
#print(words)
for wordIndex, word in enumerate(dictionary):
#print(wordIndex, word)
featuresMatrix[testIndex, wordIndex] = words.count(word)
csvFile = open("dataset-test.csv", "w", newline='')
writer = csv.writer(csvFile)
for index in range(len(testList)):
writer.writerow(featuresMatrix[index].astype(int))
return featuresMatrix
######################################################################
# Create a CSV file for easier access of the labels of the train set #
######################################################################
def getLabels():
trainList = []
trainDir = "train/"
for trainName in os.listdir(trainDir):
trainList.append(os.path.join(trainDir, trainName))
count = 0
labelsMatrix = np.zeros(len(trainList))
labelsDir = "trainLabels.txt"
with open(labelsDir, "r") as labels:
for count, line in enumerate(labels):
#print(line)
words = line.split()
check = words[0]
email = words[1].split("../data/")
email = email[1]
#print(check)
if check == 'ham':
#print("check: ", check)
labelsMatrix[count] = 1
else:
labelsMatrix[count] = 0
#print(labelsMatrix)
#print(len(trainList))
csvFile = open("dataset-training-labels.csv", "w", newline='')
writer = csv.writer(csvFile)
writer.writerow(labelsMatrix.astype(int))
return labelsMatrix
#############################################################
# Create a CSV file of the feature vector for the train set #
#############################################################
def getFeaturesMatrix(dictionary):
#print(len(dictionary))
trainList = []
trainDir = "train/"
for trainName in os.listdir(trainDir):
trainList.append(os.path.join(trainDir, trainName))
featuresMatrix = np.zeros((len(trainList), len(dictionary)))
for trainIndex, trainFile in enumerate(trainList):
with open(trainFile, "r") as textTrain:
#print(trainIndex, trainFile)
for line in textTrain:
#print(trainIndex, line)
words = line.split()
#print(words)
for wordIndex, word in enumerate(dictionary):
#print(wordIndex, word)
featuresMatrix[trainIndex, wordIndex] = words.count(word)
#print(featuresMatrix)
csvFile = open("dataset-training.csv", "w", newline='')
writer = csv.writer(csvFile)
for index in range(len(trainList)):
#listMatrix = list(featuresMatrix[index].astype(int))
#print(listMatrix)
#writer.writerow(listMatrix[index])
writer.writerow(featuresMatrix[index].astype(int))
#print(featuresMatrix.shape)
#new = np.array_split(featuresMatrix, 2)
#print(new[0].shape)
return featuresMatrix
###################################################################################
# Preprocess the original email files by removing the header, html tags, symbols, #
# and non-English words #
###################################################################################
def getMail(filename):
text = " "
with open(filename, "r", errors="ignore") as mailFile:
for line in mailFile:
if line == "\n":
for line in mailFile:
text += line
message = ""
soup = BeautifulSoup(text, "html.parser")
message = soup.get_text()
#print(message)
message = message.lower()
#print(message)
message = message.translate(str.maketrans("","", string.digits))
#print(message)
message = message.translate(str.maketrans("","", string.punctuation))
#print(message)
plain = " ".join(w for w in nltk.wordpunct_tokenize(message) if w.lower() in words or w.isalpha())
#print(plain)
#outFile = open("output.txt", "w")
#outFile.write(plain)
outname = ((filename.split("."))[1])
outputname = "outmail.{}".format(outname)
outFile = open(outputname,"w", errors="ignore")
outFile.write(plain)
def main():
#################################
# Possible values for i: #
# 1: getMail() : preprocessing #
# 2: generate dictionary.txt #
# 3: getFeaturesMatrix() #
# getFeaturesMatrixTest() #
# getLabels() #
# getLabelsTest() #
# : feature vectors & labels #
# 4: Naive Bayes Models #
# 5: removeStopWords() #
# 6: stemDictionary() #
# 7: stemEmails() #
#################################
i = 4
if i == 1:
fileList = []
fileDir = "data/"
for filename in os.listdir(fileDir):
fileList.append(os.path.join(fileDir, filename))
#print(fileList)
for filePath in fileList:
inputname = filePath
getMail(inputname)
elif i == 2:
fileList = []
fileDir = "preprocessed/"
for filename in os.listdir(fileDir):
fileList.append(os.path.join(fileDir, filename))
with open("dictionary.txt", "w") as outFile:
for filePath in fileList:
with open(filePath, "r") as textFile:
for line in textFile:
data = line.split(" ")
for i in data:
outFile.write(i)
outFile.write("\n")
textList = []
newList = []
with open("dictionary.txt", "r") as textFile:
for line in textFile:
textList.append(line)
uWords = set(textList)
for i in range(len(textList)):
if textList[i].isalpha():
newList.append(textList[i])
with open("dictionary.txt", "w") as outFile:
for i in range(len(newList)):
outFile.write(newList[i])
outFile.write("\n")
with open("dictionary.txt", "r") as textFile:
lines = textFile.readLines()
lines.sort()
with open("dictionary.txt", "w") as outFile:
for i in lines:
outFile.write(i)
elif i == 3:
dictionary = []
with open("dictionary.txt", "r") as dicionaryText:
for line in dicionaryText:
word = line.split()
dictionary += word
trainFeatures = getFeaturesMatrix(dictionary)
testFeatures = getFeaturesMatrixTest(dictionary)
trainLabels = getLabels()
testLabels = getLabelsTest()
elif i == 4:
aClass = np.array([0,1])
datasetTrain = np.genfromtxt("dataset-training.csv", dtype=np.int, delimiter=",",)
datasetTest = np.genfromtxt("dataset-test.csv", dtype=np.int, delimiter=",")
datasetTrainLabels = np.genfromtxt("dataset-training-labels.csv", dtype=np.int, delimiter=",")
datasetTestLabels = np.genfromtxt("dataset-test-labels.csv", dtype=np.int, delimiter=",")
modelM = MultinomialNB(alpha=1)
modelB = BernoulliNB(alpha=1)
splitTrain = datasetTrain.shape[0]//2
newTrainFeatures0, newTrainFeatures1 = datasetTrain[:splitTrain,:], datasetTrain[splitTrain:,:]
newTrainLabels0 = datasetTrainLabels[0:splitTrain]
newTrainLabels1 = datasetTrainLabels[splitTrain:]
modelM.partial_fit(newTrainFeatures0, newTrainLabels0, classes=aClass)
modelM.partial_fit(newTrainFeatures1, newTrainLabels1, classes=aClass)
modelB.partial_fit(newTrainFeatures0, newTrainLabels0, classes=aClass)
modelB.partial_fit(newTrainFeatures1, newTrainLabels1, classes=aClass)
#modelM.fit(datasetTrain, datasetTrainLabels)
#modelB.fit(datasetTrain, datasetTrainLabels)
predictionsM = modelM.predict(datasetTest)
predictionsM1 = modelM.predict(datasetTrain)
predictionsB = modelB.predict(datasetTest)
predictionsB1 = modelB.predict(datasetTrain)
modelAccuracyM = accuracy_score(datasetTestLabels, predictionsM)
modelAccuracyM1 = accuracy_score(datasetTrainLabels, predictionsM1)
modelAccuracyB = accuracy_score(datasetTestLabels, predictionsB)
modelAccuracyB1 = accuracy_score(datasetTrainLabels, predictionsB1)
print("Multinomial Naive Bayes (Test):\t", modelAccuracyM)
print("Multinomial Naive Bayes (Train):\t", modelAccuracyM1)
print("Bernoulli Naive Bayes (Test):\t", modelAccuracyB)
print("Bernoulli Naive Bayes (Train):\t", modelAccuracyB1)
elif i == 5:
removeStopWords()
elif i == 6:
stemDictionary()
elif i == 7:
stemEmails()
if __name__ == "__main__":
main()