-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.py
1449 lines (1155 loc) · 48.1 KB
/
solution.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
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
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC
from nltk.stem.snowball import SnowballStemmer
from nltk.tokenize import word_tokenize
import string
import time
import re
from nltk.stem.wordnet import WordNetLemmatizer
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import label_binarize
from sklearn.metrics import roc_curve, auc, plot_confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.dummy import DummyClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import MultinomialNB
import io
import matplotlib.pyplot as plt
import numpy as np
from nltk.corpus import stopwords as sw
from scipy.sparse import *
TOTREVIEWS = 41077
DEVREVIEWS = 28754
EVALREVIEWS = 12323
""" | ======================================================================================= |
| ======================================================================================= |
| ======================================================================================= |
| -------------------------------------- FUNCTIONS -------------------------------------- |
| ======================================================================================= |
| ======================================================================================= |
V ======================================================================================= V
"""
""" | ======================================================================================= |
| -------------------------------- ALWAYS USED FUNCTIONS -------------------------------- |
V ======================================================================================= V
"""
# prints how many positive and how many negative reviews are in the development dataset
def get(labels):
p = 0
n = 0
for l in labels:
if l == 'pos':
p = p + 1
else:
n = n + 1
print(p)
print(n)
# reads development file and return list of reviews
def readDevfile(fname="../development.csv"):
reviews = []
labels = []
counter = 0
tmpReview = ""
header = True
pos = re.compile(".*,pos\n$")
neg = re.compile(".*,neg\n$")
with io.open(fname, "r", encoding="utf8") as opened_file: # open (use utf-8 due to Emoji
for line in opened_file:
if header:
header = False
continue
if re.match(pos, line) is not None:
tmpReview = tmpReview + line[:-5]
reviews.append(tmpReview)
labels.append("pos")
counter = counter + 1
tmpReview = ""
elif re.match(neg, line) is not None:
tmpReview = tmpReview + line[:-5]
reviews.append(tmpReview)
labels.append("neg")
counter = counter + 1
tmpReview = ""
else:
tmpReview = tmpReview + line
if counter == len(reviews) == len(labels) == DEVREVIEWS:
print(f"Successfully read {counter} reviews")
return reviews, labels
else:
return None, None
# read evaluation file and return list of reviews
def readEvalFile(fname="../evaluation.csv"):
header = True
counter = 0
start1 = re.compile("^\"[^\"].*") # a review can start with " but not followed by another "
start2 = "\"\n" # a review start line can simply be a "\n
start3 = re.compile("^\"\"\"[^\"].*") # a review start line can start with """ but not followed by another "
end1 = re.compile(".*[^\"]\"\n$") # a line can end with "\n but not preceded by another "
end2 = "\"\n" # or it can be: "\n only that on a line
end3 = re.compile(".*[^\"]\"\"\"\n$") # a line can end with """\n but not preceded by another "
status = 0 # ---> # 0. look for a start of a review with start1, start2 or start3
tmpReview = "" # 1. look for an end of a review with a end1, end2, end3
targets = []
with io.open(fname, "r", encoding="utf8") as opened_file: # open (use utf-8 due to Emoji)
for line in opened_file:
counter = counter + 1
# print(f"---line {counter}")
# print("---"+line)
if header:
header = False
continue
if status == 0:
if re.match(start1, line) is not None or re.match(start3, line) is not None or line == start2:
# found review starting regularly with some quotes
# check if it also ends on same line
if re.match(end1, line) is not None or re.match(end3, line):
# entire review is on a line
tmpReview = line
targets.append(tmpReview)
tmpReview = ""
# print("0A: " + str(status) + " staying 0")
continue
# status doesn't change because we want another ordinary review
else:
# start on this line, but ends later
tmpReview = tmpReview + line
# print("0B: " + str(status) + " going to 1")
status = 1
continue
else:
# we were looking for an ordinary review, but it's not
tmpReview = tmpReview + line
targets.append(tmpReview)
tmpReview = ""
# print("0C: " + str(status) + " going to 0")
# status = 2
status = 0
continue
elif status == 1:
# we found the start of an ordinary review and we want its ordinary end
if re.match(end1, line) is not None or re.match(end3, line) is not None or line == end2:
# ordinary end found
tmpReview = tmpReview + line
targets.append(tmpReview)
tmpReview = ""
# print("1A: " + str(status) + " going to 0")
status = 0
continue
else:
# ordinary end not found yet
tmpReview = tmpReview + line
# print("1B: " + str(status) + " staying on 1")
continue
if TOTREVIEWS - DEVREVIEWS == len(targets):
print(f"Successfully read {EVALREVIEWS} reviews")
return targets
else:
return None
# each review is tokenized --> tokens
# each token is split according to a RegEx --> words
def tokenizing(reviews):
size = len(reviews)
tokenizedReviews = []
counter = 0
for rev in reviews:
tokenized_rev = word_tokenize(rev, language="italian")
new_rev = []
for token in tokenized_rev:
s = re.compile(",|\.|'|!|`|\(|\)|/|:|;|&|%|\"|=|\?|@|\^|“|”|\\|_|…").split(token)
for word in s:
new_rev.append(word.strip().lower())
tokenizedReviews.append(new_rev)
counter = counter + 1
print("\rComputing... " + str(int((counter / size) * 100)) + "%", end="", flush=True)
if DEVREVIEWS == len(tokenizedReviews) or EVALREVIEWS == len(tokenizedReviews):
print()
print(f"Successfully tokenized {len(tokenizedReviews)} reviews")
print()
return tokenizedReviews
else:
return None
# starting from the reviews in the shape of list of words
# --> remove all the words that are strictly shorter than given threshold
def clean(tokenizedReviews, threshold=2):
# remove the words with len<=2 (default)
size = len(tokenizedReviews)
counter = 0
wordcount = 0
remcount = 0
for rev in tokenizedReviews:
for word in rev:
wordcount = wordcount + 1
if len(word) <= threshold:
remcount = remcount + 1
rev.remove(word)
counter = counter + 1
print("\rComputing... " + str(int((counter / size) * 100)) + "%", end="", flush=True)
print()
print(f"Scanned {wordcount} words, removed {remcount}, remaining: {wordcount-remcount}")
print()
return tokenizedReviews
# each word is stemmed and a new version of the review is created --> list of stemmed words
def stemming(reviews):
size = len(reviews)
stemmedReviews = []
stemmer = SnowballStemmer("italian")
counter = 0
for rev in reviews:
new_rev = []
for word in rev:
word = stemmer.stem(word)
new_rev.append(word)
stemmedReviews.append(new_rev)
counter = counter + 1
print("\rComputing... " + str(int((counter / size) * 100)) + "%", end="", flush=True)
if DEVREVIEWS == len(stemmedReviews) or EVALREVIEWS == len(stemmedReviews):
print()
print(f"Successfully stemmed {len(stemmedReviews)} reviews")
print()
return stemmedReviews
else:
return None
# generate the list of stopwords and stem them:
# - most frequent words from frequency document (with freq higher than threshold)
# - nltk italian stopwords
# - some symbols (that should not be among the words)
# - from the first two lists remove some meaningful words
def getStopwordlist(filename="stopwordsStemImproved.txt", threshold=15000):
stpw = sw.words("italian")
toKeep = ['quanta', 'avrò', 'aveste', 'avessero', 'sareste', 'fui', 'fareste', 'farebbero', 'feci', 'facemmo',
'facessero', 'stiano', 'staremmo', 'stessero', 'con', 'contro', 'perché', 'non', 'più', 'piu']
toKeep = ['quanta', 'avrò', 'avessero', 'farebbero', 'feci', 'facessero', 'stiano', 'stessero', 'non'] # best
for w in toKeep:
if w in stpw:
stpw.remove(w)
symb = [' ', ',', '.', "'", "!", "`", "(", ")", "/", ":", ";", "&", "%", '"', "=", "?", "@", "^", "“", "”", "\\",
"_", "…", "-", "[", "]", "{", "}"]
for w in symb:
stpw.append(w)
with io.open(filename, "r", encoding="utf8") as opened_file: # open (use utf-8 due to Emoji
# skipped = 0
for line in opened_file:
pcs = line.split()
if len(pcs) != 2: # skip lines not well formatted
# skipped = skipped + 1
continue
if int(pcs[1]) > threshold: # not including here the ones with frequency=1, removed by tfidf vectorizer
if len(pcs[0]) > 2: # with length 2 or less are already removed in main()
stpw.append(pcs[0])
# print(f"Skipped {skipped} lines")
toKeep = ['non', 'ottim', 'buon', 'posizion', 'pul', 'serviz', 'dispon', 'bell', 'ben'] # fill it! (11000)
for w in toKeep:
if w in stpw:
stpw.remove(w)
return stemStopwords(stpw)
# stem the stop words in order to have them matching the stems in the reviews (that are stemmed in the same way)
def stemStopwords(stopwords):
size = len(stopwords)
stemmed = []
stemmer = SnowballStemmer("italian")
for w in stopwords:
stemmed.append(stemmer.stem(w))
print("lost stopwords: " + str(size-len(stemmed)))
return stemmed
# rebuild the reviews
# --> from a list of stemmed words to a single string (for each review)
def assemble(reviews):
size = len(reviews)
# rebuild reviews
processedReviews = []
counter = 0
for rev in reviews:
tmpReview = ""
for word in rev:
if word != '':
tmpReview = tmpReview + word + " "
processedReviews.append(tmpReview)
counter = counter + 1
print("\rComputing... " + str(int((counter / size) * 100)) + "%", end="", flush=True)
print()
print(f"Re-assembled {counter} reviwes ({size-counter} missing)")
print()
return processedReviews
# explore a range of C values
# get the F1_weighted score from cross validation with 20 folds
def tuneC(tfidf_X, labels):
print("==========CROSS-VALIDATION START==========")
print("--- Cross validating for C parameter:")
start =0.2 # 0.1 # 0.150
stop = 1 # 10 # 0.6
step = 0.001 # 1 # 0.001
cRange = np.arange(start, stop, step)
minim = np.zeros(np.shape(cRange))
maxim = np.zeros(np.shape(cRange))
avg = np.zeros(np.shape(cRange))
cnt = 0
for c in cRange:
svcTest = LinearSVC(dual=False, max_iter=10000, C=c)
# cross val F1 score weighed
outcome = cross_val_score(svcTest, tfidf_X, labels, cv=20, scoring='f1_weighted')
avg[cnt] = np.mean(outcome)
minim[cnt] = np.min(outcome)
maxim[cnt] = np.max(outcome)
cnt = cnt + 1
print("\rComputing... " + str(int((cnt / ((stop - start) / step)) * 100)) + "%", end="", flush=True)
print()
fig, ax = plt.subplots(figsize=(7, 5))
ax.plot(cRange, minim, c='red', label='min(f1_weighted) of cross validation')
ax.plot(cRange, maxim, c='green', label='max (f1_weighted) of cross validation')
ax.plot(cRange, avg, c='blue', label='avg (f1_weighted) of cross validation')
plt.xlabel('C range')
plt.ylabel('F1 score')
plt.title('F1 score varying with C')
plt.legend(loc="lower right")
ax.legend()
plt.show()
print("==========CROSS-VALIDATION END==========")
print()
return
# explore a range of max_iteration values
# get the F1_weighted score from cross validation with 20 folds
def tuneMaxIter(tfidf_X, labels):
print("==========CROSS-VALIDATION START==========")
print("--- Cross validating for max_iter parameter:")
start = 1
stop = 10
step = 1
itRange = np.arange(start, stop, step)
minim = np.zeros(np.shape(itRange))
maxim = np.zeros(np.shape(itRange))
avg = np.zeros(np.shape(itRange))
cnt = 0
for it in itRange:
svcTest = LinearSVC(dual=False, max_iter=it, C=0.3125)
outcome = cross_val_score(svcTest, tfidf_X, labels, cv=20, scoring='f1_weighted')
avg[cnt] = np.mean(outcome)
minim[cnt] = np.min(outcome)
maxim[cnt] = np.max(outcome)
cnt = cnt + 1
print("\rComputing... " + str(int((cnt / ((stop - start) / step)) * 100)) + "%", end="", flush=True)
print()
fig, ax = plt.subplots(figsize=(7, 5))
ax.plot(itRange, minim, c='red', label='min')
ax.plot(itRange, maxim, c='green', label='max')
ax.plot(itRange, avg, c='blue', label='avg')
plt.xlabel('max_iterations')
plt.ylabel('F1 score')
plt.title('F1 score varying with max_iterations')
plt.legend(loc="lower right")
ax.legend()
plt.show()
print("==========CROSS-VALIDATION END==========")
print()
return
# print the ROCs of the two classes 'pos' and 'neg' only
def generateROC(tfidf_X, labels):
print("==========ROC CURVE START==========")
print("--- Printing ROC curve:")
y = label_binarize(labels, classes=['pos', 'neg'])
# print(y)
x_train, x_test, y_train, y_test = train_test_split(tfidf_X, y, test_size=0.05)
svcTest = LinearSVC(dual=False, max_iter=10000, C=0.3125)
svcTest.fit(x_train, y_train)
y_score = svcTest.predict(x_test) # y_test = ground truth | y_score = predicted
y_test_shped = np.zeros((np.size(y_test), 2), dtype=int)
counter = 0
for lab in y_test:
if lab == 0:
y_test_shped[counter, 0] = 1
else:
y_test_shped[counter, 1] = 1
counter = counter + 1
# print(y_test_shped)
y_score_shped = np.zeros((np.size(y_score), 2), dtype=int)
counter = 0
for lab in y_score:
if lab == 0:
y_score_shped[counter, 0] = 1
else:
y_score_shped[counter, 1] = 1
counter = counter + 1
# print(y_score_shped)
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(2): # 2 classes
fpr[i], tpr[i], _ = roc_curve(y_test_shped[:, i], y_score_shped[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
fpr["micro"], tpr["micro"], _ = roc_curve(y_test_shped.ravel(), y_score_shped.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
plt.figure()
lw = 2
colors = ['darkorange', 'red']
classes = ['pos', 'neg']
for i, color in zip(range(2), colors):
plt.plot(fpr[i], tpr[i], color=color, lw=lw,
label='ROC curve of class {0} (area = {1:0.2f})'.format(classes[i], roc_auc[i]))
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic (ROC) curve')
plt.legend(loc="lower right")
plt.show()
print("==========ROC CURVE END==========")
print()
return
# print the confusion matrix only
def generateConfMatrix(tfidf_X, labels):
print("==========CONFUSION MATRIX START==========")
print("--- Generating confusion matrix:")
y = label_binarize(labels, classes=['pos', 'neg'])
print(y)
x_train, x_test, y_train, y_test = train_test_split(tfidf_X, y, test_size=0.15)
svcTest = LinearSVC(dual=False, max_iter=10000, C=0.3125)
svcTest.fit(x_train, y_train)
disp = plot_confusion_matrix(svcTest, x_test, y_test, normalize=None, display_labels=['pos', 'neg'])
disp.ax_.set_title("Confusion matrix not normalized")
print("--- Confusion matrix not normalized:")
print(disp.confusion_matrix)
plt.show()
print("==========CONFUSION MATRIX END==========")
print()
return
# prints ROCs for the two classes and confusion matrix (on same data)
def generateConfMatrixAndROC(tfidf_X, labels):
print("==========ROC CURVE AND CONFUSION MATRIX START==========")
y = label_binarize(labels, classes=['pos', 'neg'])
# print(y)
x_train, x_test, y_train, y_test = train_test_split(tfidf_X, y, test_size=0.05)
svcTest = LinearSVC(dual=False, max_iter=10000, C=0.3125)
svcTest.fit(x_train, y_train)
y_score = svcTest.predict(x_test) # y_test = ground truth | y_score = predicted
disp = plot_confusion_matrix(svcTest, x_test, y_test, normalize=None, display_labels=['pos', 'neg'])
disp.ax_.set_title("Confusion matrix not normalized")
print("--- Confusion matrix not normalized:")
print(disp.confusion_matrix)
print()
plt.show()
print("--- Printing ROC curve")
y_test_shped = np.zeros((np.size(y_test), 2), dtype=int)
counter = 0
for lab in y_test:
if lab == 0:
y_test_shped[counter, 0] = 1
else:
y_test_shped[counter, 1] = 1
counter = counter + 1
# print(y_test_shped)
y_score_shped = np.zeros((np.size(y_score), 2), dtype=int)
counter = 0
for lab in y_score:
if lab == 0:
y_score_shped[counter, 0] = 1
else:
y_score_shped[counter, 1] = 1
counter = counter + 1
# print(y_score_shped)
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(2): # 2 classes
fpr[i], tpr[i], _ = roc_curve(y_test_shped[:, i], y_score_shped[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
fpr["micro"], tpr["micro"], _ = roc_curve(y_test_shped.ravel(), y_score_shped.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
plt.figure()
lw = 2
colors = ['darkorange', 'red']
classes = ['pos', 'neg']
for i, color in zip(range(2), colors):
plt.plot(fpr[i], tpr[i], color=color, lw=lw,
label='ROC curve of class {0} (area = {1:0.2f})'.format(classes[i], roc_auc[i]))
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic (ROC) curve')
plt.legend(loc="lower right")
plt.show()
print("done")
print("==========ROC CURVE AND CONFUSION MATRIX END==========")
print()
return
# prints the chart with the comparison of many ROCs of different classifiers
def compareClassifiers(tfidf_X, labels):
print("==========MODEL COMPARISON START==========")
print("--- Printing ROC curves:")
y = label_binarize(labels, classes=['pos', 'neg'])
# print(y)
x_train, x_test, y_train, y_test = train_test_split(tfidf_X, y, test_size=0.05)
svcTest = LinearSVC(dual=False, max_iter=10000, C=0.3125)
randForest = RandomForestClassifier(n_jobs=5)
ruleBased = DummyClassifier(strategy='stratified')
knn = KNeighborsClassifier()
cnb = MultinomialNB()
decTree = DecisionTreeClassifier()
# 1. SVC
svcTest.fit(x_train, y_train)
y_score = svcTest.predict(x_test) # y_test = ground truth | y_score = predicted
y_test_shped = np.zeros((np.size(y_test), 2), dtype=int)
counter = 0
for lab in y_test:
if lab == 0:
y_test_shped[counter, 0] = 1
else:
y_test_shped[counter, 1] = 1
counter = counter + 1
# print(y_test_shped)
y_score_shped = np.zeros((np.size(y_score), 2), dtype=int)
counter = 0
for lab in y_score:
if lab == 0:
y_score_shped[counter, 0] = 1
else:
y_score_shped[counter, 1] = 1
counter = counter + 1
# print(y_score_shped)
fpr = dict()
tpr = dict()
roc_auc = dict()
fpr[0], tpr[0], _ = roc_curve(y_test_shped[:, 0], y_score_shped[:, 0])
roc_auc[0] = auc(fpr[0], tpr[0])
fpr["micro"], tpr["micro"], _ = roc_curve(y_test_shped.ravel(), y_score_shped.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
plt.figure()
lw = 2
color = 'darkorange'
plt.plot(fpr[0], tpr[0], color=color, lw=lw, label='ROC curve SVC (area = {0:0.2f})'.format(roc_auc[0]))
# 2. Random forest
randForest.fit(x_train, y_train)
y_score = randForest.predict(x_test)
y_test_shped = np.zeros((np.size(y_test), 2), dtype=int)
counter = 0
for lab in y_test:
if lab == 0:
y_test_shped[counter, 0] = 1
else:
y_test_shped[counter, 1] = 1
counter = counter + 1
# print(y_test_shped)
y_score_shped = np.zeros((np.size(y_score), 2), dtype=int)
counter = 0
for lab in y_score:
if lab == 0:
y_score_shped[counter, 0] = 1
else:
y_score_shped[counter, 1] = 1
counter = counter + 1
# print(y_score_shped)
fpr = dict()
tpr = dict()
roc_auc = dict()
fpr[0], tpr[0], _ = roc_curve(y_test_shped[:, 0], y_score_shped[:, 0])
roc_auc[0] = auc(fpr[0], tpr[0])
fpr["micro"], tpr["micro"], _ = roc_curve(y_test_shped.ravel(), y_score_shped.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
lw = 2
color = 'red'
plt.plot(fpr[0], tpr[0], color=color, lw=lw, label='ROC curve of Random Forest (area = {0:0.2f})'.format(roc_auc[0]))
# 3. Rule based classifier
decTree.fit(x_train, y_train)
y_score = decTree.predict(x_test)
y_test_shped = np.zeros((np.size(y_test), 2), dtype=int)
counter = 0
for lab in y_test:
if lab == 0:
y_test_shped[counter, 0] = 1
else:
y_test_shped[counter, 1] = 1
counter = counter + 1
# print(y_test_shped)
y_score_shped = np.zeros((np.size(y_score), 2), dtype=int)
counter = 0
for lab in y_score:
if lab == 0:
y_score_shped[counter, 0] = 1
else:
y_score_shped[counter, 1] = 1
counter = counter + 1
# print(y_score_shped)
fpr = dict()
tpr = dict()
roc_auc = dict()
fpr[0], tpr[0], _ = roc_curve(y_test_shped[:, 0], y_score_shped[:, 0])
roc_auc[0] = auc(fpr[0], tpr[0])
fpr["micro"], tpr["micro"], _ = roc_curve(y_test_shped.ravel(), y_score_shped.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
lw = 2
color = 'green'
plt.plot(fpr[0], tpr[0], color=color, lw=lw, label='ROC curve of Decision tree classifier (area = {0:0.2f})'.format(roc_auc[0]))
# 4. K-NN
knn.fit(x_train, y_train)
y_score = knn.predict(x_test)
y_test_shped = np.zeros((np.size(y_test), 2), dtype=int)
counter = 0
for lab in y_test:
if lab == 0:
y_test_shped[counter, 0] = 1
else:
y_test_shped[counter, 1] = 1
counter = counter + 1
# print(y_test_shped)
y_score_shped = np.zeros((np.size(y_score), 2), dtype=int)
counter = 0
for lab in y_score:
if lab == 0:
y_score_shped[counter, 0] = 1
else:
y_score_shped[counter, 1] = 1
counter = counter + 1
# print(y_score_shped)
fpr = dict()
tpr = dict()
roc_auc = dict()
fpr[0], tpr[0], _ = roc_curve(y_test_shped[:, 0], y_score_shped[:, 0])
roc_auc[0] = auc(fpr[0], tpr[0])
fpr["micro"], tpr["micro"], _ = roc_curve(y_test_shped.ravel(), y_score_shped.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
lw = 2
color = 'blue'
plt.plot(fpr[0], tpr[0], color=color, lw=lw, label='ROC curve of K-NN (area = {0:0.2f})'.format(roc_auc[0]))
# 5. Naive Bayes
cnb.fit(x_train, y_train)
y_score = cnb.predict(x_test)
y_test_shped = np.zeros((np.size(y_test), 2), dtype=int)
counter = 0
for lab in y_test:
if lab == 0:
y_test_shped[counter, 0] = 1
else:
y_test_shped[counter, 1] = 1
counter = counter + 1
# print(y_test_shped)
y_score_shped = np.zeros((np.size(y_score), 2), dtype=int)
counter = 0
for lab in y_score:
if lab == 0:
y_score_shped[counter, 0] = 1
else:
y_score_shped[counter, 1] = 1
counter = counter + 1
# print(y_score_shped)
fpr = dict()
tpr = dict()
roc_auc = dict()
fpr[0], tpr[0], _ = roc_curve(y_test_shped[:, 0], y_score_shped[:, 0])
roc_auc[0] = auc(fpr[0], tpr[0])
fpr["micro"], tpr["micro"], _ = roc_curve(y_test_shped.ravel(), y_score_shped.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
lw = 2
color = 'darkturquoise'
plt.plot(fpr[0], tpr[0], color=color, lw=lw, label='ROC curve of Naive Bayes (area = {0:0.2f})'.format(roc_auc[0]))
# conclude plot
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Classifiers comparison (ROC curves)')
plt.legend(loc="lower right")
plt.show()
print("==========MODEL COMPARISON END==========")
print()
return
""" | ======================================================================================= |
| ----- NOT USED AT EACH RUN, BUT USED IN DATA EXPLORATION AT DEVELOPMENT BEGINNING ----- |
V ======================================================================================= V
"""
# W.I.P. --> decide if use Stemmer, Lemmatizer or an hybrid (right now this is hybrid)
class LemmaTokenizer(object):
def __init__(self):
self.lemmatizer = WordNetLemmatizer()
self.stemmer = SnowballStemmer("italian")
def __call__(self, document):
lemmas = []
re_digit = re.compile("[0-9]") # regular expression to filter digit, tokens
for t in word_tokenize(document, language="italian"):
t = t.strip()
lemma = self.lemmatizer.lemmatize(t)
# remove tokens with only punctuation chars and digits
if lemma not in string.punctuation and len(lemma) > 1 and len(lemma) < 16 and not re_digit.match(lemma):
lemmas.append(self.stemmer.stem(lemma))
return lemmas
# Function for the creation of a file with each word and its frequency formatted as: word freq\n
# it builds it from both the documents
def printStopwordsFile():
print("==========WORD FREQUENCY FILE CREATION START==========")
print("---------- {developmentImproved.csv} ----------")
with io.open("../developmentImproved.csv", "r", encoding="utf8") as opened_file: # open (use utf-8 due to Emoji
development = opened_file.read() # read entire file content
print("---------- {evaluationImproved.csv} ----------")
with open("../evaluationImproved.csv", encoding="utf8") as opened_file: # open (use utf-8 due to Emoji
evaluation = opened_file.read() # read entire file content
method = 1
# 1: tokenize with nltk.word_tokenizer and use the italian snowball stemmer (seems to be better for now)
# 2: use the nltk wordnet lemmatizer
if method == 1:
# method 1
allTokens = word_tokenize(development, language="italian")
tokenDict = {}
stemmer = SnowballStemmer("italian")
print("File 1 ...")
stat = 0
for t in allTokens:
t = t.lower().strip()
s = re.compile(",|\.|'|!|`|\(|\)|/|:|;|&|%|\"|=|\?|@|\^|“|”|\\|_|…").split(t)
stat = stat + len(s) - 1
for r in s:
r = stemmer.stem(r)
if r in tokenDict.keys():
tokenDict[r] = tokenDict[r]+1
else:
tokenDict[r] = 1
print("File 2 ...")
allTokens = word_tokenize(evaluation, language="italian")
for t in allTokens:
t = t.lower().strip()
s = re.compile(",|\.|'|!|`|\(|\)|/|:|;|&|%|\"|=|\?|@|\^|“|”|\\|_|…").split(t)
stat = stat + len(s) - 1
for r in s:
r = stemmer.stem(r)
if r in tokenDict.keys():
tokenDict[r] = tokenDict[r] + 1
else:
tokenDict[r] = 1
print("Finalising ...")
# Converting into list of tuple
listTknCnt = [(k, v) for k, v in tokenDict.items()]
# sorting
listTknCnt.sort(key=lambda x: x[1], reverse=True)
# print into a file
with io.open("stopwordsStemImproved.txt", "w", encoding="utf8") as f:
for k, v in listTknCnt:
f.write(str(k) + " " + str(v) + "\n")
print("Additional splits: "+str(stat))
else:
# method 2
tokenDict = {}
print("File 1 ...")
tokenizer = LemmaTokenizer()
allTokens2 = tokenizer(development)
stat = 0
for t in allTokens2:
t = t.lower().strip()
s = re.compile(",|\.|'|!|`|\(|\)|/|:|;|&|%|\"|=|\?|@|\^|“|”|\\|_|…").split(t)
stat = stat + len(s) - 1
for r in s:
if r in tokenDict.keys():
tokenDict[r] = tokenDict[r] + 1
else:
tokenDict[r] = 1
print("File 2 ...")
allTokens2 = tokenizer(evaluation)
for t in allTokens2:
t = t.lower().strip()
s = re.compile(",|\.|'|!|`|\(|\)|/|:|;|&|%|\"|=|\?|@|\^|“|”|\\|_|…").split(t)
stat = stat + len(s) - 1
for r in s:
if r in tokenDict.keys():
tokenDict[r] = tokenDict[r] + 1
else:
tokenDict[r] = 1
print("Finalising ...")
# Converting into list of tuple
listTknCnt = [(k, v) for k, v in tokenDict.items()]
# sorting
listTknCnt.sort(key=lambda x: x[1], reverse=True)
# print into a file
with io.open("stopwordsStemImproved.txt", "w", encoding="utf8") as f:
for k, v in listTknCnt:
f.write(str(k) + " " + str(v) + "\n")
print("Additional splits: " + str(stat))
print("==========WORD FREQUENCY FILE CREATION START==========")
# function that looks for a substring (lookfor) inside the reviews
# returns how many times it appears in positive and negative reviews
def explore(lookfor, reviews, labels, ratio=False):
pos = 0
neg = 0
c = 0
for i in reviews:
if lookfor in i:
if labels[c] == 'pos':
pos = pos + i.lower().count(lookfor)
elif labels[c] == 'neg':
neg = neg + i.lower().count(lookfor)
else:
print("OPS")
c = c + 1
if ratio:
if pos+neg != 0 and (pos/(pos+neg)>=0.7 or pos/(pos+neg)<=0.3):
print(lookfor + " " + str(pos / (pos + neg)))
return lookfor
else:
return None
else:
print("String: "+lookfor)
print("#pos: "+str(pos))
print("#neg: "+str(neg))
# function to plot the density of the words starting from the word frequency file (filename)
# on x-axis: the frequency of a word
# on y-axis: how many words there are with that frequency
# start: from which freq start to plot
# end: up to which freq to plot
def plotStopwordsDensityDistribution(start, end, filename="stopwordsStemImproved.txt"):
fig, ax = plt.subplots(figsize=(7, 5))
firstTime = True
x = None
y = None