-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSentiment_analysis_python_notebook.py
More file actions
1987 lines (1340 loc) · 72 KB
/
Sentiment_analysis_python_notebook.py
File metadata and controls
1987 lines (1340 loc) · 72 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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
# In[1]:
get_ipython().system('pip install bs4')
get_ipython().system('pip install nltk')
get_ipython().system('pip install fuzzywuzzy')
get_ipython().system('pip install wordcloud')
get_ipython().system('pip install xgboost')
get_ipython().system('pip install gensim')
# In[2]:
import pandas as pd
import numpy as np
import re
from bs4 import BeautifulSoup
from nltk.stem import PorterStemmer
from nltk.tokenize import RegexpTokenizer
import string
from sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
from statistics import mean
from nltk.stem import WordNetLemmatizer
import nltk
from scipy.sparse import hstack
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import LabelEncoder
from wordcloud import WordCloud
from matplotlib import pyplot as plt
import xgboost as xgb
from sklearn.metrics import precision_score, recall_score, accuracy_score
from fuzzywuzzy import fuzz
import matplotlib as mpl
import seaborn as sns
from gensim.models import word2vec
# Custom settings to view all column names and their data in the output
pd.set_option('display.max_columns', None)
pd.set_option('display.max_colwidth', -1)
nltk.download('wordnet')
# In[3]:
#repr(string)
# In[4]:
data = pd.read_csv('generic_tweets.txt', sep = "," )
# In[5]:
data['class'].value_counts(dropna = False)
# Replacing 4 with 1 for convenient working
# In[6]:
data['class'].replace(4,1, inplace = True)
# In[7]:
data['query'].value_counts(dropna = False)
# In[8]:
#Since query column consists of only 'No_QUERY', removing it from data
data.drop('query', axis = 1, inplace = True)
# In[9]:
data.head()
# ## Text processing of tweets for further working
#
# Removal of stop words:
# The goal of stop words is to remove unnecessary words (reduces storage complexities) but the available lists of stop words, the one from the NLTK library for instance,it has words that potentially convey negative sentiments such as: not, don’t, hasn’t…. but for sentiment analysis problem we want to keep negative words.
#
# From the file stop_words.txt, removing negative sentiment words
# In[10]:
stop_words = pd.read_csv('stop_words.txt', names = ['stop words'])
stop_words_list = stop_words.iloc[:,0].tolist()
words_to_remove = ['cannot', "can't", 'arent', "didn't", "doesn't", "don't", "hasn't", "haven't", "no", "not", "shouldn't",
"wasnt", "werent", "wouldnt"]
for word in words_to_remove:
stop_words_list.remove(word)
# In[11]:
#removing html tags and attributes
def remove_html_tags(input_text):
output_text = BeautifulSoup(input_text).get_text()
return output_text
# removal of URLS, hashtags, usernames and mentions beacuse they do not weigh in sentiment analysis
def remove_urls_hash_tags(input_text):
output_text = re.sub('@[A-Z0-9a-z]+|#[A-Z0-9a-z]+|http\S+', ' ', input_text)
return output_text
#replacing emoticons with 'positive' (positive emotion) and 'negative' (negative emotion)
happy_emo = [':-)', ':)', ';)', ':o)', ':]', ':3', ':c)', ':>', '=]', '8)', '=)', ':}',
':^)', ':-D', ':D', ';D', '8-D', '8D', 'x-D', 'xD', 'X-D', 'XD', '=-D', '=D',
'=-3', '=3', ':-))', ":'-)", ":')", ':*', ':^*', '>:P', ':-P', ':P', 'X-P',
'x-p', 'xp', 'XP', ':-p', ':p', '=p', ':-b', ':b', '>:)', '>;)', '>:-)', '<3']
sad_emo = [':L', ':-/', '>:/', ':S', '>:[', ':@', ':-(', ':[', ':-||', '=L', ':<',
':-[', ':-<', '=\\', '=/', '>:(', ':(', '>.<', ":'-(", ":'(", ':\\', ':-c',
':c', ':{', '>:\\', ';(']
def replace_emoticons(input_text):
words = input_text.split()
output_text = ''
for word in words:
count = 0
for pos_emo in happy_emo:
if word == pos_emo:
output_text = output_text + ' '+ 'posemo' #posemo in place of happy emoticon
count +=1
for neg_emo in sad_emo:
if word == neg_emo:
output_text = output_text + ' '+ 'negemo' #negemo in place of sad emotion
count +=1
if count == 0:
output_text = output_text + ' ' + word
return output_text
def preprocess_text(input_text):
output_text = ' '
sentence = remove_urls_hash_tags(input_text) #urls, hashtags, mentions &tags
sentence = replace_emoticons(sentence) #replace emoticons
#convert to lower case (words like GOOD and good should be considered same)
lower_case = sentence.lower() #lowercase
lower_case = re.sub('\.|\,|\?|\!|-|_','', lower_case)
#punctuations add noise and do not contribute to the sentiments
punctuation_removal = lower_case.translate(str.maketrans('', '', string.punctuation))
split_list = punctuation_removal.split()
#removal of stopwords from the list prepared in the cell above
for index, word in enumerate(split_list): #removal of stopwords
if word in stop_words_list:
split_list.remove(word)
sentence = split_list
#lemmatizing words so that all words are in their base form (i.e predicts, predict & predicted should be represented as predict)
lemmatizer=WordNetLemmatizer()
words_lem = [lemmatizer.lemmatize(word) for word in sentence]
#removing single letter words
words_lem = [word for word in words_lem if (len(word)>1)]
output_text = output_text.join(words_lem)
#removing anything apart from words and numbers: final processing
output_text = re.sub('([^A-Z0-9a-z\s]+)', ' ', output_text)
return output_text
# In[12]:
data['tweets'] = data['text'].apply(lambda x: preprocess_text(x)).copy()
# In[13]:
data['tweets'].head()
# ## Exploratory Analysis for generic tweets file
# Word Cloud:
# A word cloud represents word usage in a document by resizing individual words proportionally to its frequency, and then presenting them in random arrangement.
# In[14]:
#Word cloud for Positive Tweets
generic_tweets = data['tweets'][data['class']==1]
tweets_string = []
for t in generic_tweets:
tweets_string.append(t)
tweets_string = pd.Series(tweets_string).str.cat(sep=' ')
wordcloud = WordCloud(width=1600, height=800,max_font_size=200).generate(tweets_string)
fig, axes = plt.subplots(2, 1, figsize = (12,10))
axes[0].set_title('Word cloud for positive sentiments')
axes[0].imshow(wordcloud, interpolation="bilinear")
axes[0].axis("off")
generic_tweets = data['tweets'][data['class'] == 0]
tweets_string = []
for t in generic_tweets:
tweets_string.append(t)
tweets_string = pd.Series(tweets_string).str.cat(sep=' ')
wordcloud = WordCloud(width=1600, height=800,max_font_size=200).generate(tweets_string)
axes[1].set_title('Word cloud for negative sentiments')
axes[1].imshow(wordcloud, interpolation="bilinear")
axes[1].axis("off")
plt.show()
plt.savefig('Word Clouds.png')
# **Discussion:**
#
# Some words in both the word clouds clearly represent their respective emotion. For example:
# Positve emotion words: good, haha, love, nice, great, well, posemo
# Negative emotion words: sad, still, cant, dont, hate
#
# However, both the word clouds have common prominent words like today, amp which might represent common subject of tweets
# ## Model Preparation and Implementation on Generic Tweets data
#
# Feature extraction
# 1. Bag of words
# 2. TF-IDF
#
# Models are trained on generic tweet's vocabulary and then sentiments of canadian election tweets are preidcted using the best model.This give us insight on the model performance on unseen data
# In[17]:
#shuffling data because classes are not shuffled first 100000 are 0's and next 100000 1's
data = data.sample(frac=1).reset_index(drop=True)
# In[18]:
X = data['tweets']
y = data['class']
# In[19]:
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=0.3)
# In[20]:
X_train
# Using count vectorizer for bag of words and tfidf vectorizer for TFIDF.
#
# **Parameters for TFIDF and Bag of words:**
# 1. max_fetaures are set to 2000 for reduce computation time and have uniform number of features for models.
# 2. strip_accents: to replace any special character with ascii representation
# In[21]:
#sparse matrix for bag of words
count_vectorizer = CountVectorizer(max_features = 2000, strip_accents = 'ascii')
count_vectorizer.fit(X)
feature_names = count_vectorizer.get_feature_names()
bow_train = count_vectorizer.transform(X_train)
bow_test = count_vectorizer.transform(X_test)
# In[22]:
#sparse matrix for TFIDF
tfidf_vectorizer = TfidfVectorizer(max_features = 2000, strip_accents = 'ascii')
tfidf_vectorizer.fit(X)
tfidf_train = tfidf_vectorizer.transform(X_train)
tfidf_test = tfidf_vectorizer.transform(X_test)
# In[23]:
f_train = hstack([tfidf_train, bow_train])
f_test = hstack([tfidf_test, bow_test])
# In[24]:
f_train.shape
# In[25]:
f_test.shape
# **Evaluation metric:**
# classification report is measured for all models but for comparing the results accuracy and f-measure is considered (precision and recall have similar values for all models, therefore it's suitable to consider f-measure for evaluation)
#
# Further,
# In classification report, **macro-average f1 score** is considered for evaluation because macro-average will compute the metric independently for each class and then take the average (hence treating all classes equally). Also, we have equal sentiment polarity in dataset. Therefore macro average is a better choice.
# In[26]:
train_accuracy = []
test_accuracy = []
train_f_measure = []
test_f_measure = []
# ## Model 1: Logistic Regression
#
# Parameters chosen:
#
# 1. **C** = 0.01; because smaller values specify stronger regularization. (Regularization is a very important technique to prevent overfitting)
# 2. **solver** = saga; because it is faster than other solvers for large datasets, when both the number of samples and the number of features are large.
# 3. **penalty** = l2; because it addresses the multicollinearity problem by constraining the coefficient norm and keeping all the variables.
# In[27]:
model_name = 'Logistic_regression - Bag of Words'
model_logistic_regression_bow = LogisticRegression(C = 0.01, solver = 'saga', penalty = 'l2')
model_logistic_regression_bow.fit(bow_train, y_train)
#evaluation on test
accuracy_test_lr_bow = model_logistic_regression_bow.score(bow_test, y_test)
#test_accuracy.append(accuracy_test)
print("Accuracy on test set for model- ", model_name, "is", round(accuracy_test_lr_bow,2)*100 , "%")
predictions = model_logistic_regression_bow.predict(bow_test)
conf_matrix_logistic_regression = confusion_matrix(y_test,predictions,labels=[0, 1])
print ("Confusion matrix: \n", conf_matrix_logistic_regression)
classification_report_ = classification_report(y_test,predictions, output_dict=True)
class_report_logistic_regression = pd.DataFrame(classification_report_).transpose()
f1_score_lr_bow = class_report_logistic_regression.loc['macro avg','f1-score']
#test_f_measure.append(f1_score_test)
print("Precision, recall and F1_score: \n", class_report_logistic_regression)
print("Macro-average score on test set: ", f1_score_lr_bow)
#evaluation on training set to check that model is not overfitting
accuracy_train = model_logistic_regression_bow.score(bow_train, y_train)
#train_accuracy.append(accuracy_train)
print("Accuracy on train set for model- ", model_name, "is", round(accuracy_train,2)*100 , "%")
predictions_train = model_logistic_regression_bow.predict(bow_train)
classification_report_ = classification_report(y_train,predictions_train, output_dict=True)
class_report_logistic_regression_train = pd.DataFrame(classification_report_).transpose()
f1_score_train = class_report_logistic_regression_train.loc['macro avg','f1-score']
#train_f_measure.append(f1_score_train)
print("Macro-average score on train set: ", f1_score_train)
# In[28]:
model_name = 'Logistic_regression - tfidf'
model_logistic_regression_tfidf = LogisticRegression(C = 0.01, solver = 'saga', penalty = 'l2')
model_logistic_regression_tfidf.fit(tfidf_train, y_train)
#evaluation on test
accuracy_test_lr_tfidf = model_logistic_regression_tfidf.score(tfidf_test, y_test)
#test_accuracy.append(accuracy_test)
print("Accuracy on test set for model- ", model_name, "is", round(accuracy_test_lr_tfidf,2)*100 , "%")
predictions = model_logistic_regression_tfidf.predict(tfidf_test)
conf_matrix_logistic_regression = confusion_matrix(y_test,predictions,labels=[0, 1])
print ("Confusion matrix: \n", conf_matrix_logistic_regression)
classification_report_ = classification_report(y_test,predictions, output_dict=True)
class_report_logistic_regression = pd.DataFrame(classification_report_).transpose()
f1_score_lr_tfidf = class_report_logistic_regression.loc['macro avg','f1-score']
#test_f_measure.append(f1_score_test)
print("Precision, recall and F1_score: \n", class_report_logistic_regression)
print("Macro-average score on test set: ", f1_score_lr_tfidf)
#evaluation on training set to check that model is not overfitting
accuracy_train = model_logistic_regression_tfidf.score(tfidf_train, y_train)
#train_accuracy.append(accuracy_train)
print("Accuracy on train set for model- ", model_name, "is", round(accuracy_train,2)*100 , "%")
predictions_train = model_logistic_regression_tfidf.predict(tfidf_train)
classification_report_ = classification_report(y_train,predictions_train, output_dict=True)
class_report_logistic_regression_train = pd.DataFrame(classification_report_).transpose()
f1_score_train = class_report_logistic_regression_train.loc['macro avg','f1-score']
#train_f_measure.append(f1_score_train)
print("Macro-average score on train set: ", f1_score_train)
# **Discussion:**
#
# Since accuracies and f1-scores for training set and test are nearly same, it is not overfitting. Hence are parameters for models works fine and can be used for new datasets for sentiment analysis
# ## Model 2: Naive Bayes
#
# **Model chosen:** Multinomial bayes..this is mostly used for document classification problem. The features/predictors used by the classifier are the frequency of the words present in the document.
#
# Hyperparameter alpha is used for smoothening of data. Using alpha = 1 (default value)
# In[29]:
model_name = 'Naive Bayes- Bag of words'
model_naive_bayes_bow = MultinomialNB(alpha = 1)
model_naive_bayes_bow.fit(bow_train, y_train)
#evaluation on test
accuracy_test_nb_bow = model_naive_bayes_bow.score(bow_test, y_test)
#test_accuracy.append(accuracy_test)
print("Accuracy on test set for model- ", model_name, "is", round(accuracy_test_nb_bow,2)*100 , "%")
predictions = model_naive_bayes_bow.predict(bow_test)
conf_matrix_naive_bayes = confusion_matrix(y_test,predictions,labels=[0, 1])
print ("Confusion matrix: \n", conf_matrix_naive_bayes)
classification_report_ = classification_report(y_test,predictions, output_dict=True)
class_report_naive_bayes = pd.DataFrame(classification_report_).transpose()
f1_score_nb_bow = class_report_naive_bayes.loc['macro avg','f1-score']
#test_f_measure.append(f1_score_test_nb_bow)
print("Precision, recall and F1_score: \n", class_report_naive_bayes)
print("Macro-average score on test set: ", f1_score_nb_bow)
#evaluation on training set to check that model is not overfitting
accuracy_train = model_naive_bayes_bow.score(bow_train, y_train)
#train_accuracy.append(accuracy_train)
print("Accuracy on train set for model- ", model_name, "is", round(accuracy_train,2)*100 , "%")
predictions_train = model_naive_bayes_bow.predict(bow_train)
classification_report_ = classification_report(y_train,predictions_train, output_dict=True)
class_report_naive_bayes_train = pd.DataFrame(classification_report_).transpose()
f1_score_train = class_report_naive_bayes_train.loc['macro avg','f1-score']
#train_f_measure.append(f1_score_train)
print("Macro-average score on train set: ", f1_score_train)
# In[30]:
model_name = 'Naive Bayes- TFIDF'
model_naive_bayes_tfidf = MultinomialNB(alpha = 1)
model_naive_bayes_tfidf.fit(tfidf_train, y_train)
#evaluation on test
accuracy_test_nb_tfidf = model_naive_bayes_tfidf.score(tfidf_test, y_test)
#test_accuracy.append(accuracy_test)
print("Accuracy on test set for model- ", model_name, "is", round(accuracy_test_nb_tfidf,2)*100 , "%")
predictions = model_naive_bayes_tfidf.predict(tfidf_test)
conf_matrix_naive_bayes = confusion_matrix(y_test,predictions,labels=[0, 1])
print ("Confusion matrix: \n", conf_matrix_naive_bayes)
classification_report_ = classification_report(y_test,predictions, output_dict=True)
class_report_naive_bayes = pd.DataFrame(classification_report_).transpose()
f1_score_nb_tfidf = class_report_naive_bayes.loc['macro avg','f1-score']
#test_f_measure.append(f1_score_test_nb_bow)
print("Precision, recall and F1_score: \n", class_report_naive_bayes)
print("Macro-average score on test set: ", f1_score_nb_tfidf)
#evaluation on training set to check that model is not overfitting
accuracy_train = model_naive_bayes_tfidf.score(tfidf_train, y_train)
#train_accuracy.append(accuracy_train)
print("Accuracy on train set for model- ", model_name, "is", round(accuracy_train,2)*100 , "%")
predictions_train = model_naive_bayes_tfidf.predict(tfidf_train)
classification_report_ = classification_report(y_train,predictions_train, output_dict=True)
class_report_naive_bayes_train = pd.DataFrame(classification_report_).transpose()
f1_score_train = class_report_naive_bayes_train.loc['macro avg','f1-score']
#train_f_measure.append(f1_score_train)
print("Macro-average score on train set: ", f1_score_train)
# **Discussion:**
#
# Since accuracies and f1-scores for training set and test are nearly same, it is not overfitting. Hence are parameter alpha = 1 for model works fine and can be used for new datasets for sentiment analysis
# ## Model 3: kNN Classifer
#
# Classification is computed from a simple majority vote of the nearest neighbors of each point: a query point is assigned the data class which has the most representatives within the nearest neighbors of the point.
#
# **Parameters:**
# 1. n_neighnors = 5 (default)
# 2. algorithm = brute_force because of sparse input
# In[31]:
model_name = 'KNN Classifier - Bag of words'
model_KNN_bow = KNeighborsClassifier(n_neighbors=5, algorithm = 'brute')
model_KNN_bow.fit(bow_train, y_train)
#evaluation on test
accuracy_test_KNN_bow = model_KNN_bow.score(bow_test, y_test)
#test_accuracy.append(accuracy_test)
print("Accuracy on test set for model- ", model_name, "is", round(accuracy_test_KNN_bow,2)*100 , "%")
predictions = model_KNN_bow.predict(bow_test)
conf_matrix_KNN = confusion_matrix(y_test,predictions,labels=[0, 1])
print ("Confusion matrix: \n", conf_matrix_KNN)
classification_report_ = classification_report(y_test,predictions, output_dict=True)
class_report_KNN = pd.DataFrame(classification_report_).transpose()
f1_score_KNN_bow = class_report_KNN.loc['macro avg','f1-score']
#test_f_measure.append(f1_score_test)
print("Precision, recall and F1_score: \n", class_report_KNN)
print("Macro-average score on test set: ", f1_score_KNN_bow)
#evaluation on training set to check that model is not overfitting
accuracy_train = model_KNN_bow.score(bow_train, y_train)
#train_accuracy.append(accuracy_train)
print("Accuracy on train set for model- ", model_name, "is", round(accuracy_train,2)*100 , "%")
predictions_train = model_KNN_bow.predict(bow_train)
classification_report_ = classification_report(y_train,predictions_train, output_dict=True)
class_report_KNN_train = pd.DataFrame(classification_report_).transpose()
f1_score_train = class_report_KNN_train.loc['macro avg','f1-score']
#train_f_measure.append(f1_score_train)
print("Macro-average score on train set: ", f1_score_train)
# In[32]:
model_name = 'KNN Classifier- TFIDF'
model_KNN_tfidf = KNeighborsClassifier(n_neighbors=5, algorithm = 'brute')
model_KNN_tfidf.fit(tfidf_train, y_train)
#evaluation on test
accuracy_test_KNN_tfidf = model_KNN_tfidf.score(tfidf_test, y_test)
#test_accuracy.append(accuracy_test)
print("Accuracy on test set for model- ", model_name, "is", round(accuracy_test_KNN_tfidf,2)*100 , "%")
predictions = model_KNN_tfidf.predict(tfidf_test)
conf_matrix_KNN = confusion_matrix(y_test,predictions,labels=[0, 1])
print ("Confusion matrix: \n", conf_matrix_KNN)
classification_report_ = classification_report(y_test,predictions, output_dict=True)
class_report_KNN = pd.DataFrame(classification_report_).transpose()
f1_score_KNN_tfidf = class_report_KNN.loc['macro avg','f1-score']
#test_f_measure.append(f1_score_test_nb_bow)
print("Precision, recall and F1_score: \n", class_report_naive_bayes)
print("Macro-average score on test set: ", f1_score_KNN_tfidf)
#evaluation on training set to check that model is not overfitting
accuracy_train = model_KNN_tfidf.score(tfidf_train, y_train)
#train_accuracy.append(accuracy_train)
print("Accuracy on train set for model- ", model_name, "is", round(accuracy_train,2)*100 , "%")
predictions_train = model_KNN_tfidf.predict(tfidf_train)
classification_report_ = classification_report(y_train,predictions_train, output_dict=True)
class_report_naive_bayes_train = pd.DataFrame(classification_report_).transpose()
f1_score_train = class_report_naive_bayes_train.loc['macro avg','f1-score']
#train_f_measure.append(f1_score_train)
print("Macro-average score on train set: ", f1_score_train)
# **Discussion:**
#
# KNN model seems to be slightly overfitted: comparing test accuracy(67%) and train accuracy(77%)
#
# Accuracy and f1-score for both the cases (TFIDF and Bag of words) is lesser than Naive Bayes and Logistic regression metrics.
# Also, KNN is computationally slower than the other two models
#
# ## Model 4: Support Vector Machine
#
# Support Vector Machines (SVMs) work well with high dimensional spaces and are memory efficient.
#
# Using RBF kernel for SVMs: which uses non-linear hyperplane. gamma is a parameter for non linear hyperplanes. The higher the gamma value it tries to exactly fit the training data set
# Since we have lot of features, it won't be ideal to take linear plane for approximation
# In[33]:
model_name = 'SVM- Bag of words'
model_SVM_bow = SVC(gamma = 'auto', cache_size = 1000)
model_SVM_bow.fit(bow_train, y_train)
#evaluation on test
accuracy_test_SVM_bow = model_SVM_bow.score(bow_test, y_test)
#test_accuracy.append(accuracy_test)
print("Accuracy on test set for model- ", model_name, "is", round(accuracy_test_SVM_bow,2)*100 , "%")
predictions = model_SVM_bow.predict(bow_test)
conf_matrix_SVM = confusion_matrix(y_test,predictions,labels=[0, 1])
print ("Confusion matrix: \n", conf_matrix_SVM)
classification_report_ = classification_report(y_test,predictions, output_dict=True)
class_report_SVM = pd.DataFrame(classification_report_).transpose()
f1_score_SVM_bow = class_report_SVM.loc['macro avg','f1-score']
#test_f_measure.append(f1_score_test_nb_bow)
print("Precision, recall and F1_score: \n", class_report_SVM)
print("Macro-average score on test set: ", f1_score_SVM_bow)
#evaluation on training set to check that model is not overfitting
accuracy_train = model_SVM_bow.score(bow_train, y_train)
#train_accuracy.append(accuracy_train)
print("Accuracy on train set for model- ", model_name, "is", round(accuracy_train,2)*100 , "%")
predictions_train = model_SVM_bow.predict(bow_train)
classification_report_ = classification_report(y_train,predictions_train, output_dict=True)
class_report_SVM_train = pd.DataFrame(classification_report_).transpose()
f1_score_train = class_report_SVM_train.loc['macro avg','f1-score']
#train_f_measure.append(f1_score_train)
print("Macro-average score on train set: ", f1_score_train)
# In[34]:
model_name = 'SVM- TFIDF'
model_SVM_tfidf = SVC(gamma = 'auto', cache_size = 1000)
model_SVM_tfidf.fit(tfidf_train, y_train)
#evaluation on test
accuracy_test_SVM_tfidf = model_SVM_tfidf.score(tfidf_test, y_test)
#test_accuracy.append(accuracy_test)
print("Accuracy on test set for model- ", model_name, "is", round(accuracy_test_SVM_tfidf,2)*100 , "%")
predictions = model_SVM_tfidf.predict(tfidf_test)
conf_matrix_SVM = confusion_matrix(y_test,predictions,labels=[0, 1])
print ("Confusion matrix: \n", conf_matrix_SVM)
classification_report_ = classification_report(y_test,predictions, output_dict=True)
class_report_SVM = pd.DataFrame(classification_report_).transpose()
f1_score_SVM_tfidf = class_report_SVM.loc['macro avg','f1-score']
#test_f_measure.append(f1_score_test_nb_bow)
print("Precision, recall and F1_score: \n", class_report_SVM)
print("Macro-average score on test set: ", f1_score_SVM_tfidf)
#evaluation on training set to check that model is not overfitting
accuracy_train = model_SVM_tfidf.score(tfidf_train, y_train)
#train_accuracy.append(accuracy_train)
print("Accuracy on train set for model- ", model_name, "is", round(accuracy_train,2)*100 , "%")
predictions_train = model_SVM_tfidf.predict(tfidf_train)
classification_report_ = classification_report(y_train,predictions_train, output_dict=True)
class_report_SVM_train = pd.DataFrame(classification_report_).transpose()
f1_score_train = class_report_SVM_train.loc['macro avg','f1-score']
#train_f_measure.append(f1_score_train)
print("Macro-average score on train set: ", f1_score_train)
# Since accuracies and f1-score are almost same on test and train data, the model is not overfitting
# ## Model 5: Decision Trees
#
# Decision Trees can be useful for this case, as data to be trained as equal number of samples for both classes.
#
# Using default parameters for decision trees
# In[35]:
## Model 4: Decision Trees
model_name = 'Decision Trees- Bag of words'
model_decision_tree_bow = DecisionTreeClassifier()
model_decision_tree_bow.fit(bow_train, y_train)
#evaluation on test
accuracy_test_dt_bow = model_decision_tree_bow.score(bow_test, y_test)
#test_accuracy.append(accuracy_test)
print("Accuracy on test set for model- ", model_name, "is", round(accuracy_test_dt_bow,2)*100 , "%")
predictions = model_decision_tree_bow.predict(bow_test)
conf_matrix_decision_tree = confusion_matrix(y_test,predictions,labels=[0, 1])
print ("Confusion matrix: \n", conf_matrix_decision_tree)
classification_report_ = classification_report(y_test,predictions, output_dict=True)
class_report_decision_tree = pd.DataFrame(classification_report_).transpose()
f1_score_dt_bow = class_report_decision_tree.loc['macro avg','f1-score']
#test_f_measure.append(f1_score_)
print("Precision, recall and F1_score: \n", class_report_decision_tree)
print("Macro-average score on test set: ", f1_score_dt_bow)
#evaluation on training set to check that model is not overfitting
accuracy_train = model_decision_tree_bow.score(bow_train, y_train)
#train_accuracy.append(accuracy_train)
print("Accuracy on train set for model- ", model_name, "is", round(accuracy_train,2)*100 , "%")
predictions_train = model_decision_tree_bow.predict(bow_train)
classification_report_ = classification_report(y_train,predictions_train, output_dict=True)
class_report_decision_tree_train = pd.DataFrame(classification_report_).transpose()
f1_score_train = class_report_decision_tree_train.loc['macro avg','f1-score']
#train_f_measure.append(f1_score_train)
print("Macro-average score on train set: ", f1_score_train)
# In[36]:
## Model 4: Decision Trees
model_name = 'Decision Trees- TFIDF'
model_decision_tree_tfidf = DecisionTreeClassifier()
model_decision_tree_tfidf.fit(tfidf_train, y_train)
#evaluation on test
accuracy_test_dt_tfidf = model_decision_tree_tfidf.score(tfidf_test, y_test)
#test_accuracy.append(accuracy_test)
print("Accuracy on test set for model- ", model_name, "is", round(accuracy_test_dt_tfidf,2)*100 , "%")
predictions = model_decision_tree_tfidf.predict(tfidf_test)
conf_matrix_decision_tree = confusion_matrix(y_test,predictions,labels=[0, 1])
print ("Confusion matrix: \n", conf_matrix_decision_tree)
classification_report_ = classification_report(y_test,predictions, output_dict=True)
class_report_decision_tree = pd.DataFrame(classification_report_).transpose()
f1_score_dt_tfidf = class_report_decision_tree.loc['macro avg','f1-score']
#test_f_measure.append(f1_score_)
print("Precision, recall and F1_score: \n", class_report_decision_tree)
print("Macro-average score on test set: ", f1_score_dt_tfidf)
#evaluation on training set to check that model is not overfitting
accuracy_train = model_decision_tree_tfidf.score(tfidf_train, y_train)
#train_accuracy.append(accuracy_train)
print("Accuracy on train set for model- ", model_name, "is", round(accuracy_train,2)*100 , "%")
predictions_train = model_decision_tree_tfidf.predict(tfidf_train)
classification_report_ = classification_report(y_train,predictions_train, output_dict=True)
class_report_decision_tree_train = pd.DataFrame(classification_report_).transpose()
f1_score_train = class_report_decision_tree_train.loc['macro avg','f1-score']
#train_f_measure.append(f1_score_train)
print("Macro-average score on train set: ", f1_score_train)
# Since evaluation metrics - accuracy and f1 measure on test data and train data are not close, the model is overfit. To deal with this, paramters like number of maximum leaf nodes and maximum depth of tree is defined
#
# 1. max_leaf_nodes: nodes are defined as relative reduction in impurity
# 2. max_depth: tree size
# In[37]:
## Model 4: Decision Trees
model_name = 'Decision Trees- Bag of words'
model_decision_tree_bow = DecisionTreeClassifier(max_depth = 10,max_leaf_nodes = 30)
model_decision_tree_bow.fit(bow_train, y_train)
#evaluation on test
accuracy_test_dt_bow = model_decision_tree_bow.score(bow_test, y_test)
#test_accuracy.append(accuracy_test)
print("Accuracy on test set for model- ", model_name, "is", round(accuracy_test_dt_bow,2)*100 , "%")
predictions = model_decision_tree_bow.predict(bow_test)
conf_matrix_decision_tree = confusion_matrix(y_test,predictions,labels=[0, 1])
print ("Confusion matrix: \n", conf_matrix_decision_tree)
classification_report_ = classification_report(y_test,predictions, output_dict=True)
class_report_decision_tree = pd.DataFrame(classification_report_).transpose()
f1_score_dt_bow = class_report_decision_tree.loc['macro avg','f1-score']
#test_f_measure.append(f1_score_)
print("Precision, recall and F1_score: \n", class_report_decision_tree)
print("Macro-average score on test set: ", f1_score_dt_bow)
#evaluation on training set to check that model is not overfitting
accuracy_train = model_decision_tree_bow.score(bow_train, y_train)
#train_accuracy.append(accuracy_train)
print("Accuracy on train set for model- ", model_name, "is", round(accuracy_train,2)*100 , "%")
predictions_train = model_decision_tree_bow.predict(bow_train)
classification_report_ = classification_report(y_train,predictions_train, output_dict=True)
class_report_decision_tree_train = pd.DataFrame(classification_report_).transpose()
f1_score_train = class_report_decision_tree_train.loc['macro avg','f1-score']
#train_f_measure.append(f1_score_train)
print("Macro-average score on train set: ", f1_score_train)
# In[38]:
## Model 4: Decision Trees
model_name = 'Decision Trees- TFIDF'
model_decision_tree_tfidf = DecisionTreeClassifier(max_depth = 10,max_leaf_nodes = 30)
model_decision_tree_tfidf.fit(tfidf_train, y_train)
#evaluation on test
accuracy_test_dt_tfidf = model_decision_tree_tfidf.score(tfidf_test, y_test)
#test_accuracy.append(accuracy_test)
print("Accuracy on test set for model- ", model_name, "is", round(accuracy_test_dt_tfidf,2)*100 , "%")
predictions = model_decision_tree_tfidf.predict(tfidf_test)
conf_matrix_decision_tree = confusion_matrix(y_test,predictions,labels=[0, 1])
print ("Confusion matrix: \n", conf_matrix_decision_tree)
classification_report_ = classification_report(y_test,predictions, output_dict=True)
class_report_decision_tree = pd.DataFrame(classification_report_).transpose()
f1_score_dt_tfidf = class_report_decision_tree.loc['macro avg','f1-score']
#test_f_measure.append(f1_score_)
print("Precision, recall and F1_score: \n", class_report_decision_tree)
print("Macro-average score on test set: ", f1_score_dt_tfidf)
#evaluation on training set to check that model is not overfitting
accuracy_train = model_decision_tree_tfidf.score(tfidf_train, y_train)
#train_accuracy.append(accuracy_train)
print("Accuracy on train set for model- ", model_name, "is", round(accuracy_train,2)*100 , "%")
predictions_train = model_decision_tree_tfidf.predict(tfidf_train)
classification_report_ = classification_report(y_train,predictions_train, output_dict=True)
class_report_decision_tree_train = pd.DataFrame(classification_report_).transpose()
f1_score_train = class_report_decision_tree_train.loc['macro avg','f1-score']
#train_f_measure.append(f1_score_train)
print("Macro-average score on train set: ", f1_score_train)
# ## Model 6 Ensemble - Random Forest
#
# A random forest is a meta estimator that fits a number of decision tree classifiers on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting
#
# **Parameters:**
# 1. n_estimators = 100 (default) - number of trees in the forest
# 2. max_depth = the tree size (using same as in Decision Trees model)
# 3. max_leaf_nodes = 30; using same as in Decision trees model - to prevent overfitting)
# 4. Bootstrapping = True; if False, it uses the whole dataset for sub-trees which is computationally expensive
# In[39]:
model_name = 'Random Forest- bag of words'
model_random_forest_bow = RandomForestClassifier(n_estimators=100,max_depth = 10,max_leaf_nodes = 30, bootstrap = True )
model_random_forest_bow.fit(bow_train, y_train)
#evaluation on test
accuracy_test_rf_bow = model_random_forest_bow.score(bow_test, y_test)
#test_accuracy.append(accuracy_test)
print("Accuracy on test set for model- ", model_name, "is", round(accuracy_test_rf_bow,2)*100 , "%")
predictions = model_random_forest_bow.predict(bow_test)
conf_matrix_random_forest = confusion_matrix(y_test,predictions,labels=[0, 1])
print ("Confusion matrix: \n", conf_matrix_random_forest)
classification_report_ = classification_report(y_test,predictions, output_dict=True)
class_report_random_forest = pd.DataFrame(classification_report_).transpose()
f1_score_rf_bow = class_report_decision_tree.loc['macro avg','f1-score']
#test_f_measure.append(f1_score_test)
print("Precision, recall and F1_score: \n", class_report_random_forest)
print("Macro-average score on test set: ", f1_score_rf_bow)
#evaluation on training set to check that model is not overfitting
accuracy_train = model_random_forest_bow.score(bow_train, y_train)
#train_accuracy.append(accuracy_train)
print("Accuracy on train set for model- ", model_name, "is", round(accuracy_train,2)*100 , "%")
predictions_train = model_random_forest_bow.predict(bow_train)
classification_report_ = classification_report(y_train,predictions_train, output_dict=True)
class_report_random_forest_train = pd.DataFrame(classification_report_).transpose()
f1_score_train = class_report_random_forest_train.loc['macro avg','f1-score']
#train_f_measure.append(f1_score_train)
print("Macro-average score on train set: ", f1_score_train)
# In[40]:
model_name = 'Random Forest- TFIDF'
model_random_forest_tfidf = RandomForestClassifier(n_estimators=100,max_depth = 10,max_leaf_nodes = 30, bootstrap = True )
model_random_forest_tfidf.fit(tfidf_train, y_train)
#evaluation on test
accuracy_test_rf_tfidf = model_random_forest_tfidf.score(tfidf_test, y_test)
#test_accuracy.append(accuracy_test)
print("Accuracy on test set for model- ", model_name, "is", round(accuracy_test_rf_tfidf,2)*100 , "%")
predictions = model_random_forest_tfidf.predict(tfidf_test)
conf_matrix_random_forest = confusion_matrix(y_test,predictions,labels=[0, 1])
print ("Confusion matrix: \n", conf_matrix_random_forest)
classification_report_ = classification_report(y_test,predictions, output_dict=True)
class_report_random_forest = pd.DataFrame(classification_report_).transpose()
f1_score_rf_tfidf = class_report_decision_tree.loc['macro avg','f1-score']
#test_f_measure.append(f1_score_test)
print("Precision, recall and F1_score: \n", class_report_random_forest)
print("Macro-average score on test set: ", f1_score_rf_tfidf)
#evaluation on training set to check that model is not overfitting
accuracy_train = model_random_forest_tfidf.score(tfidf_train, y_train)
#train_accuracy.append(accuracy_train)
print("Accuracy on train set for model- ", model_name, "is", round(accuracy_train,2)*100 , "%")
predictions_train = model_random_forest_tfidf.predict(tfidf_train)
classification_report_ = classification_report(y_train,predictions_train, output_dict=True)
class_report_random_forest_train = pd.DataFrame(classification_report_).transpose()
f1_score_train = class_report_random_forest_train.loc['macro avg','f1-score']
#train_f_measure.append(f1_score_train)
print("Macro-average score on train set: ", f1_score_train)
# ## Model 7: Ensemble - XGBoost
#
# Boosting trains models in succession, with each new model being trained to correct the errors made by the previous ones. Models are added sequentially until no further improvements can be made.
#
# **Parameters:**
#
# 1. max_depth (maximum depth of the decision trees being trained)
# 2. Objective (the loss function being used)
# 3. num_class (the number of classes in the dataset).
# 4. eta algorithm prevents overfitting. This algorithm makes XGBoost different from Gradient Boosting. Trees are added to the ensemble with a certain weight (eta*residual error)
# In[41]:
D_train = xgb.DMatrix(bow_train, label=y_train)
D_test = xgb.DMatrix(bow_test, label=y_test)
param = {'eta': 0.3, 'max_depth': 3,'objective': 'multi:softprob','num_class': 3}
steps = 20 # The number of training iterations
model_name = 'XGBoost- bag of words'
model_XGBoost_bow = xgb.train(param, D_train, steps)
#model_XGBoost.fit(f_train, y_train)
#evaluation on test
predict = model_XGBoost_bow.predict(D_test)
predictions = np.asarray([np.argmax(line) for line in predict])
precision = precision_score(y_test, predictions, average='macro')
recall= recall_score(y_test, predictions, average='macro')
f1_score_xgb_bow = 2*(precision*recall)/(precision+recall)
accuracy_test_xgb_bow = accuracy_score(y_test, predictions)
print("Precision on test set = {}".format(precision))
print("Recall on test set = {}".format(recall))
print("F1 Score on test set = {}".format(f1_score_xgb_bow))
print("Accuracy on test set = {}".format(accuracy_test_xgb_bow))
#test_accuracy.append(accuracy_test)
#test_f_measure.append(f1_score_test)
#evaluation on training set to check that model is not overfitting
predict_train = model_XGBoost_bow.predict(D_train)
predictions_train = np.asarray([np.argmax(line) for line in predict_train])
precision_train = precision_score(y_train, predictions_train, average='macro')
recall= recall_score(y_train, predictions_train, average='macro')
f1_score_train = 2*(precision*recall)/(precision+recall)
accuracy_train = accuracy_score(y_train, predictions_train)
print("F1 Score on training set = {}".format(f1_score_train))
print("Accuracy on training set = {}".format(accuracy_train))
#train_accuracy.append(accuracy_train)
#train_f_measure.append(f1_score_train)
# In[42]:
D_train = xgb.DMatrix(tfidf_train, label=y_train)
D_test = xgb.DMatrix(tfidf_test, label=y_test)
param = {'eta': 0.3, 'max_depth': 3,'objective': 'multi:softprob','num_class': 3}
steps = 20 # The number of training iterations
model_name = 'XGBoost- tfidf'
model_XGBoost_tfidf = xgb.train(param, D_train, steps)