-
Notifications
You must be signed in to change notification settings - Fork 7
/
engine.py
186 lines (152 loc) · 4.04 KB
/
engine.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
# Imports
import nltk.classify.util
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import movie_reviews
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import os
import random
import pickle
class SpamDetector:
def createWordFeatures(self,words):
"""
Function
--------
createWordFeatures
Create a dictionary that returns True for each word.
Parameters
----------
words : list
The list of words
Returns
-------
resDict : Dict
Example
-------
createWordFeatures(["the", "MIS 5470", "class", "has", "python", "and","R","modules"])
{'MIS 5470': True,
'R': True,
'and': True,
'class': True,
'has': True,
'modules': True,
'python': True,
'the': True}
"""
resDict = dict( [ (word, True) for word in words] )
return resDict
def tokenizeCreateWordFeatures(self):
"""
Function
--------
tokenizeCreateWordFeatures
Append a "ham" or "spam" at the end of each dictionary created by createWordFeatures function.
This is to tell the algorithm that this text is of type ham or spam.
Merge spam and ham lists.
Shuffle the result to make it randomised.
Returns
-------
mergedList : list
Example
-------
output = tokenizeCreateWordFeatures()
print(output[0])
({'Subject': True, ':': True, 'fw': True, 'nice': True, 'mhoter': True, 'fucking': True,
'top': True, 'of': True, 'the': True, 'morning': True, 'to': True, 'you': True, '!': True,
')': True, 'matayaa': True}, 'spam')
"""
data_directory = "data"
hamList = []
spamList = []
for directories, subdirs, files in os.walk(data_directory):
if (os.path.split(directories)[1] == 'ham'):
for fileName in files:
with open(os.path.join(directories, fileName), encoding="latin-1") as f:
message = f.read()
words = word_tokenize(message)
hamList.append((self.createWordFeatures(words), "ham"))
if (os.path.split(directories)[1] == 'spam'):
for fileName in files:
with open(os.path.join(directories, fileName), encoding="latin-1") as f:
message = f.read()
words = word_tokenize(message)
spamList.append((self.createWordFeatures(words), "spam"))
mergedList = hamList + spamList
random.shuffle(mergedList)
return mergedList
def createTestTrain(self):
"""
Function
--------
createTestTrain
Create test/train splits.
Returns
-------
(trainingData, testData) : tuple
"""
mergedList = self.tokenizeCreateWordFeatures()
trainingPart = int(len(mergedList) * .6)
trainingData = mergedList[:trainingPart]
testData = mergedList[trainingPart:]
return (trainingData, testData)
def createModel(self):
"""
Function
--------
createModel
Create the naive Bayes classifier
Returns
-------
classifier : nltk.classify.naivebayes.NaiveBayesClassifier
"""
trainingData, testData = self.createTestTrain()
classifier = NaiveBayesClassifier.train(trainingData)
return classifier
def saveModel(self):
"""
Function
--------
saveModel
Save the model to disk
Returns
-------
outputMsg : str
Example
-------
saveModel()
'Model saved successfully !'
"""
classifier = self.createModel()
fileName = 'nb_model.sav'
outputMsg = ""
try:
pickle.dump(classifier, open(fileName, 'wb'))
outputMsg = "Model saved successfully !"
except:
outputMsg = "Error when saving model !"
return outputMsg
def predictMessage(self,msg):
"""
Function
--------
predictMessage
Classify the message by telling if it is a ham or spam.
Parameters
----------
msg : str
A message we want to classify
Returns
-------
str: 'ham' or 'spam'
Example
-------
message = "Hi welcome to this session, please log in using your username and password then click on the start button."
predictMessage(message)
'ham'
"""
fileName = 'nb_model.sav'
loaded_model = pickle.load(open(fileName, 'rb'))
output_msg = ""
words = word_tokenize(msg)
output_msg = dict( [ (word, True) for word in words] )
return loaded_model.classify(output_msg)