-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapatne2NB.py
353 lines (216 loc) · 7.33 KB
/
apatne2NB.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
## Naive Bayes classifier for Tweet classification
# coding: utf-8
# In[1]:
import numpy as np
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn import svm
from sklearn.feature_extraction.text import TfidfVectorizer
import re
import unicodedata as ud
from sklearn.metrics import precision_recall_fscore_support as prfs
import csv
import HTMLParser
from sklearn.metrics import classification_report
from sklearn.cross_validation import cross_val_score
from numpy import random
from nltk.stem.porter import PorterStemmer as porterStemmer
from itertools import izip
import collections
from sklearn.naive_bayes import BernoulliNB
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
# In[2]:
def cleanTweet(originalTweet):
htmlParser = HTMLParser.HTMLParser()
tweet = originalTweet
#tweet = htmlParser.unescape(originalTweet);
#tweet = tweet.decode('windows-1252').encode('ascii', 'ignore')
#tweet = tweet.decode('windows-1252')
#tweet = tweet.decode("utf8").encode('ascii', 'ignore')
#tweet = re.sub(r'[^\x00-\xFF]+', r'', tweet)
#tweet = re.sub(r'[^\x00-\x7F]+', r'', tweet)
#tweet = tweet.decode('utf-8').strip()
#tweet = tweet.decode('unicode_escape').encode('ascii','ignore')
#tweet = tweet.encode('ascii','ignore')
tweet = ''.join([i if ord(i) < 128 else ' ' for i in tweet])
# remove URLs in tweet
tweet = re.sub(r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*', '', tweet)
# remove strings starting with @ in tweet
tweet = re.sub(r'(\s)@\w+', r'', tweet)
tweet = re.sub(r'@\w+', r'', tweet)
# remove HTML tags from tweet
tweet = re.sub('<[^<]+?>', '', tweet)
# separates words joined with capital words.
# E.g. DisplayIsAweson to Display Is Awesom
#tweet = " ".join(re.findall('[A-Z][^A-Z]*', tweet));
# remove exclamations
tweet = re.sub(r'[<>!#@$:.,%\?-]+', r'', tweet)
# remove extra white spaces
tweet = re.sub(r'\s+', r' ', tweet)
# stemming
stemmer = porterStemmer()
stemmedTweet = [stemmer.stem(word) for word in tweet.split(" ")]
stemmedTweet = " ".join(stemmedTweet)
tweet = str(stemmedTweet)
tweet = tweet.replace("'", "")
return tweet
# In[3]:
trainData = pd.read_csv("A:\\new_Sync\\Box Sync\\academics\\sem3\\491\\assignments\\hw4\\data\\train2Columns.csv")
# In[4]:
testData = pd.read_csv("A:\\new_Sync\\Box Sync\\academics\\sem3\\491\\assignments\\hw4\\data\\test2Columns.csv")
# In[5]:
trainData.shape
#data.head(2)
# In[6]:
rawTweetsSeries = trainData['tweets'];
tweetLabels = trainData['class'];
# In[7]:
rawTestTweetsSeries = testData['tweets'];
testTweetLabels = testData['class'];
# In[8]:
rawTestTweetsList = rawTestTweetsSeries.tolist()
testTweetLabelList = testTweetLabels.tolist()
# In[9]:
rawTweetsList = rawTweetsSeries.tolist()
tweetLabelList = tweetLabels.tolist()
# In[10]:
print (len(rawTweetsList))
print (rawTweetsList[0])
print (len(rawTestTweetsList))
print (rawTestTweetsList[0])
# In[11]:
randomTweets = random.choice(rawTweetsList, 3)
print (randomTweets)
randomTestTweets = random.choice(rawTestTweetsList, 3)
print (randomTestTweets)
# In[12]:
i = 0;
cleanedTweetsList = []
for tweet in rawTweetsList:
#tweet.encode('utf-8').strip()
#tweet = tweet.decode("utf8").encode('ascii', 'ignore')
#print (i ,),
cleanedTweet = cleanTweet(tweet).encode('ascii', 'ignore').strip();
cleanedTweetsList.append(cleanedTweet);
i += 1
# In[13]:
j = 0;
cleanedTestTweetsList = []
for tweet in rawTestTweetsList:
cleanedTestTweet = cleanTweet(tweet).encode('ascii', 'ignore').strip();
cleanedTestTweetsList.append(cleanedTestTweet);
j += 1
# In[14]:
randomTweets = random.choice(cleanedTweetsList, 3)
print (randomTweets)
randomTestTweets = random.choice(cleanedTestTweetsList, 3)
print (randomTestTweets)
# In[15]:
# Create feature vectors
vectorizer = TfidfVectorizer(min_df=0.000125,
max_df = 0.75,
sublinear_tf=True,
use_idf=True)
# In[16]:
nbClassifier = BernoulliNB()
# In[17]:
trainVectors = vectorizer.fit_transform(cleanedTweetsList)
trainVectors.shape
# In[18]:
testVectors = vectorizer.transform(cleanedTestTweetsList)
testVectors.shape
# In[19]:
nbClassifier.fit(trainVectors, tweetLabelList)
# In[20]:
predictedLabels = nbClassifier.predict(testVectors)
# In[21]:
predictedLabelList = predictedLabels.tolist()
# In[22]:
classActual = np.array(testTweetLabels)
classPredicted = np.array(predictedLabelList)
# In[23]:
#prfs(classActual, classPredicted)
# In[24]:
target_names = ['0', '1']
# In[25]:
print(classification_report(testTweetLabels, predictedLabelList, target_names=target_names))
# In[26]:
print("Confusion matrix")
print (confusion_matrix(testTweetLabels, predictedLabels))
# In[27]:
counter=collections.Counter(testTweetLabels)
print("Actual values: "),
print (counter)
# In[28]:
counter=collections.Counter(predictedLabels)
print("Actual values: "),
print(counter)
# In[29]:
testAccuracy = nbClassifier.score(testVectors, testTweetLabels)
print ("Test accuracy:"),
print (testAccuracy)
# In[30]:
trainAccuracy = nbClassifier.score(trainVectors, tweetLabels)
print ("Train accuracy:"),
print (trainAccuracy)
# In[31]:
cvScores = cross_val_score(nbClassifier, trainVectors, tweetLabelList, cv=10)
print ("Cross validation scores:"),
print (cvScores)
print ("Mean: ", cvScores.mean())
print ("Minimum: ", cvScores.min())
print ("Maximum: ", cvScores.max())
# In[32]:
xAxis = [x for x in range(1,13)]
yAxis = cvScores.tolist()
yAxis.extend([trainAccuracy, testAccuracy])
# In[33]:
plt.plot(xAxis, yAxis, marker='o', linestyle='--', color='r')
plt.xlabel("Cross validation round number")
plt.ylabel("Accuracy")
plt.title("Naive Bayes Accuracy for 10 fold Cross Validation")
plt.text(7, .795, "11=train, 12=test")
plt.show()
# In[34]:
# Question 10
# In[35]:
predictionProbabilities = nbClassifier.predict_proba(testVectors)
zeroProbs = predictionProbabilities[:, 1]
oneProbs = predictionProbabilities[:, 0]
topFiveOne = oneProbs.argsort()[-5:][::-1]
# In[36]:
print ("Correctly classified probabilities:")
print ("------------------------------------------------------------------------------")
print ("tweetid \t tweet \t actual label \t predited label \t prediction probability");
print ("------------------------------------------------------------------------------")
for x in topFiveOne:
print (x),
print (rawTestTweetsList[x]),
print (testTweetLabelList[x]),
print (predictedLabelList[x])
print (predictionProbabilities[x][0])
# In[37]:
# Question 7
# In[38]:
featureNames = vectorizer.get_feature_names()
coefficientArray = nbClassifier.coef_[0]
top20Features = coefficientArray.argsort()[-20:][::-1]
# In[39]:
print ("Top 20 features:")
for x in top20Features:
print (featureNames[x]),
# In[40]:
# Question 7
# In[41]:
#fpr, tpr, thresholds = metrics.roc_curve(y, scores, pos_label=2)
fpr, tpr, thresholds = metrics.roc_curve(testTweetLabelList, predictedLabelList)
roc_auc = auc(fpr, tpr)
# In[42]:
plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plt.title("ROC Curve for Naive Bayes")
plt.show()