-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwitter Code.py
More file actions
1233 lines (935 loc) · 47.7 KB
/
Twitter Code.py
File metadata and controls
1233 lines (935 loc) · 47.7 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
#LOADING LIBRARIES
import re # for regular expressions
import nltk # for text manipulation
import string # forString operations (not necessary)
from datetime import datetime # To access datetime
import warnings # for throwing exceptions
import numpy as np # for scientific computing
import pandas as pd # for working with data
import seaborn as sns # extension of matplotlib
import matplotlib.pyplot as plt #plots graphs
from sklearn.preprocessing import StandardScaler #To transform the data
from nltk.stem.porter import * #To use PorterStemmer function
from wordcloud import WordCloud #To use wordcloud
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer #TfidfVectorizer->gives higher weight to words occuring rare in a entire corpus but good in few documents
import gensim #Topic modelling(identify which topic is discussed), Similarity retrieval
from tqdm import tqdm
tqdm.pandas(desc="progress-bar") #To display progress bar with title "progres-bar"
from gensim.models.deprecated.doc2vec import LabeledSentence #Labelling tweets for doc2vec purpose
from sklearn.linear_model import LogisticRegression # To build Logistic regression model
from sklearn.model_selection import train_test_split # For splitting data into train and test data
from sklearn.metrics import f1_score # To compute performance of the model
from sklearn import svm # To build Support vector machine model
from sklearn.ensemble import RandomForestClassifier #To build Random forest classifier model
from xgboost import XGBClassifier #To build extreme gradient boosting model
import xgboost as xgb #Imports all features of extreme gradient boosting algorithm
import lightgbm as lgb #To build light gradient boosting model
np.random.seed(11)#To reproduce results
###################################################################################################################################################################
#DATA INSPECTION
#sets value
pd.set_option("display.max_colwidth", 200)
#To ignore deprecation warnings
warnings.filterwarnings("ignore")
#importing datasets
train = pd.read_csv('train_tweets.csv')
test = pd.read_csv('test_tweets.csv')
#first 10 data of non-racist and racist tweets resp..,
print("\nNON RACIST TWEETS\n")
print(train[train['label'] == 0].head(10))
print("\nRACIST TWEETS\n")
print(train[train['label'] == 1].head(10))
#dimensions of data set
print("\nTRAINING SET\n")
print(train.shape)
print("\nTEST SET\n")
print(test.shape)
#split of tweets in terms of labels in training set
print("NO OF POSITIVE AND NEGATIVE TWEETS IN TRAINING DATASET")
print(train["label"].value_counts())
#tweets in terms of number of words in each tweet
length_train = train['tweet'].str.len()
length_test = test['tweet'].str.len()
#histogram autoamatically scales dataset suitable to plot the graph
#here bins seperate the enitre dataset into intervals of 20 and plot graph (discrete kind)
plt.hist(length_train, bins=20, label="train_tweets")
plt.hist(length_test, bins=20, label="test_tweets")
plt.legend()
plt.xlabel("Tweet id")
plt.ylabel("No of Words")
plt.show()
###################################################################################################################################################################
#DATA CLEANING
#To combine train and test data for cleaning
combi = train.append(test, ignore_index=True , sort=False)
#user-defined function to remove unwanted text patterns from the tweets.
def remove_pattern(input_txt, pattern):
#Finds all words matching the pattern
r = re.findall(pattern, input_txt)
for i in r:
#removes the matched words
input_txt = re.sub(i, '', input_txt)
return input_txt
#Removing user handles (\w - words)
#vectorize function used when recursively a function is called
combi['tidy_tweet'] = np.vectorize(remove_pattern)(combi['tweet'], "@[\w]*")
#Removing Punctuations, Numbers, and Special Characters (^ - except)
combi['tidy_tweet'] = combi['tidy_tweet'].str.replace("[^a-zA-Z#]", " ")
#Removing short words (assuming that less than 3 letter words will not much influence over sentiment)
#lambda function is similar to macros
#apply funcion applies particular function over every element
#Here, we join the words with empty string
combi['tidy_tweet'] = combi['tidy_tweet'].apply(lambda x: ' '.join([w for w in x.split() if len(w)>3]))
#Tokenization (List for each tweet where items are each word in the tweet)
tokenized_tweet = combi['tidy_tweet'].apply(lambda x: x.split())
#Normalization
tokenized_tweet = tokenized_tweet.apply(lambda x: [PorterStemmer().stem(i) for i in x])
print("\nFIRST 5 PROCESSED TOKENIZED TWEETS\n")
print(tokenized_tweet.head())
#Stitching normalized tokens together
for i in range(len(tokenized_tweet)):
tokenized_tweet[i] = ' '.join(tokenized_tweet[i])
combi['tidy_tweet'] = tokenized_tweet
###################################################################################################################################################################
#VISUALIZATION FROM TWEETS
#word cloud visualization is used to identify frequency of words
#Non-racist tweets
#Taking non - racist tweets
normal_words =' '.join([text for text in combi['tidy_tweet'][combi['label'] == 0]])
#Generating word cloud
wordcloud = WordCloud(width=800, height=500, random_state=11, max_font_size=110).generate(normal_words)
#Plotting word cloud in graph
plt.figure(figsize=(10, 7))
plt.imshow(wordcloud, interpolation="none")
plt.axis('off')
plt.show()
#Racist tweets
#Taking non - racist tweets
normal_words =' '.join([text for text in combi['tidy_tweet'][combi['label'] == 1]])
#Generating word cloud
wordcloud = WordCloud(width=800, height=500, random_state=11, max_font_size=110).generate(normal_words)
#Plotting word cloud in graph
plt.figure(figsize=(10, 7))
plt.imshow(wordcloud, interpolation="none")
plt.axis('off')
plt.show()
#Function to collect hashtags
def hashtag_extract(x):
hashtags = []
# Loop over the words in the tweet
for i in x:
#r - raw string used for specifying regular expressions
ht = re.findall(r"#(\w+)", i)
hashtags.append(ht)
return hashtags
# extracting hashtags from non-racist/sexist tweets
HT_regular = hashtag_extract(combi['tidy_tweet'][combi['label'] == 0])
# extracting hashtags from racist/sexist tweets
HT_negative = hashtag_extract(combi['tidy_tweet'][combi['label'] == 1])
# unnesting list (to make muliple list as single list)
HT_regular = sum(HT_regular,[])
HT_negative = sum(HT_negative,[])
#Plotting non-racist hashtags
#Frequency of each item
a = nltk.FreqDist(HT_regular)
#Storing frequency as dict/2D form
d = pd.DataFrame({'Hashtag': list(a.keys()),'Count': list(a.values())})
# selecting top 20 most frequent hashtags
d = d.nlargest(columns="Count", n = 20)
#Plotting
plt.figure(figsize=(18,5))
ax = sns.barplot(data=d, x= "Hashtag", y = "Count")
plt.show()
#Plotting racist hashtags
#Frequency of each item
a = nltk.FreqDist(HT_negative)
#Storing frequency as dict/2D form
d = pd.DataFrame({'Hashtag': list(a.keys()),'Count': list(a.values())})
# selecting top 20 most frequent hashtags
d = d.nlargest(columns="Count", n = 20)
#Plotting
plt.figure(figsize=(18,5))
ax = sns.barplot(data=d, x= "Hashtag", y = "Count")
plt.show()
###################################################################################################################################################################
#Bag-of-words Features
#max_df/min_df = int->no of documents ; float->percentage among total documents
#max_features = top 1000 features taken
#stop_words = english-> inbulit stop words list for english is used
bow_vectorizer = CountVectorizer(max_df=0.90, min_df=2, max_features=1000, stop_words='english')
#making data to center with mean zero and unit standard deviation
bow = bow_vectorizer.fit_transform(combi['tidy_tweet'])
###################################################################################################################################################################
#TF-IDF Features
#TF = (Number of times term t appears in a document)/(Number of terms in the document)
#IDF = log(N/n), where, N is the number of documents and n is the number of documents a term t has appeared in.
#TF-IDF = TF*IDF
tfidf_vectorizer = TfidfVectorizer(max_df=0.90, min_df=2, max_features=1000, stop_words='english')
#making data to center withe mean zero and unit standard deviation
tfidf = tfidf_vectorizer.fit_transform(combi['tidy_tweet'])
###################################################################################################################################################################
#_____________________________________________________________Notes on Word2Vec________________________________________________________________________________
#Word embeddings-> representing words as vectors
# -> high dimensional word features into low dimensional feature vectors by preserving the contextual similarity
#Combination of CBOW (Continuous bag of words) and Skip-gram model.
#CBOW-> tends to predict the target/current word using surrounding words present in window
#Skip-gram model-> tries to predict the surrounding words present in the window using the target/current word.
#Softmax-> converts vector as probability distribution
#Pretrained Word2Vec models (huge in size)
#Google News Word Vectors
#Freebase names
#DBPedia vectors (wiki2vec)
#Training own Word2Vec model
#tokenizing
tokenized_tweet = combi['tidy_tweet'].apply(lambda x: x.split())
model_w2v = gensim.models.Word2Vec(
tokenized_tweet,
size=200, # to represent in no.of.dimensions-> more the dimension, more the efficiency of model
window=5, # takes 10 words surrounding the current word to find context of current word
min_count=2, # removes words with frequency less than 2
sg = 1, # 1 for skip-gram model
hs = 0, # 0 for negative sampling
negative = 10, # only takes random 10 negative samples(since dataset is huge, this is done)
workers= 1, # no.of threads to train the model - set to 1 to reproduce same results
seed = 11, # to generate same random numbers every time
hashfxn = hash # for reproducability
)
#Training the built model-> should specify model, size of corpus, epoch
model_w2v.train(tokenized_tweet, total_examples= len(combi['tidy_tweet']), epochs=20)
#Getting similar context words to the mentioned word
sim_dinner = model_w2v.wv.most_similar(positive="dinner")
sim_trump = model_w2v.wv.most_similar(positive="trump")
i=0
sim_dinner_len = len(sim_dinner)
print("\nWORDS SIMILAR TO DINNER\n")
while(i<sim_dinner_len):
print("\n")
print(sim_dinner[i])
i=i+1
i=0
print("\nWORDS SIMILAR TO TRUMP\n")
sim_trump_len = len(sim_trump)
while(i<sim_trump_len):
print("\n")
print(sim_trump[i])
i=i+1
#Functions for converting tweets into vectors
def word_vector(tokens, size):
#Creates array with specified all filled with zeros and it is given a new shape
vec = np.zeros(size).reshape((1, size))
count = 0.
for word in tokens:
try:
#every token in a tweet is converted as a vector
vec += model_w2v[word].reshape((1, size))
count += 1.
# handling the case where the token is not in vocabulary continue
except KeyError:
continue
if count != 0:
vec /= count
return vec
#word2vec feature set
wordvec_arrays = np.zeros((len(tokenized_tweet), 200))
for i in range(len(tokenized_tweet)):
wordvec_arrays[i,:] = word_vector(tokenized_tweet[i], 200)
#converting array into 2D Table
wordvec_df = pd.DataFrame(wordvec_arrays)
###################################################################################################################################################################
#Doc2vec Embedding
#To label each tweet
def add_label(twt):
output = []
for i, s in zip(twt.index, twt):
#Tweet Id's are itself made as label
output.append(LabeledSentence(s, ["tweet_" + str(i)]))
return output
labeled_tweets = add_label(tokenized_tweet)
#Prints o to 5 labeled tweets
print("\nFIRST 6 LABELED TWEETS FOR ILLUSTRATION\n")
print(labeled_tweets[:6])
#Doc2vec is a small extension to the CBOW model.
#Instead of using just words to predict the next word, we also added paragraph ID which is document-unique.
# Word vectors represent concept of a word, while document vector represent the concept of a document
#Training doc2vec model
model_d2v = gensim.models.Doc2Vec(
dm=1, # dm = 1 for ‘distributed memory’ model
dm_mean=1, # dm = 1 for using mean of the context word vectors
vector_size=200, # to represent in no.of.dimensions-> more the dimension, more the efficiency of model
window=5, # takes 10 words surrounding the current word to find context of current word
negative = 7, # only takes random 7 negative samples(since dataset is huge, this is done)
min_count=2, # removes words with frequency less than 2
workers=1, # no. of threads to train the model - to reproduce same results
alpha=0.1, # learning rate
seed = 11, # to generate same random numbers every time
)
#To show progress bar while training Doc2vec model
model_d2v.build_vocab([i for i in tqdm(labeled_tweets)])
#Training Doc2vec model
model_d2v.train(labeled_tweets, total_examples= len(combi['tidy_tweet']), epochs=15)
#Preparing doc2vec Feature Set
docvec_arrays = np.zeros((len(tokenized_tweet), 200))
for i in range(len(combi)):
docvec_arrays[i,:] = model_d2v.docvecs[i].reshape((1,200))
#converting array into 2D Table
docvec_df = pd.DataFrame(docvec_arrays)
###################################################################################################################################################################
#Building different machine learning models to use later
#We are computing evaluation time for different models
# Creating Logistic regression model
#solver -> algorithm for optimimzation problem
lreg = LogisticRegression(solver = "lbfgs", random_state=11)
# Creating SVM model
#kernel -> type of classifier
#C -> regularization ; lower value of c, larger is the margin seperating hyperplane
svc = svm.SVC(kernel='linear', C=1, random_state = 11, probability=True)
#Creating Random Forest model
#n_estimators -> No of trees
rf = RandomForestClassifier(n_estimators=400, random_state=11)
#Creating xgb model
#max_depth -> tree depth ; more the depth, more is the complexity
xgb_cl = XGBClassifier(random_state=11, n_estimators=1000)
#We are going to split the bow, tfidf, word2vec and doc2vec features into train and test data once (in Logitic regression model)
#Use the same train and test data correspondingly in all other machine leaning models also
###################################################################################################################################################################
print("\n\nLOGISTIC REGRESSION MODEL ACCURACIES\n\n")
#BOW FEATURES - Logistic Regression model
# Segregating dataset into train and test BoW features
#0 to 31961 -> Training dataset
#31962 to end -> Test dataset
train_bow = bow[:31962,:]
test_bow = bow[31962:,:]
# splitting Training dataset into training and validation set
xtrain_bow, xvalid_bow, ytrain, yvalid = train_test_split(train_bow, train['label'],random_state=11,test_size=0.3)
# Training the model with training set from Training dataset and computing training time
start = datetime.now()
lreg.fit(xtrain_bow, ytrain)
stop = datetime.now()
lreg_bow_exec_time = stop - start
# prediction on the validation set from Training dataset
prediction = lreg.predict_proba(xvalid_bow)
#If probability for label 1 is over 0.3, it is taken as label 1
prediction_int = prediction[:,1]>=0.3
prediction_int = prediction_int.astype(np.int)
#calculating f1 score for model performance
bow_lreg_pred_score = f1_score(yvalid, prediction_int)
print("\nF1 SCORE FOR BAG OF WORDS USING LOGISTIC REGRESSION\n")
print(bow_lreg_pred_score)
#Testing the built Logistic regression model on test data
#predicting on test data
bow_lreg_test_pred = lreg.predict_proba(test_bow)
#If probability for label 1 is over 0.3, it is taken as label 1
bow_lreg_test_pred_int = bow_lreg_test_pred[:,1]>=0.3
bow_lreg_test_pred_int = bow_lreg_test_pred_int.astype(np.int)
#Assigning the predicted values in the label field of test dataset
test['label'] = bow_lreg_test_pred_int
#Updating id and corresponding predicted labels in new csv file
submission = test[['id','label']]
submission.to_csv('logreg_bow.csv', index=False)
#TF-IDF FEATURES - Logistic Regression model
# Segregating dataset into train and test TF-IDF features
#0 to 31961 -> Training dataset
#31962 to end -> Test dataset
train_tfidf = tfidf[:31962,:]
test_tfidf = tfidf[31962:,:]
# splitting Training dataset into training and validation set (taking same train and validation set of BOW FEATURES)
xtrain_tfidf = train_tfidf[ytrain.index]
xvalid_tfidf = train_tfidf[yvalid.index]
# Training the model with training set from Training dataset and computing training time
start = datetime.now()
lreg.fit(xtrain_tfidf, ytrain)
stop = datetime.now()
lreg_tfidf_exec_time = stop - start
# prediction on the validation set from Training dataset
prediction = lreg.predict_proba(xvalid_tfidf)
#If probability for label 1 is over 0.3, it is taken as label 1
prediction_int = prediction[:,1]>=0.3
prediction_int = prediction_int.astype(np.int)
#calculating f1 score for model performance
tfidf_lreg_pred_score = f1_score(yvalid, prediction_int)
print("\nF1 SCORE FOR TF-IDF USING LOGISTIC REGRESSION\n")
print(tfidf_lreg_pred_score)
#Testing the built Logistic regression model on test data
#predicting on test data
tfidf_lreg_test_pred = lreg.predict_proba(test_tfidf)
#If probability for label 1 is over 0.3, it is taken as label 1
tfidf_lreg_test_pred_int = tfidf_lreg_test_pred[:,1]>=0.3
tfidf_lreg_test_pred_int = tfidf_lreg_test_pred_int.astype(np.int)
#Assigning the predicted values in the label field of test dataset
test['label'] = tfidf_lreg_test_pred_int
#Updating id and corresponding predicted labels in new csv file
submission = test[['id','label']]
submission.to_csv('logreg_tfidf.csv', index=False)
#WORD2VEC FEATURES - Logistic Regression model
# Segregating dataset into train and test WORD2VEC features
#0 to 31961 -> Training dataset
#31962 to end -> Test dataset
#iloc - access data by row index(since wordvec_df is 2D)
train_w2v = wordvec_df.iloc[:31962,:]
test_w2v = wordvec_df.iloc[31962:,:]
# splitting Training dataset into training and validation set (taking same train and validation set of BOW FEATURES)
xtrain_w2v = train_w2v.iloc[ytrain.index,:]
xvalid_w2v = train_w2v.iloc[yvalid.index,:]
# Training the model with training set from Training dataset and computing training time
start = datetime.now()
lreg.fit(xtrain_w2v, ytrain)
stop = datetime.now()
lreg_w2v_exec_time = stop - start
# prediction on the validation set from Training dataset
prediction = lreg.predict_proba(xvalid_w2v)
#If probability for label 1 is over 0.3, it is taken as label 1
prediction_int = prediction[:,1]>=0.3
prediction_int = prediction_int.astype(np.int)
#calculating f1 score for model performance
w2v_lreg_pred_score = f1_score(yvalid, prediction_int)
print("\nF1 SCORE FOR WORD2VEC USING LOGISTIC REGRESSION\n")
print(w2v_lreg_pred_score)
#Testing the built Logistic regression model on test data
#predicting on test data
w2v_lreg_test_pred = lreg.predict_proba(test_w2v)
#If probability for label 1 is over 0.3, it is taken as label 1
w2v_lreg_test_pred_int = w2v_lreg_test_pred[:,1]>=0.3
w2v_lreg_test_pred_int = w2v_lreg_test_pred_int.astype(np.int)
#Assigning the predicted values in the label field of test dataset
test['label'] = w2v_lreg_test_pred_int
#Updating id and corresponding predicted labels in new csv file
submission = test[['id','label']]
submission.to_csv('logreg_w2v.csv', index=False)
#DOC2VEC FEATURES - Logistic Regression model
# Segregating dataset into train and test DOC2VEC features
#0 to 31961 -> Training dataset
#31962 to end -> Test dataset
#iloc - access data by row index(since docvec_df is 2D)
train_d2v = docvec_df.iloc[:31962,:]
test_d2v = docvec_df.iloc[31962:,:]
# splitting Training dataset into training and validation set (taking same train and validation set of BOW FEATURES)
xtrain_d2v = train_d2v.iloc[ytrain.index,:]
xvalid_d2v = train_d2v.iloc[yvalid.index,:]
# Training the model with training set from Training dataset and computing training time
start = datetime.now()
lreg.fit(xtrain_d2v, ytrain)
stop = datetime.now()
lreg_d2v_exec_time = stop - start
# prediction on the validation set from Training dataset
prediction = lreg.predict_proba(xvalid_d2v)
#If probability for label 1 is over 0.3, it is taken as label 1
prediction_int = prediction[:,1]>=0.3
prediction_int = prediction_int.astype(np.int)
#calculating f1 score for model performance
d2v_lreg_pred_score = f1_score(yvalid, prediction_int)
print("\nF1 SCORE FOR DOC2VEC USING LOGISTIC REGRESSION\n")
print(d2v_lreg_pred_score)
#Testing the built Logistic regression model on test data
#predicting on test data
d2v_lreg_test_pred = lreg.predict_proba(test_d2v)
#If probability for label 1 is over 0.3, it is taken as label 1
d2v_lreg_test_pred_int = d2v_lreg_test_pred[:,1]>=0.3
d2v_lreg_test_pred_int = d2v_lreg_test_pred_int.astype(np.int)
#Assigning the predicted values in the label field of test dataset
test['label'] = d2v_lreg_test_pred_int
#Updating id and corresponding predicted labels in new csv file
submission = test[['id','label']]
submission.to_csv('logreg_d2v.csv', index=False)
###############################################################################################################################################################################
print("\n\nSUPPORT VECTOR MACHINE MODEL ACCURACIES\n\n")
#BOW FEATURES - SVM model
# Training the model with training set from Training dataset and computing training time
start = datetime.now()
svc.fit(xtrain_bow, ytrain)
stop = datetime.now()
svm_bow_exec_time = stop - start
# prediction on the validation set from Training dataset
prediction = svc.predict_proba(xvalid_bow)
#If probability for label 1 is over 0.3, it is taken as label 1
prediction_int = prediction[:,1]>=0.3
prediction_int = prediction_int.astype(np.int)
#calculating f1 score for model performance
bow_svm_pred_score = f1_score(yvalid, prediction_int)
print("\nF1 SCORE FOR BAG OF WORDS USING SUPPORT VECTOR MACHINE\n")
print(bow_svm_pred_score)
#Testing the built SVM model on test data
#predicting on test data
bow_svm_test_pred = svc.predict_proba(test_bow)
#If probability for label 1 is over 0.3, it is taken as label 1
bow_svm_test_pred_int = bow_svm_test_pred[:,1]>=0.3
bow_svm_test_pred_int = bow_svm_test_pred_int.astype(np.int)
#Assigning the predicted values in the label field of test dataset
test['label'] = bow_svm_test_pred_int
#Updating id and corresponding predicted labels in new csv file
submission = test[['id','label']]
submission.to_csv('svm_bow.csv', index=False)
#TF-IDF FEATURES - SVM model
# Training the model with training set from Training dataset and computing training time
start = datetime.now()
svc.fit(xtrain_tfidf, ytrain)
stop = datetime.now()
svm_tfidf_exec_time = stop - start
# prediction on the validation set from Training dataset
prediction = svc.predict_proba(xvalid_tfidf)
#If probability for label 1 is over 0.3, it is taken as label 1
prediction_int = prediction[:,1]>=0.3
prediction_int = prediction_int.astype(np.int)
#calculating f1 score for model performance
tfidf_svm_pred_score = f1_score(yvalid, prediction_int)
print("\nF1 SCORE FOR TF-IDF USING SUPPORT VECTOR MACHINE\n")
print(tfidf_svm_pred_score)
#Testing the built SVM on test data
#predicting on test data
tfidf_svm_test_pred = svc.predict_proba(test_tfidf)
#If probability for label 1 is over 0.3, it is taken as label 1
tfidf_svm_test_pred_int = tfidf_svm_test_pred[:,1]>=0.3
tfidf_svm_test_pred_int = tfidf_svm_test_pred_int.astype(np.int)
#Assigning the predicted values in the label field of test dataset
test['label'] = tfidf_svm_test_pred_int
#Updating id and corresponding predicted labels in new csv file
submission = test[['id','label']]
submission.to_csv('svm_tfidf.csv', index=False)
#WORD2VEC FEATURES - SVM model
# Training the model with training set from Training dataset and computing training time
start = datetime.now()
svc.fit(xtrain_w2v, ytrain)
stop = datetime.now()
svm_w2v_exec_time = stop - start
# prediction on the validation set from Training dataset
prediction = svc.predict_proba(xvalid_w2v)
#If probability for label 1 is over 0.3, it is taken as label 1
prediction_int = prediction[:,1]>=0.3
prediction_int = prediction_int.astype(np.int)
#calculating f1 score for model performance
w2v_svm_pred_score = f1_score(yvalid, prediction_int)
print("\nF1 SCORE FOR WORD2VEC USING SUPPORT VECTOR MACHINE\n")
print(w2v_svm_pred_score)
#Testing the built SVM model on test data
#predicting on test data
w2v_svm_test_pred = svc.predict_proba(test_w2v)
#If probability for label 1 is over 0.3, it is taken as label 1
w2v_svm_test_pred_int = w2v_svm_test_pred[:,1]>=0.3
w2v_svm_test_pred_int = w2v_svm_test_pred_int.astype(np.int)
#Assigning the predicted values in the label field of test dataset
test['label'] = w2v_svm_test_pred_int
#Updating id and corresponding predicted labels in new csv file
submission = test[['id','label']]
submission.to_csv('svm_w2v.csv', index=False)
#DOC2VEC FEATURES - SVM model
# Training the model with training set from Training dataset and computing training time
start = datetime.now()
svc.fit(xtrain_d2v, ytrain)
stop = datetime.now()
svm_d2v_exec_time = stop - start
# prediction on the validation set from Training dataset
prediction = svc.predict_proba(xvalid_d2v)
#If probability for label 1 is over 0.3, it is taken as label 1
prediction_int = prediction[:,1]>=0.3
prediction_int = prediction_int.astype(np.int)
#calculating f1 score for model performance
d2v_svm_pred_score = f1_score(yvalid, prediction_int)
print("\nF1 SCORE FOR DOC2VEC USING SUPPORT VECTOR MACHINE\n")
print(d2v_svm_pred_score)
#Testing the built SVM model on test data
#predicting on test data
d2v_svm_test_pred = svc.predict_proba(test_d2v)
#If probability for label 1 is over 0.3, it is taken as label 1
d2v_svm_test_pred_int = d2v_svm_test_pred[:,1]>=0.3
d2v_svm_test_pred_int = d2v_svm_test_pred_int.astype(np.int)
#Assigning the predicted values in the label field of test dataset
test['label'] = d2v_svm_test_pred_int
#Updating id and corresponding predicted labels in new csv file
submission = test[['id','label']]
submission.to_csv('svm_d2v.csv', index=False)
###########################################################################################################################################################################################
print("\n\nRANDOM FOREST MODEL ACCURACIES\n\n")
#BOW FEATURES - RANDOMFOREST model
# Training the model with training set from Training dataset and computing training time
start = datetime.now()
rf.fit(xtrain_bow, ytrain)
stop = datetime.now()
rf_bow_exec_time = stop - start
# prediction on the validation set from Training dataset
prediction = rf.predict_proba(xvalid_bow)
#If probability for label 1 is over 0.3, it is taken as label 1
prediction_int = prediction[:,1]>=0.3
prediction_int = prediction_int.astype(np.int)
#calculating f1 score for model performance
bow_rf_pred_score = f1_score(yvalid, prediction_int)
print("\nF1 SCORE FOR BAG OF WORDS USING RANDOM FOREST\n")
print(bow_rf_pred_score)
#Testing the built RANDOM FOREST model on test data
#predicting on test data
bow_rf_test_pred = rf.predict_proba(test_bow)
#If probability for label 1 is over 0.3, it is taken as label 1
bow_rf_test_pred_int = bow_rf_test_pred[:,1]>=0.3
bow_rf_test_pred_int = bow_rf_test_pred_int.astype(np.int)
#Assigning the predicted values in the label field of test dataset
test['label'] = bow_rf_test_pred_int
#Updating id and corresponding predicted labels in new csv file
submission = test[['id','label']]
submission.to_csv('rf_bow.csv', index=False)
#TF-IDF FEATURES - RANDOM FOREST model
# Training the model with training set from Training dataset and computing training time
start = datetime.now()
rf.fit(xtrain_tfidf, ytrain)
stop = datetime.now()
rf_tfidf_exec_time = stop - start
# prediction on the validation set from Training dataset
prediction = rf.predict_proba(xvalid_tfidf)
#If probability for label 1 is over 0.3, it is taken as label 1
prediction_int = prediction[:,1]>=0.3
prediction_int = prediction_int.astype(np.int)
#calculating f1 score for model performance
tfidf_rf_pred_score = f1_score(yvalid, prediction_int)
print("\nF1 SCORE FOR TF-IDF USING RANDOM FOREST\n")
print(tfidf_rf_pred_score)
#Testing the built RANDOM FOREST on test data
#predicting on test data
tfidf_rf_test_pred = rf.predict_proba(test_tfidf)
#If probability for label 1 is over 0.3, it is taken as label 1
tfidf_rf_test_pred_int = tfidf_rf_test_pred[:,1]>=0.3
tfidf_rf_test_pred_int = tfidf_rf_test_pred_int.astype(np.int)
#Assigning the predicted values in the label field of test dataset
test['label'] = tfidf_rf_test_pred_int
#Updating id and corresponding predicted labels in new csv file
submission = test[['id','label']]
submission.to_csv('rf_tfidf.csv', index=False)
#WORD2VEC FEATURES - RANDOM FOREST model
# Training the model with training set from Training dataset and computing training time
start = datetime.now()
rf.fit(xtrain_w2v, ytrain)
stop = datetime.now()
rf_w2v_exec_time = stop - start
# prediction on the validation set from Training dataset
prediction = rf.predict_proba(xvalid_w2v)
#If probability for label 1 is over 0.3, it is taken as label 1
prediction_int = prediction[:,1]>=0.3
prediction_int = prediction_int.astype(np.int)
#calculating f1 score for model performance
w2v_rf_pred_score = f1_score(yvalid, prediction_int)
print("\nF1 SCORE FOR WORD2VEC USING RANDOM FOREST\n")
print(w2v_rf_pred_score)
#Testing the built RANDOM FOREST model on test data
#predicting on test data
w2v_rf_test_pred = rf.predict_proba(test_w2v)
#If probability for label 1 is over 0.3, it is taken as label 1
w2v_rf_test_pred_int = w2v_rf_test_pred[:,1]>=0.3
w2v_rf_test_pred_int = w2v_rf_test_pred_int.astype(np.int)
#Assigning the predicted values in the label field of test dataset
test['label'] = w2v_rf_test_pred_int
#Updating id and corresponding predicted labels in new csv file
submission = test[['id','label']]
submission.to_csv('rf_w2v.csv', index=False)
#DOC2VEC FEATURES - RANDOM FOREST model
# Training the model with training set from Training dataset and computing training time
start = datetime.now()
rf.fit(xtrain_d2v, ytrain)
stop = datetime.now()
rf_d2v_exec_time = stop - start
# prediction on the validation set from Training dataset
prediction = rf.predict_proba(xvalid_d2v)
#If probability for label 1 is over 0.3, it is taken as label 1
prediction_int = prediction[:,1]>=0.3
prediction_int = prediction_int.astype(np.int)
#calculating f1 score for model performance
d2v_rf_pred_score = f1_score(yvalid, prediction_int)
print("\nF1 SCORE FOR DOC2VEC USING RANDOM FOREST\n")
print(d2v_rf_pred_score)
#Testing the built RANDOM FOREST model on test data
#predicting on test data
d2v_rf_test_pred = rf.predict_proba(test_d2v)
#If probability for label 1 is over 0.3, it is taken as label 1
d2v_rf_test_pred_int = d2v_rf_test_pred[:,1]>=0.3
d2v_rf_test_pred_int = d2v_rf_test_pred_int.astype(np.int)
#Assigning the predicted values in the label field of test dataset
test['label'] = d2v_rf_test_pred_int
#Updating id and corresponding predicted labels in new csv file
submission = test[['id','label']]
submission.to_csv('rf_d2v.csv', index=False)
#######################################################################################################################################################################################################
print("\n\nEXTREME GRADIENT BOOSTING MODEL ACCURACIES\n\n")
#BOW FEATURES - EXTREME GRADIENT BOOSTING model
#Training the model with training set from Training dataset and computing training time
start = datetime.now()
xgb_cl.fit(xtrain_bow, ytrain)
stop = datetime.now()
xgb_bow_exec_time = stop - start
#prediction on the validation set from Training dataset
prediction = xgb_cl.predict_proba(xvalid_bow)
#If probability for label 1 is over 0.3, it is taken as label 1
prediction_int = (prediction[:,1])>=0.3
prediction_int = prediction_int.astype(np.int)
#calculating f1 score for model performance
bow_xgb_pred_score = f1_score(yvalid, prediction_int)
print("\nF1 SCORE FOR BAG OF WORDS USING EXTREME GRADIENT BOOSTING\n")
print(bow_xgb_pred_score)
#Testing the built EXTREME GRADIENT BOOSTING model on test data
#predicting on test data
bow_xgb_test_pred = xgb_cl.predict_proba(test_bow)
#If probability for label 1 is over 0.3, it is taken as label 1
bow_xgb_test_pred_int = (bow_xgb_test_pred[:,1])>=0.3
bow_xgb_test_pred_int = bow_xgb_test_pred_int.astype(np.int)
#Assigning the predicted values in the label field of test dataset
test['label'] = bow_xgb_test_pred_int
#Updating id and corresponding predicted labels in new csv file
submission = test[['id','label']]
submission.to_csv('xgb_bow.csv', index=False)
#TF-IDF FEATURES - EXTREME GRADIENT BOOSTING model
#Training the model with training set from Training dataset and computing training time
start = datetime.now()
xgb_cl.fit(xtrain_tfidf, ytrain)
stop = datetime.now()
xgb_tfidf_exec_time = stop - start
#prediction on the validation set from Training dataset
prediction = xgb_cl.predict_proba(xvalid_tfidf)
#If probability for label 1 is over 0.3, it is taken as label 1
prediction_int = (prediction[:,1])>=0.3
prediction_int = prediction_int.astype(np.int)
#calculating f1 score for model performance
tfidf_xgb_pred_score = f1_score(yvalid, prediction_int)
print("\nF1 SCORE FOR TF-IDF USING EXTREME GRADIENT BOOSTING\n")
print(tfidf_xgb_pred_score)
#Testing the built EXTREME GRADIENT BOOSTING on test data
#predicting on test data
tfidf_xgb_test_pred = xgb_cl.predict_proba(test_tfidf)
#If probability for label 1 is over 0.3, it is taken as label 1
tfidf_xgb_test_pred_int = (tfidf_xgb_test_pred[:,1])>=0.3
tfidf_xgb_test_pred_int = tfidf_xgb_test_pred_int.astype(np.int)
#Assigning the predicted values in the label field of test dataset
test['label'] = tfidf_xgb_test_pred_int
#Updating id and corresponding predicted labels in new csv file
submission = test[['id','label']]
submission.to_csv('xgb_tfidf.csv', index=False)
#WORD2VEC FEATURES - EXTREME GRADIENT BOOSTING model
# Training the model with training set from Training dataset and computing training time
start = datetime.now()
xgb_cl.fit(xtrain_w2v, ytrain)
stop = datetime.now()
xgb_w2v_exec_time = stop - start
# prediction on the validation set from Training dataset
prediction = xgb_cl.predict_proba(xvalid_w2v)
#If probability for label 1 is over 0.3, it is taken as label 1
prediction_int = (prediction[:,1])>=0.3
prediction_int = prediction_int.astype(np.int)
#calculating f1 score for model performance
w2v_xgb_pred_score = f1_score(yvalid, prediction_int)
print("\nF1 SCORE FOR WORD2VEC USING EXTREME GRADIENT BOOSTING\n")
print(w2v_xgb_pred_score)
#Testing the built EXTREME GRADIENT BOOSTING model on test data
#predicting on test data
w2v_xgb_test_pred = xgb_cl.predict_proba(test_w2v)
#If probability for label 1 is over 0.3, it is taken as label 1
w2v_xgb_test_pred_int = (w2v_xgb_test_pred[:,1])>=0.3
w2v_xgb_test_pred_int = w2v_xgb_test_pred_int.astype(np.int)
#Assigning the predicted values in the label field of test dataset
test['label'] = w2v_xgb_test_pred_int
#Updating id and corresponding predicted labels in new csv file
submission = test[['id','label']]
submission.to_csv('xgb_w2v.csv', index=False)
#DOC2VEC FEATURES - EXTREME GRADIENT BOOSTING model
# Training the model with training set from Training dataset and computing training time
start = datetime.now()
xgb_cl.fit(xtrain_d2v, ytrain)
stop = datetime.now()
xgb_d2v_exec_time = stop - start
# prediction on the validation set from Training dataset
prediction = xgb_cl.predict_proba(xvalid_d2v)
#If probability for label 1 is over 0.3, it is taken as label 1
prediction_int = (prediction[:,1])>=0.3
prediction_int = prediction_int.astype(np.int)
#calculating f1 score for model performance
d2v_xgb_pred_score = f1_score(yvalid, prediction_int)
print("\nF1 SCORE FOR DOC2VEC USING EXTREME GRADIENT BOOSTING\n")
print(d2v_xgb_pred_score)
#Testing the built EXTREME GRADIENT BOOSTING model on test data
#predicting on test data
d2v_xgb_test_pred = xgb_cl.predict_proba(test_d2v)
#If probability for label 1 is over 0.3, it is taken as label 1
d2v_xgb_test_pred_int = (d2v_xgb_test_pred[:,1])>=0.3
d2v_xgb_test_pred_int = d2v_xgb_test_pred_int.astype(np.int)
#Assigning the predicted values in the label field of test dataset
test['label'] = d2v_xgb_test_pred_int
#Updating id and corresponding predicted labels in new csv file
submission = test[['id','label']]
submission.to_csv('xgb_d2v.csv', index=False)
###################################################################################################################################################################
#Creating lgb model
lgb_params ={
#specifying laerning objective -> binary classification
'objective':'binary',
#Rate of training
'learningRate':0.1,
#tree depth ; more the depth, more is the complexity
'max_depth':6,
#type of boosting to be performed
'boosting_type':'gbdt',
#No of leaves-> To control complexity
'num_leaves':50,
#Minimum data each leaf may have