-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.py
2465 lines (2084 loc) · 96.8 KB
/
util.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
# -*- coding: utf-8 -*-
"""This is a helper module with utility classes and functions."""#这是一个包含实用程序类和函数的助手模块
from __future__ import print_function
from io import open
from os import listdir, makedirs, path, remove as remove_file
from os import walk
from sys import version_info
from tqdm import tqdm
from math import ceil
from itertools import product
from collections import defaultdict
from numpy import mean, linspace, arange
from sklearn.metrics import classification_report, accuracy_score, hamming_loss
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import StratifiedKFold
from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
import numpy as np
import unicodedata
import webbrowser
import errno
import json
import re
import warnings
try:
from sklearn.metrics import multilabel_confusion_matrix
except ImportError:
print("\033[93m* Your Scikit-learn version does not include `multilabel_confusion_matrix()`.\n"
"* Update Scikit-learn in case you want to work with multi-label classification.\033[0m")
def multilabel_confusion_matrix(*args):
"""Dummy version of multilabel_confusion_matrix."""
return np.array([])
ENCODING = "utf-8"
REGEX_DATE = re.compile(
r"(?:\d+([.,]\d+)?[-/\\]\d+([.,]\d+)?[-/\\]\d+([.,]\d+)?)"
)
REGEX_TEMP = re.compile(
r"(?:\d+([.,]\d+)?\s*(\xc2[\xb0\xba])?\s*[CcFf](?=[^a-zA-Z]))"
)
REGEX_MONEY = re.compile(r"(?:\$\s*\d+([.,]\d+)?)")
REGEX_PERCENT = re.compile(r"(?:\d+([.,]\d+)?\s*%)")
REGEX_NUMBER = re.compile(r"(?:\d+([.,]\d+)?)")
REGEX_DOTS_CHARS = re.compile(r"(?:([(),;:?!=\"/.|<>\[\]]+)|(#(?![a-zA-Z])))")
REGEX_DOTS_CHAINED = re.compile(r"(?:(#[a-zA-Z0-9]+)(\s)*(?=#))")
EVAL_HTML_OUT_FILE = "ss3_model_evaluation[%s].html"
EVAL_HTML_SRC_FOLDER = "resources/evaluation_plot/"
EVAL_CACHE_EXT = ".ss3ev"
STR_ACCURACY, STR_PRECISION = "accuracy", "precision"
STR_RECALL, STR_F1 = "recall", "f1-score"
STR_HAMMING_LOSS, STR_EXACT_MATCH = "hamming-loss", "exact-match"
GLOBAL_METRICS = [STR_ACCURACY, STR_HAMMING_LOSS, STR_EXACT_MATCH]
METRICS = [STR_PRECISION, STR_RECALL, STR_F1]
EXCP_METRICS = GLOBAL_METRICS + ["confusion_matrix", "categories"]
AVGS = ["micro avg", "macro avg", "weighted avg", "samples avg"]
STR_TEST, STR_FOLD = 'test', 'fold'
STR_MOST_PROBABLE = "most-probable"
ERROR_NAM = "'%s' is not a valid metric " + "(excepted: %s)" % (
", ".join(["'%s'" % m for m in [STR_ACCURACY] + METRICS])
)
ERROR_NAT = "'%s' is not a valid target "
ERROR_NAT += "(excepted: %s or a category label)" % (", ".join(["'%s'" % a for a in AVGS]))
ERROR_CNE = "the classifier has not been evaluated yet"
ERROR_CNA = ("a classifier has not yet been assigned "
"(try using `Evaluation.set_classifier(clf)`)")
ERROR_IKV = "`k_fold` argument must be an integer greater than or equal to 2"
ERROR_IKT = "`k_fold` argument must be an integer"
ERROR_INGV = "`n_grams` argument must be a positive integer"
ERROR_IHV = "hyperparameter values must be numbers"
PY2 = version_info[0] == 2
if not PY2:
basestring = None # to avoid the Flake8 "F821 undefined name" error
# a more user-friendly alias for numpy.linspace
# to be used along with grid_search
span = linspace
frange = arange
class VERBOSITY:
"""verbosity "enum" constants."""
QUIET = 0
NORMAL = 1
VERBOSE = 2
class Evaluation:
"""
Evaluation class.
This class provides the user easy-to-use methods for model evaluation and
hyperparameter optimization, like, for example, the ``Evaluation.test``,
``Evaluation.kfold_cross_validation``, ``Evaluation.grid_search``,
``Evaluation.plot`` methods for performing tests, stratified k-fold cross
validations, grid searches for hyperparameter optimization, and
visualizing evaluation results using an interactive 3D plot, respectively.
All the evaluation methods provided by this class internally use a cache
mechanism in which all the previously computed evaluation will be
permanently stored for later use. This will prevent the user to waste time
performing the same evaluation more than once, or, in case of computer
crashes or power failure during a long evaluation, once relunched, it will
skip previously computed values and continue the evaluation from the point
were the crashed happened on.
Usage:
>>> from util import Evaluation
For examples usages for the previously mentioned method, read their
documentation, or do one of the tutorials.
"""
__cache__ = None
__cache_file__ = None
__clf__ = None
__last_eval_tag__ = None
__last_eval_method__ = None
__last_eval_def_cat__ = None
@staticmethod
def __kfold2method__(k_fold):
"""Convert the k number to a proper method string."""
return STR_TEST if not k_fold or k_fold <= 1 else str(k_fold) + '-' + STR_FOLD
@staticmethod
def __set_last_evaluation__(tag, method, def_cat):
"""Save the last evaluation tag, method, and default category."""
Evaluation.__last_eval_tag__ = tag
Evaluation.__last_eval_method__ = method
Evaluation.__last_eval_def_cat__ = def_cat
@staticmethod
def __get_last_evaluation__():
"""Return the tag, method and default category used in the last evaluation."""
if Evaluation.__last_eval_tag__:
return Evaluation.__last_eval_tag__, \
Evaluation.__last_eval_method__, \
Evaluation.__last_eval_def_cat__
elif Evaluation.__cache__:
tag = list(Evaluation.__cache__)[0]
method = list(Evaluation.__cache__[tag])[0]
def_cat = list(Evaluation.__cache__[tag][method])[0]
return tag, method, def_cat
else:
return None, None, None
@staticmethod
def __cache_json_hook__(dct):
"""Convert a given dictionary to a RecursiveDefaultDict."""
c_ddct = RecursiveDefaultDict()
for key in dct.keys():
try:
c_ddct[float(key)] = dct[key]
except ValueError:
c_ddct[key] = dct[key]
return c_ddct
@staticmethod
def __cache_load__():
"""Load evaluations from disk."""
if not Evaluation.__cache__:
Print.info("loading evaluations from cache")
clf = Evaluation.__clf__
empty_cache = False
if clf:
try:
with open(Evaluation.__cache_file__, "r", encoding=ENCODING) as json_file:
Evaluation.__cache__ = json.loads(
json_file.read(),
object_hook=Evaluation.__cache_json_hook__
)
except IOError:
empty_cache = True
else:
empty_cache = True
if empty_cache:
Print.info("no evaluation results found, creating a new empty cache")
Evaluation.__cache__ = RecursiveDefaultDict()
@staticmethod
def __cache_update__():
"""Save cached values (evaluations) to disk."""
clf = Evaluation.__clf__
if not clf:
return
Print.info("updating evaluations cache")
with open(Evaluation.__cache_file__, "w", encoding=ENCODING) as json_file:
try: # Python 3
json_file.write(json.dumps(Evaluation.__cache__))
except TypeError: # Python 2
json_file.write(json.dumps(Evaluation.__cache__).decode(ENCODING))
@staticmethod
def __cache_save_result__(
cache, categories, accuracy, report, conf_matrix, k_fold, i_fold,
s, l, p, a, hamming_loss=None
):
"""Compute, update and finally save evaluation results to disk."""
rf = round_fix
s, l = rf(s), rf(l)
p, a = rf(p), rf(a)
cache["categories"] = categories
# if there aren't previous best results, initialize them to -1
if cache["accuracy"]["best"]["value"] == {}:
cache["accuracy"]["best"]["value"] = -1
if hamming_loss is not None:
cache["hamming-loss"]["best"]["value"] = -1
for metric, avg in product(METRICS, AVGS):
if avg in report: # scikit-learn > 0.20 does not include 'micro avg' in report
cache[metric][avg]["best"]["value"] = -1
for cat in categories:
for metric in METRICS:
cache[metric]["categories"][cat]["best"]["value"] = -1
# if fold results array is empty, create new ones
if cache["accuracy"]["fold_values"][s][l][p][a] == {}:
cache["accuracy"]["fold_values"][s][l][p][a] = [0] * k_fold
if hamming_loss is not None:
cache["hamming-loss"]["fold_values"][s][l][p][a] = [0] * k_fold
cache["confusion_matrix"][s][l][p][a] = [None] * k_fold
for metric, avg in product(METRICS, AVGS):
if avg in report:
cache[metric][avg]["fold_values"][s][l][p][a] = [0] * k_fold
for cat in categories:
for metric in METRICS:
cache[metric]["categories"][cat]["fold_values"][s][l][p][a] = [0] * k_fold
# saving fold results
cache["accuracy"]["fold_values"][s][l][p][a][i_fold] = rf(accuracy)
if hamming_loss is not None:
cache["hamming-loss"]["fold_values"][s][l][p][a][i_fold] = rf(1 - hamming_loss)
for metric, avg in product(METRICS, AVGS):
if avg in report:
cache[metric][avg]["fold_values"][s][l][p][a][i_fold] = rf(report[avg][metric])
for cat in categories:
for metric in METRICS:
cache[metric]["categories"][cat]["fold_values"][s][l][p][a][i_fold] = rf(
report[cat][metric]
)
cache["confusion_matrix"][s][l][p][a][i_fold] = conf_matrix.tolist()
# if this is the last fold, compute and store averages and best values
if i_fold + 1 == k_fold:
accuracy_avg = rf(mean(cache["accuracy"]["fold_values"][s][l][p][a]))
cache["accuracy"]["value"][s][l][p][a] = accuracy_avg
best_acc = cache["accuracy"]["best"]
if accuracy_avg > best_acc["value"]:
best_acc["value"] = accuracy_avg
best_acc["s"], best_acc["l"] = s, l
best_acc["p"], best_acc["a"] = p, a
if hamming_loss is not None:
hamloss_avg = rf(mean(cache["hamming-loss"]["fold_values"][s][l][p][a]))
cache["hamming-loss"]["value"][s][l][p][a] = hamloss_avg
best_haml = cache["hamming-loss"]["best"]
if hamloss_avg > best_haml["value"]:
best_haml["value"] = hamloss_avg
best_haml["s"], best_haml["l"] = s, l
best_haml["p"], best_haml["a"] = p, a
for metric, avg in product(METRICS, AVGS):
if avg in report:
metric_avg = rf(mean(cache[metric][avg]["fold_values"][s][l][p][a]))
cache[metric][avg]["value"][s][l][p][a] = metric_avg
best_metric_avg = cache[metric][avg]["best"]
if metric_avg > best_metric_avg["value"]:
best_metric_avg["value"] = metric_avg
best_metric_avg["s"], best_metric_avg["l"] = s, l
best_metric_avg["p"], best_metric_avg["a"] = p, a
for cat in categories:
for metric in METRICS:
metric_cat_avg = rf(mean(
cache[metric]["categories"][cat]["fold_values"][s][l][p][a]
))
cache[metric]["categories"][cat]["value"][s][l][p][a] = metric_cat_avg
best_metric_cat = cache[metric]["categories"][cat]["best"]
if metric_cat_avg > best_metric_cat["value"]:
best_metric_cat["value"] = metric_cat_avg
best_metric_cat["s"], best_metric_cat["l"] = s, l
best_metric_cat["p"], best_metric_cat["a"] = p, a
Evaluation.__cache_update__()
@staticmethod
def __cache_is_in__(tag, method, def_cat, s, l, p, a):
"""Return whether this evaluation is already cached."""
s, l = round_fix(s), round_fix(l)
p, a = round_fix(p), round_fix(a)
results = Evaluation.__cache_get_evaluations__(tag, method, def_cat)
return results["accuracy"]["value"][s][l][p][a] != {}
@staticmethod
def __cache_get_test_evaluation__(tag, def_cat, s, l, p, a):
"""Return test results from the cache storage."""
s, l = round_fix(s), round_fix(l)
p, a = round_fix(p), round_fix(a)
if Evaluation.__cache_is_in__(tag, STR_TEST, def_cat, s, l, p, a):
Print.info("retrieving test evaluation from cache")
y_true = []
y_pred = []
cache = Evaluation.__cache_get_evaluations__(tag, STR_TEST, def_cat)
cm = np.array(cache["confusion_matrix"][s][l][p][a][0])
categories = cache["categories"]
for icat_true, row in enumerate(cm):
y_true.extend([icat_true] * sum(row))
for icat_pred in range(len(row)):
y_pred.extend([icat_pred] * row[icat_pred])
return y_true, y_pred, categories
return None, None, None
@staticmethod
def __cache_get_evaluations__(tag, method, def_cat):
"""Given a tag, a method and a default category return cached evaluation results."""
Evaluation.__cache_load__()
return Evaluation.__cache__[tag][method][def_cat]
@staticmethod
def __cache_remove_lpsa__(c_metric, s, l, p, a, simulate=False, best=True):
"""Remove evaluation results from cache given hyperparameters s, l, p, a."""
count = 0
update_best = False
if best:
values = c_metric["value"]
best = c_metric["best"]
if best["s"] == s or best["l"] == l or \
best["p"] == p or best["a"] == a:
update_best = True
else:
values = c_metric
ss = list(values.keys())
for _s in ss:
if s is not None and _s != s:
continue
ll = list(values[_s].keys())
for _l in ll:
if l is not None and _l != l:
continue
pp = list(values[_s][_l].keys())
for _p in pp:
if p is not None and _p != p:
continue
aa = list(values[_s][_l][_p].keys())
for _a in aa:
if a is not None and _a != a:
continue
if not simulate:
del values[_s][_l][_p][_a]
count += 1
if not values[_s][_l][_p]:
del values[_s][_l][_p]
if not values[_s][_l]:
del values[_s][_l]
if not values[_s]:
del values[_s]
if update_best and not simulate:
c_metric["best"] = Evaluation.__get_global_best__(values)
return count
@staticmethod
def __cache_get_default_tag__(clf, x_data, n_grams=None):
"""Create and return a default cache tag."""
n_grams = n_grams or len(clf.__max_fr__[0]) if len(clf.__max_fr__) > 0 else 1
return "%s_%s[%d-data]" % (
clf.get_name(),
"words" if n_grams == 1 else "%d-grams" % n_grams,
len(x_data)
)
@staticmethod
def __cache_remove__(tag, method, def_cat, s, l, p, a, simulate=False):
"""Remove evaluations from the cache storage."""
Print.verbosity_region_begin(VERBOSITY.QUIET)
Evaluation.__cache_load__()
Print.verbosity_region_end()
cache = Evaluation.__cache__
count_details = RecursiveDefaultDict()
count = 0
tags = list(cache.keys())
for t in tags:
if tag and t != tag:
continue
methods = list(cache[t].keys())
for md in methods:
if method and md != method:
continue
def_cats = list(cache[t][md].keys())
for dc in def_cats:
if def_cat and dc != def_cat:
continue
c_accuracy = cache[t][md][dc]["accuracy"]
count_details[t][md][dc] = Evaluation.__cache_remove_lpsa__(
c_accuracy, s, l, p, a, simulate
)
count += count_details[t][md][dc]
if not simulate:
Evaluation.__cache_remove_lpsa__(
cache[t][md][dc]["confusion_matrix"], s, l, p, a, best=False
)
if not cache[t][md][dc]["confusion_matrix"]:
del cache[t][md][dc]
metrics = list(cache[t][md][dc].keys())
for metric in metrics:
if metric not in EXCP_METRICS:
c_metric = cache[t][md][dc][metric]
categories = list(c_metric["categories"].keys())
for cat in categories:
if not simulate:
Evaluation.__cache_remove_lpsa__(
c_metric["categories"][cat], s, l, p, a
)
avgs = list(c_metric.keys())
for avg in avgs:
if avg != "categories":
c_avg = cache[t][md][dc][metric][avg]
if not simulate:
Evaluation.__cache_remove_lpsa__(c_avg, s, l, p, a)
if not cache[t][md][dc]:
del cache[t][md][dc]
if not cache[t][md]:
del cache[t][md]
if not cache[t]:
del cache[t]
return count, count_details
@staticmethod
def __classification_report_k_fold__(
tag, method, def_cat, s, l, p, a, plot=True,
metric=None, metric_target='macro avg'
):
"""Create the classification report for k-fold validations."""
Print.verbosity_region_begin(VERBOSITY.VERBOSE, force=True)
s, l = round_fix(s), round_fix(l)
p, a = round_fix(p), round_fix(a)
cache = Evaluation.__cache_get_evaluations__(tag, method, def_cat)
categories = cache["categories"]
multilabel = STR_HAMMING_LOSS in cache
metric = metric or (STR_ACCURACY if not multilabel else STR_HAMMING_LOSS)
metric = metric if metric != STR_EXACT_MATCH else STR_ACCURACY
name_width = max(len(cn) for cn in categories)
width = max(name_width, len(AVGS[-1]))
head_fmt = '{:>{width}s} ' + ' {:>9}' * len(METRICS)
report = head_fmt.format('', *['avg'] * len(METRICS), width=width)
report += '\n'
report += head_fmt.format('', *METRICS, width=width)
report += '\n\n'
for cat in categories:
report += '{:>{width}s} '.format(cat, width=width)
for mc in METRICS:
report += ' {:>9.2f}'.format(
cache[mc]["categories"][cat]["value"][s][l][p][a]
)
report += '\n'
report += '\n'
for av in AVGS:
if av in cache[mc]:
report += '{:>{width}s} '.format(av, width=width)
for mc in METRICS:
report += ' {:>9.2f}'.format(
cache[mc][av]["value"][s][l][p][a]
)
report += '\n'
report += "\n\n %s: %.3f\n" % (
Print.style.bold("Avg. %s" % ("Exact Match Ratio" if multilabel else "Accuracy")),
cache["accuracy"]["value"][s][l][p][a]
)
if multilabel:
report += " %s: %.3f\n" % (
Print.style.bold("Avg. Hamming Loss"),
round_fix(1 - cache["hamming-loss"]["value"][s][l][p][a])
)
Print.show(report)
Print.verbosity_region_end()
if plot and not multilabel:
Evaluation.__plot_confusion_matrices__(
cache["confusion_matrix"][s][l][p][a], categories,
r"$\sigma=%.3f; \lambda=%.3f; \rho=%.3f; \alpha=%.3f$"
%
(s, l, p, a)
)
if metric in GLOBAL_METRICS:
val = cache[metric]["value"][s][l][p][a]
return val if metric != STR_HAMMING_LOSS else 1 - val
else:
if metric not in cache:
raise KeyError(ERROR_NAM % str(metric))
if metric_target in cache[metric]:
return cache[metric][metric_target]["value"][s][l][p][a]
elif metric_target in cache[metric]["categories"]:
return cache[metric]["categories"][metric_target]["value"][s][l][p][a]
raise KeyError(ERROR_NAT % str(metric_target))
@staticmethod
def __plot_confusion_matrices__(cms, classes, info='', max_colums=3, multilabel=False):
"""Show and plot the confusion matrices."""
import matplotlib.pyplot as plt
categories = classes
classes = ['no', 'yes'] if multilabel else classes
n_cms = len(cms)
rows = int(ceil(n_cms / (max_colums + .0)))
columns = max_colums if n_cms > max_colums else n_cms
title = 'Confusion Matri%s' % ('x' if n_cms == 1 else 'ces')
if info:
title += "\n(%s)" % info
fig, _ = plt.subplots(rows, columns, figsize=(8, 8))
# fig.tight_layout()
if n_cms > 1:
fig.suptitle(title + '\n', fontweight="bold")
for axi, ax in enumerate(fig.axes):
if axi >= n_cms:
fig.delaxes(ax)
continue
cm = np.array(cms[axi])
ax.set_xticks(np.arange(cm.shape[1]))
ax.set_yticks(np.arange(cm.shape[0]))
im = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Purples)
if n_cms == 1:
ax.figure.colorbar(im, ax=ax)
if n_cms == 1:
ax.set_title(title + '\n', fontweight="bold")
elif multilabel:
ax.set_title(categories[axi], fontweight="bold")
if (axi % max_colums) == 0:
ax.set_ylabel('True', fontweight="bold")
ax.set_yticklabels(classes[:cm.shape[0]])
else:
ax.tick_params(labelleft=False)
if axi + 1 > n_cms - max_colums or multilabel:
ax.set_xlabel('Predicted', fontweight="bold")
ax.set_xticklabels(classes[:cm.shape[1]])
else:
ax.tick_params(labelbottom=False)
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j, i, str(cm[i, j]),
ha="center", va="center",
color="white" if cm[i, j] > thresh else "black")
plt.show()
plt.close()
@staticmethod
def __get_global_best__(values):
"""Given a list of evaluations values, return the best one."""
best = RecursiveDefaultDict()
best["value"] = -1
for s in values:
for l in values[s]:
for p in values[s][l]:
for a in values[s][l][p]:
if values[s][l][p][a] > best["value"]:
best["value"] = values[s][l][p][a]
best["s"] = s
best["l"] = l
best["p"] = p
best["a"] = a
return best
@staticmethod
def __evaluation_result__(
clf, y_true, y_pred, categories, def_cat, cache=True, method="test",
tag=None, folder=False, plot=True, k_fold=1, i_fold=0, force_show=False,
metric=None, metric_target='macro avg'
):
"""Compute evaluation results and save them to disk (cache)."""
import warnings
from __init__ import STR_UNKNOWN_CATEGORY, IDX_UNKNOWN_CATEGORY, STR_UNKNOWN
warnings.filterwarnings('ignore')
if force_show:
Print.verbosity_region_begin(VERBOSITY.VERBOSE, force=True)
multilabel = clf.__multilabel__
metric = metric or (STR_ACCURACY if not multilabel else STR_HAMMING_LOSS)
metric = metric if metric != STR_EXACT_MATCH else STR_ACCURACY
hammingloss = None
if metric == STR_HAMMING_LOSS and not multilabel:
raise ValueError("the '%s' metric is only allowed in multi-label get_best_hyperparameterscation."
% STR_HAMMING_LOSS)
if not multilabel:
n_cats = len(categories)
if def_cat == STR_UNKNOWN:
if categories[-1] != STR_UNKNOWN_CATEGORY:
categories = categories + [STR_UNKNOWN_CATEGORY]
y_pred = [y if y != IDX_UNKNOWN_CATEGORY else n_cats for y in y_pred]
else:
y_pred = membership_matrix(clf, y_pred, labels=False)
y_true = membership_matrix(clf, y_true, labels=False)
hammingloss = hamming_loss(y_pred, y_true)
accuracy = accuracy_score(y_pred, y_true)
Print.show()
Print.show(
classification_report(
y_true, y_pred,
labels=range(len(categories)), target_names=categories
)
)
if not multilabel:
Print.show("\n %s: %.3f" % (Print.style.bold("Accuracy"), accuracy))
else:
Print.show("\n %s: %.3f" % (Print.style.bold("Exact Match Ratio"), accuracy))
Print.show(" %s: %.3f" % (Print.style.bold("Hamming Loss"), hammingloss))
if not multilabel:
unclassified = None
if tag and def_cat == STR_UNKNOWN:
unclassified = sum(map(lambda v: v == n_cats, y_pred))
if tag and unclassified:
cat_acc = []
for cat in clf.get_categories():
cat_acc.append((
cat,
accuracy_score(
[
clf.get_category_index(cat) if y == n_cats else y
for y in y_pred
],
y_true
)
))
best_acc = sorted(cat_acc, key=lambda e: -e[1])[0]
Print.warn(
"A better accuracy (%.3f) would be obtained "
"with '%s' as the default category"
%
(best_acc[1], best_acc[0])
)
Print.warn(
"(Since %d%% of the documents were classified as 'unknown')"
%
(unclassified * 100.0 / len(y_true))
)
Print.show()
if not multilabel:
conf_matrix = confusion_matrix(y_true, y_pred)
else:
conf_matrix = multilabel_confusion_matrix(y_true, y_pred)
report = classification_report(
y_true, y_pred,
labels=range(len(categories)), target_names=categories,
output_dict=True
)
s, l, p, a = clf.get_hyperparameters()
if not cache or not Evaluation.__cache_is_in__(tag, method, def_cat, s, l, p, a):
Evaluation.__cache_save_result__(
Evaluation.__cache_get_evaluations__(tag, method, def_cat),
categories, accuracy, report,
conf_matrix, k_fold, i_fold,
s, l, p, a, hamming_loss=hammingloss
)
if plot:
Evaluation.__plot_confusion_matrices__(
[conf_matrix] if not multilabel else conf_matrix, categories,
r"$\sigma=%.3f; \lambda=%.3f; \rho=%.3f; \alpha=%.3f$"
%
(s, l, p, a), multilabel=multilabel
)
warnings.filterwarnings('default')
if force_show:
Print.verbosity_region_end()
if metric == STR_ACCURACY:
return accuracy
elif metric == STR_HAMMING_LOSS:
return hammingloss
else:
if metric_target not in report:
raise KeyError(ERROR_NAT % str(metric_target))
if metric not in report[metric_target]:
raise KeyError(ERROR_NAM % str(metric))
return report[metric_target][metric]
@staticmethod
def __grid_search_loop__(
clf, x_test, y_test, ss, ll, pp, aa, k_fold,
i_fold, def_cat, tag, categories, cache=True,
leave_pbar=True, extended_pbar=False, desc_pbar=None, prep=True
):
"""Grid search main loop."""
method = Evaluation.__kfold2method__(k_fold)
ss = [round_fix(s) for s in list_by_force(ss)]
ll = [round_fix(l) for l in list_by_force(ll)]
pp = [round_fix(p) for p in list_by_force(pp)]
aa = [round_fix(a) for a in list_by_force(aa)]
slp_list = list(product(ss, ll, pp))
desc_pbar = desc_pbar or "Grid search"
progress_bar = tqdm(
total=len(slp_list) * len(aa), desc=desc_pbar,
leave=leave_pbar or (method != 'test' and i_fold + 1 >= k_fold)
)
progress_desc = tqdm(
total=0,
bar_format='{desc}', leave=leave_pbar,
disable=not extended_pbar
)
Print.verbosity_region_begin(VERBOSITY.QUIET)
for s, l, p in slp_list:
clf.set_hyperparameters(s, l, p)
updated = False
for a in aa:
if not cache or not Evaluation.__cache_is_in__(
tag, method, def_cat, s, l, p, a
):
if not updated:
progress_desc.set_description_str(
" Status: [updating model...] "
"(s=%.3f; l=%.3f; p=%.3f; a=%.3f)"
%
(s, l, p, a)
)
clf.update_values()
updated = True
clf.set_alpha(a)
progress_desc.set_description_str(
" Status: [classifying...] "
"(s=%.3f; l=%.3f; p=%.3f; a=%.3f)"
%
(s, l, p, a)
)
y_pred = clf.predict(
x_test, def_cat,
labels=False, leave_pbar=False, prep=prep
)
Evaluation.__evaluation_result__(
clf, y_test, y_pred,
categories, def_cat,
cache, method, tag,
plot=False, k_fold=k_fold, i_fold=i_fold
)
else:
progress_desc.set_description_str(
" Status: [skipping (already cached)...] "
"(s=%.3f; l=%.3f; p=%.3f; a=%.3f)"
%
(s, l, p, a)
)
progress_bar.update(1)
progress_desc.update(1)
progress_desc.set_description_str(" Status: [finished]")
progress_bar.close()
progress_desc.close()
Print.verbosity_region_end()
@staticmethod
def set_classifier(clf):
"""
Set the classifier to be evaluated.
:param clf: the classifier
:type clf: SS3
"""
if Evaluation.__clf__ != clf:
Evaluation.__clf__ = clf
Evaluation.__cache_file__ = path.join(
clf.__models_folder__,
clf.get_name() + EVAL_CACHE_EXT
)
try:
makedirs(clf.__models_folder__)
except OSError as ose:
if ose.errno == errno.EEXIST and path.isdir(clf.__models_folder__):
pass
else:
raise
Evaluation.__cache__ = None
Evaluation.__cache_load__()
@staticmethod
def clear_cache(clf=None):
"""
Wipe out the evaluation cache (for the given classifier).
:param clf: the classifier (optional)
:type clf: SS3
"""
if clf is not None:
Evaluation.set_classifier(clf)
Evaluation.__cache__ = None
clf = Evaluation.__clf__
if clf:
if path.exists(Evaluation.__cache_file__):
remove_file(Evaluation.__cache_file__)
@staticmethod
def plot(html_path='./', open_browser=True):
"""
Open up an interactive 3D plot with the obtained results.
This 3D plot is opened up in the web browser and shows the results
obtained from all the performed evaluations up to date. In addition,
before showing the plot in the browser, this method also creates a
portable HTML file containing the 3D plot.
:param html_path: the path in which to store the portable HTML file
(default: './')
:type html_path: str
:param open_browser: whether to open the HTML in the browser or not
(default: True)
:type open_browser: bool
:raises: ValueError
"""
clf = Evaluation.__clf__
if not clf:
raise ValueError(ERROR_CNA)
if not Evaluation.__cache__:
Print.info("no evaluations to be plotted")
return False
pyss3_path = path.dirname(__file__)
html_src = EVAL_HTML_SRC_FOLDER
result_html_file = path.join(html_path, EVAL_HTML_OUT_FILE % clf.__name__)
fout = open(result_html_file, 'w', encoding=ENCODING)
fhtml = open(
path.join(pyss3_path, html_src + "model_evaluation.html"),
'r', encoding=ENCODING
)
for line in fhtml.readlines():
if "plotly.min.js" in line:
plotly_path = path.join(pyss3_path, html_src + "plotly.min.js")
with open(plotly_path, 'r', encoding=ENCODING) as fplotly:
fout.write(u' <script type="text/javascript">')
fout.write(fplotly.read())
fout.write(u'</script>\n')
elif "angular.min.js" in line:
angular_path = path.join(pyss3_path, html_src + "angular.min.js")
with open(angular_path, 'r', encoding=ENCODING) as fangular:
fout.write(u' <script type="text/javascript">')
fout.write(fangular.read())
fout.write(u'</script>\n')
elif "data.js" in line:
fout.write(u' <script type="text/javascript">')
fout.write(u'var $model_name = "%s"; ' % clf.get_name())
fout.write(
u'var $results = JSON.parse("%s");'
%
json.dumps(Evaluation.__cache__).replace('"', r'\"')
)
fout.write(u'</script>\n')
elif "[[__version__]]" in line:
from pyss3 import __version__
fout.write(line.replace("[[__version__]]", __version__))
else:
fout.write(line)
fhtml.close()
fout.close()
if open_browser:
webbrowser.open(result_html_file)
Print.info("evaluation plot saved in '%s'" % result_html_file)
return True
@staticmethod
def get_best_hyperparameters(
metric=None, metric_target='macro avg', tag=None, method=None, def_cat=None
):
"""
Return the best hyperparameter values for the given metric.
From all the evaluations performed using the given ``method``, default
category(``def_cat``) and cache ``tag``, this method returns the
hyperparameter values that performed the best, according to the given
``metric``, if not supplied, these values will automatically use the
ones matching the last performed evaluation.
Available metrics are: 'accuracy', 'f1-score', 'precision', and
'recall'. In addition, In multi-label classification also 'hamming-loss'
and 'exact-match'
Except for accuracy, a ``metric_target`` option must also be supplied
along with the ``metric`` indicating the target we aim at measuring,
that is, whether we want to measure some averaging performance or the
performance on a particular category.
:param metric: the evaluation metric to return, options are:
'accuracy', 'f1-score', 'precision', or 'recall'
When working with multi-label classification problems,
two more options are allowed: 'hamming-loss' and 'exact-match'.
Note: exact match will produce the same result than 'accuracy'.
(default: 'accuracy', or 'hamming-loss' for multi-label case).
:type metric: str
:param metric_target: the target we aim at measuring with the given
metric. Options are: 'macro avg', 'micro avg',
'weighted avg' or a category label (default
'macro avg').
:type metric_target: str
:param tag: the cache tag from where to look up the results
(by default it will automatically use the tag of the last
evaluation performed)
:type tag: str
:param method: the evaluation method used, options are: 'test', 'K-fold',
where K is a positive integer (by default it will match the
method of the last evaluation performed).
:type method: str
:param def_cat: the default category used the evaluations, options are:
'most-probable', 'unknown' or a category label (by default
it will use the same as the last evaluation performed).
:type def_cat: str
:returns: a tuple of the hyperparameter values: (s, l, p, a).
:rtype: tuple
:raises: ValueError, LookupError, KeyError
"""