-
Notifications
You must be signed in to change notification settings - Fork 0
/
sms_spam_classification.py
292 lines (203 loc) · 8.66 KB
/
sms_spam_classification.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
# -*- coding: utf-8 -*-
"""SMS Spam Classification.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1blKT1BS3kssTrx5AUtRVoHAYB91LlR48
**Context**
The SMS Spam Collection is a set of SMS tagged messages that have been collected for SMS Spam research.
It contains one set of SMS messages in English of 5,574 messages, tagged acording being ham (legitimate) or spam.
**Objective**
To classify the messages as Spam or Ham using NLP.
<h1>Importing Libraries</h1>
"""
import pandas as pd
import numpy as np
import nltk
nltk.download("stopwords")
"""<h1>Loading Data</h1>"""
data = pd.read_csv('spam.csv', encoding='Latin-1')
data.head()
data = data.drop(['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4'], axis=1)
data.head()
data.rename(columns= {"v1":"label", "v2":"message"}, inplace=True)
data.head()
"""<h1>Handling Categorical Data</h1>"""
data = pd.get_dummies(data, columns=['label'])
data.head()
data['label_ham'].value_counts()
data.info()
data['count'] = 0
for i in np.arange(0, len(data.message)):
data.loc[i, 'count'] = len(data.loc[i, 'message'])
data.head()
data.describe()
"""<h1>Processing Message</h1>"""
data['message'][0]
"""**Preparing Word Vector Corpus**"""
corpus = []
"""**Using Porter Stemmer**"""
from nltk.stem.porter import PorterStemmer
import re
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import CountVectorizer
ps = PorterStemmer()
for i in range(0, 5572):
#regular expressions
msg = data['message'][i]
#deal with email addresses
msg = re.sub('\b[\w\-.]+?@\w+?\.\w{2,4}\b', 'emailaddr', data['message'][i])
#urls
msg = re.sub('(http[s]?\S+)|(\w+\.[A-Za-z]{2,4}\S*)', 'httpaddr', data['message'][i])
#money symbols
msg = re.sub('([A-Z]{3}|[A-Z]?[\$€¥])?\s?(\d{1,3}((,\d{1,3})+)?(.\d{1,3})?(.\d{1,3})?(,\d{1,3})?)', 'moneysymb', data['message'][i])
#phone numbers
msg = re.sub('\b(\+\d{1,2}\s)?\d?[\-(.]?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}\b', 'phonenumbr', data['message'][i])
#numbers
msg = re.sub('\d+(\.\d+)?', 'numbr', data['message'][i])
#Removing punctuations
msg = re.sub('[^\w\d\s]', ' ', data['message'][i])
if i==0:
print("\t\t\t\t Message", i)
if i==0:
print("\n After Regular Expression - Message ", i, " : ", msg)
#Each Word to lowercase
msg = msg.lower()
if i==0:
print("\n Lower case Message ", i, " : ", msg)
#Splitting words
msg = msg.split()
if i==0:
print("\n After Splitting Message ", i, " : ", msg)
#Stemming with PorterStemmer handling Stop Words
msg = [ps.stem(word) for word in msg if not word in set(stopwords.words('english'))]
if i==0:
print("\n After Stemming Message ", i, " : ", msg)
# preparing Messages with Remaining Tokens
msg = ' '.join(msg)
if i==0:
print("\n Final Prepared Message ", i, " : ", msg, "\n\n")
# Preparing WordVector Corpus
corpus.append(msg)
"""<h1>Preparing Vectors for Each Message</h1>"""
cv = CountVectorizer()
cv
#converting messages to numeric form
data_input = cv.fit_transform(corpus).toarray()
data_input[0]
data_input
data_input.shape
"""<h1>Applying Classification</h1>
>
* **Input: Prepared Sparse Matrix/Vectors for Each Message**
* **Output: Label i.e. Spam or Ham**
"""
data.head()
data_output = data['label_ham']
data_output.value_counts()
"""**Data Splitting**"""
from sklearn.model_selection import train_test_split
train_x, test_x, train_y, test_y = train_test_split(data_input, data_output, test_size=0.20, random_state=0)
"""<h1>ML Model</h1>"""
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn import tree
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
"""**Training**"""
nvb = GaussianNB()
nvb.fit(train_x, train_y)
dec = tree.DecisionTreeClassifier()
dec.fit(train_x, train_y)
# rf = RandomForestClassifier(n_estimators=200)
# rf.fit(train_x, train_y)
"""**Predictions**"""
pred_nvb = nvb.predict(test_x)
pred_dec = dec.predict(test_x)
print ("Accuracy : %0.5f \n\n" % accuracy_score(test_y, pred_nvb))
print (classification_report(test_y, pred_nvb))
print ("Accuracy : %0.5f \n\n" % accuracy_score(test_y, pred_dec))
print (classification_report(test_y, pred_dec))
# print ("Accuracy : %0.5f \n\n" % accuracy_score(test_y, pred_rf))
# print (classification_report(test_y, pred_rf))
"""<h1>Final Accuracy</h1>
>
* **Random Forest : 97.220%**
* **Decision Tree : 97.040%**
* **GaussianNB : 87.085%**
<h1>Hyperparameter Tuning for Random Forest</h1>
"""
from sklearn.model_selection import GridSearchCV
params = {
'bootstrap': [True, False],
'max_depth': [4, 6, 8, 10, 12, 16, None],
'max_features': ['auto', 'sqrt'],
'n_estimators': [100, 200, 300, 400, 500, 600],
}
random_rf = GridSearchCV(estimator = rf, param_grid = params, cv = 3, verbose=2, n_jobs = -1)
random_rf.fit(train_x, train_y)
rf = RandomForestClassifier(bootstrap=True, ccp_alpha=0.0,
class_weight=None,
criterion='gini', max_depth=None,
max_features='auto',
max_leaf_nodes=None,
max_samples=None,
min_impurity_decrease=0.0,
min_impurity_split=None,
min_samples_leaf=1,
min_samples_split=2,
min_weight_fraction_leaf=0.0,
n_estimators=200, n_jobs=None,
oob_score=False,
random_state=None, verbose=0,
warm_start=False)
rf.fit(train_x, train_y)
pred_rf = rf.predict(test_x)
print ("Accuracy : %0.5f \n\n" % accuracy_score(test_y, pred_rf))
print (classification_report(test_y, pred_rf))
"""Accuracy increased by:
**0.089%**
<h1> KFold Cross validation</h1>
"""
from sklearn.model_selection import KFold
kfold = KFold(n_splits=5, random_state=0, shuffle=False)
# preparing a fresh random forest
rf1 = RandomForestClassifier(bootstrap=True, ccp_alpha=0.0,
class_weight=None,
criterion='gini', max_depth=None,
max_features='auto',
max_leaf_nodes=None,
max_samples=None,
min_impurity_decrease=0.0,
min_impurity_split=None,
min_samples_leaf=1,
min_samples_split=2,
min_weight_fraction_leaf=0.0,
n_estimators=200, n_jobs=None,
oob_score=False,
random_state=None, verbose=0,
warm_start=False)
accuracy = []
for train_index,test_index in kfold.split(data_input):
xtrain,xtest = data_input[train_index], data_input[test_index]
ytrain,ytest = data_output[train_index], data_output[test_index]
rf1 = RandomForestClassifier(bootstrap=True, ccp_alpha=0.0,
class_weight=None,
criterion='gini', max_depth=None,
max_features='auto',
max_leaf_nodes=None,
max_samples=None,
min_impurity_decrease=0.0,
min_impurity_split=None,
min_samples_leaf=1,
min_samples_split=2,
min_weight_fraction_leaf=0.0,
n_estimators=200, n_jobs=None,
oob_score=False,
random_state=None, verbose=0,
warm_start=False)
rf1.fit(xtrain, ytrain)
prediction = rf1.predict(xtest)
accuracy.append(accuracy_score(ytest, prediction))
accuracy
np.mean(accuracy)
"""*Maximum Accuracy Score:* **97.541%**"""