-
Notifications
You must be signed in to change notification settings - Fork 0
412 lines (178 loc) · 6 KB
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
#!/usr/bin/env python
# coding: utf-8
# In[22]:
print(' SpamHam Project ')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.preprocessing import LabelEncoder
from sklearn import metrics
import seaborn as sn
from sklearn.metrics import confusion_matrix
import re
get_ipython().run_line_magic('matplotlib', 'inline')
from sklearn import model_selection, preprocessing, naive_bayes,metrics
from sklearn.feature_extraction.text import TfidfVectorizer
# In[5]:
df_inputdata = pd.read_csv('/Users/jaswanthjerripothula/Desktop/SpamHam.csv',usecols = [0,1],encoding = 'latin-1')
# In[7]:
df_inputdata.head()
# In[11]:
df_inputdata.rename(columns = {'v1': 'Category','v2': 'Message'}, inplace = True)
# In[12]:
df_inputdata.head()
# In[13]:
df_inputdata.count()
# In[14]:
df_inputdata.groupby('Category').describe()
# In[15]:
df_inputdata.groupby('Category').count()
# In[18]:
category_count = pd.DataFrame()
category_count['count'] = df_inputdata['Category'].value_counts()
# In[19]:
category_count['count']
# In[34]:
fig , ax = plt.subplots(figsize = (12,6))
sn.barplot (x = category_count.index , y = category_count['count'],ax = ax)
ax.set_ylabel ('Count',fontsize = 20)
ax.set_xlabel ('Category',fontsize = 20)
ax.tick_params(labelsize = 20)
# In[33]:
#Looking at the above numbers of hams and spams there are more number of hams than spams
# In[35]:
#Preprocessing Tweets for removing punctuations(! , '), @ , # , https , special characters
def processMessage(tweet):
from string import punctuation
tweet = re.sub(r'\&\w*;','',tweet)
tweet = re.sub('@[^\s]+','',tweet)
tweet = re.sub(r'\$\w*','',tweet)
tweet = tweet.lower()
tweet = re.sub(r'https?:\/\/.*\/\w*','',tweet)
tweet = re.sub(r'#\w*','',tweet)
tweet = re.sub(r'['+punctuation.replace('@','')+']+','',tweet)
tweet = re.sub(r'\b\w{1,2}\b','',tweet)
tweet = re.sub(r'\s\s+',' ',tweet)
tweet = tweet.lstrip(' ')
tweet = ''.join(c for c in tweet if c <= '\uFFFF')
return tweet
# In[37]:
df_inputdata['Message'] = df_inputdata['Message'].apply(processMessage)
# In[38]:
df_inputdata['Message'].head(7)
# In[39]:
df_inputdata['Message'].tail(7)
# In[40]:
df_inputdata['Category'].value_counts()
# In[42]:
#convert the labels from text to numbers
label_encoder = preprocessing.LabelEncoder()
df_inputdata['Category'] = label_encoder.fit_transform(df_inputdata['Category'])
# In[43]:
X = df_inputdata.Message
y = df_inputdata.Category
# In[44]:
df_inputdata['Category'].head(7)
# In[45]:
#Split the dataser into 80% and 20% for training respectively
X_train , X_test , y_train , y_test = train_test_split(X,y,test_size = 0.20)
# In[46]:
type (X_train)
# In[47]:
#convert the raw document into a matrix of TF-IDF features
tfidf_vect = TfidfVectorizer(analyzer = 'word', token_pattern = r'\w{1,}', max_features = 20000)
#Create TF-IDF with X_train
tfidf_vect.fit(X_train)
# In[48]:
#the TF-IDF created with X_train for transforming X_train and X_test
xtrain_tfidf = tfidf_vect.transform(X_train)
xvalid_tfidf = tfidf_vect.transform(X_test)
# In[50]:
#Create a model for NaiveBaye's Model
model = naive_bayes.MultinomialNB()
# In[51]:
#Create a model for NaiveBaye's Model
model = naive_bayes.MultinomialNB()
# In[53]:
#Get the prediction for X_test which is transformed with TF-IDF
y_pred = model.predict(xvalid_tfidf)
# In[57]:
#Get accuracy for the model
metrics.accuracy_score(y_test,y_pred)
# In[63]:
#Get the confusion Matrix
cm = confusion_matrix(y_test,y_pred)
conf_matrix = pd.DataFrame(data = cm , columns = ['Predicted : 0','Predicted : 1'],
index = ['Actual : 0','Actual : 1'])
plt.figure(figsize = (8,5))
sn.heatmap(conf_matrix, annot=True , fmt = 'd', cmap = "YlGnBu")
# In[69]:
#Ham input for testing
myHamData = np.array(["Nah I don't think he goes to usf, he lives around here though"])
#Spam input for testing
mySpamData = np.array(["URGENT! You have won a 1 week FREE membership in our £100,000 Prize Jackpot! Txt the word: CLAIM to No: 81010 T&C www.dbuk.net LCCLTD POBOX 4403LDNW1A7RW18"])
# In[70]:
myHamData = tfidf_vect.transform(myHamData)
# In[101]:
y_result1 = model.predict(myHamData)
# In[102]:
y_result1[0]
# In[103]:
hamvalue = label_encoder.inverse_transform([y_result1[0]])
# In[105]:
hamvalue[0]
# In[121]:
#Spam,Ham
myMultiplesData=["Free entry in 2 a wkly comp to win FA Cup final tkts 21st May 2005. Text FA to 87121 to receive entry question(std txt rate)T&C's apply 08452810075over18's","Had your mobile 11 months or more? U R entitled to Update to the latest colour mobiles with camera for Free! Call The Mobile Update Co FREE on 08002986030",'I HAVE A DATE ON SUNDAY WITH WILL!!']
# In[122]:
df_myMultiplesData=pd.DataFrame(myMultiplesData,columns={'Message'})
# In[123]:
df_myMultiplesData['Message'] = df_myMultiplesData['Message'].apply(processMessage)
# In[124]:
myMultiData = tfidf_vect.transform(df_myMultiplesData['Message'])
# In[125]:
y_predlabels=model.predict(myMultiData)
# In[126]:
y_predlabels.shape
# In[127]:
#y_predlabels=y_prelabels.reshape(-1)
# In[128]:
vals = label_encoder.inverse_transform(y_predlabels)
# In[129]:
for val in vals:
print(val)
# In[130]:
from sklearn.metrics import classification_report
# In[131]:
report = classification_report(y_test,y_pred,labels=[0,1])
# In[132]:
print(report)
# In[133]:
type(report)
# In[134]:
#recall=TP/(TP+FN)
#precision=TP/(TP+FP)
#f1-score = 2*(precision*recall)/(precision+recall)
# In[146]:
TP = cm[0,0]
FN = cm[0,1]
FP = cm[1,0]
TN = cm[1,1]
# In[137]:
recall = TP/(TP+FN)
# In[138]:
recall
# In[141]:
precision = TP/(TP+FP)
# In[142]:
precision
# In[143]:
f1score = 2*(precision*recall)/(precision+recall)
# In[144]:
f1score
# In[145]:
print(' HAMSPAM Project completed successfully ')
# In[ ]: