-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcebnn_main.py
executable file
·2114 lines (1786 loc) · 91.7 KB
/
cebnn_main.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
#!/usr/bin/env python3.10
# -*- coding: utf-8 -*-
from __future__ import annotations
# For deterministic behavior
__import__('os').environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'
import copy
import gc
import io
import math
import multiprocessing
import os
import pickle
import random
import re
import subprocess
import sys
import termios
import time
import warnings
from collections import defaultdict
from functools import reduce
from itertools import combinations
from numbers import Real
from operator import itemgetter
from timeit import default_timer as timer
from typing import TYPE_CHECKING, Any, Container, List, Literal, Optional, Tuple, TypeVar
import matplotlib.pyplot as plt
import numpy as np
import torch
import torchvision
from adabelief_pytorch import AdaBelief # type: ignore[attr-defined]
from apex.optimizers import FusedLAMB
from pytorch_warmup import UntunedLinearWarmup
from scipy.optimize import basinhopping
from sklearn.metrics import matthews_corrcoef, roc_auc_score, roc_curve
from skorch import NeuralNetClassifier
from skorch.exceptions import SkorchWarning
from skorch.callbacks import Callback, EpochScoring, PrintLog, ProgressBar
from skorch.dataset import get_len, unpack_data
from skorch.utils import TeeGenerator, to_tensor
from tap import Tap
from torch import Tensor, autograd, nn
from torch.optim.lr_scheduler import CosineAnnealingLR, StepLR
from torch.optim.optimizer import Optimizer
from torch.utils.data import DataLoader
from torchvision import transforms
from tqdm import tqdm
import mypickle
from aadamw01 import AAdamW01
from adamwr.adamw import AdamW
from adamwr.cyclic_scheduler import CyclicLRWithRestarts
from algorithm import fbeta_like_geo_youden, multilabel_confusion_matrix
from augment import MayResize, find_best_augment_params, make_data_transform
from cebnn_common import ModelLoader, model_supports_resnet_d, parse_sublayer_ratio, pos_proba, pred_uncertainty
from datamunge import ImbalancedDatasetSampler
from dataset import CatDataset, LabeledDataset, LabeledSubset, MultiLabelCSVDataset, TransformedDataset
from losses import EDL_Digamma_Loss, EDL_Log_Loss, EDL_MSE_Loss
from sgdw import SGDW
from util import zip_strict
if TYPE_CHECKING:
from typing import Callable, Dict, Iterable, Iterator, NoReturn, Sequence, Set, Type, Union
from sklearn.base import BaseEstimator
from torch.optim.lr_scheduler import _LRScheduler
from torch.utils.data.dataset import Dataset
from cebnn_common import Module
from util import Array
StrPath = Union[str, 'os.PathLike[str]']
AnyEstimator = TypeVar('AnyEstimator', bound=BaseEstimator)
AnyResampleArgs = TypeVar('AnyResampleArgs', bound='ResampleArgs')
AnyRLS = TypeVar('AnyRLS', bound='ResampledLabeledSubset')
AnyDataset = Union[Dataset[Any]]
AnyNNC = TypeVar('AnyNNC', bound='MyNeuralNetClassifier')
T = TypeVar('T')
DEFAULT_SUBLAYERS = (0, .5)
DEFAULT_EPOCHS = 20
DEFAULT_BATCH_SIZE = 16
DEFAULT_ANNEALING_STEP = 10
DEFAULT_OPTIMIZER = 'adam'
DEFAULT_SCHEDULER = 'linear'
DEFAULT_SCH_PERIOD = 1
DEFAULT_SEED = 42
DEFAULT_NUM_WORKERS = 4
UNTYPED_NONE: Any = None
cfg: 'Config' = UNTYPED_NONE
transformed_datasets: Dict[str, LabeledDataset] = {}
device: torch.device = UNTYPED_NONE
options: 'MainArgParser' = UNTYPED_NONE
def disable_echo() -> None:
fd = sys.stdin.fileno()
if not os.isatty(fd):
return
attr = termios.tcgetattr(fd)
attr[3] &= ~termios.ECHO # type: ignore[operator]
termios.tcsetattr(fd, termios.TCSADRAIN, attr)
def seed_all(seed: int) -> None:
# See https://pytorch.org/docs/stable/notes/randomness.html
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def imshow(inp: Tensor, title: Optional[str] = None) -> None:
"""Imshow for Tensor."""
inp = inp.numpy().transpose((1, 2, 0))
inp = np.clip(inp, 0, 1)
plt.imshow(inp)
if title is not None:
plt.title(title)
plt.show()
class GradScale(autograd.Function):
@staticmethod
def forward(ctx: Any, x: Tensor, factor: Tensor) -> Tensor:
ctx.save_for_backward(factor)
return x.view_as(x)
@staticmethod
def backward(ctx: Any, grad_output: Tensor) -> Tuple[Tensor, Optional[Tensor]]:
factor, = ctx.saved_tensors
return grad_output * factor, None
def grad_scale(x: Tensor, factor: Tensor) -> Tensor:
return GradScale.apply(x, factor)
class ExtraTrainLoss(autograd.Function):
@staticmethod
def forward(ctx: Any, base_loss: Tensor, extra_loss: Tensor) -> Tensor:
with torch.enable_grad():
detached_base_loss = base_loss.detach()
detached_base_loss.requires_grad_()
detached_extra_loss = extra_loss.detach()
detached_extra_loss.requires_grad_()
total_loss = detached_base_loss + detached_extra_loss
ctx.saved_losses = detached_base_loss, detached_extra_loss
ctx.save_for_backward(total_loss)
return base_loss.clone()
@staticmethod
def backward(ctx: Any, grad_output: Tensor) -> Tuple[Tensor, Tensor]:
total_loss, = ctx.saved_tensors
base_loss, extra_loss = ctx.saved_losses
with torch.enable_grad():
total_loss.backward(grad_output)
return base_loss.grad, extra_loss.grad
def extra_train_loss(base_loss: Tensor, extra_loss: Tensor) -> Tensor:
return ExtraTrainLoss.apply(base_loss, extra_loss)
class ExtraTrainLossMixin(nn.Module):
def __init__(self, norm_params: Sequence[nn.Parameter], model: Module, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._norm_params = norm_params
self._model = model
self.register_buffer('zero', torch.zeros((), device=device))
if options.l1reg is not None:
self.register_buffer('l1reg', torch.tensor(options.l1reg, device=device))
if options.l2reg is not None:
self.register_buffer('l2reg', torch.tensor(options.l2reg, device=device))
if options.corrreg is not None:
self.register_buffer('corrreg', torch.tensor(options.corrreg, device=device))
def forward(self, pred: Tensor, target: Tensor, epoch: int) -> Tensor:
base_loss: Tensor = super().forward(pred, target, epoch)
if not torch.is_grad_enabled():
return base_loss # Only apply extra loss while training
if options.l1reg is None and options.l2reg is None and options.corrreg is None:
return base_loss # No extra loss needed
def lp_loss(p: int, reg: Tensor) -> Tensor:
return sum((grad_scale(np, reg).norm(p=p) for np in self._norm_params),
start=self.zero)
l1_loss = l2_loss = corr_loss = self.zero
if options.l1reg is not None:
l1_loss = lp_loss(1, self.l1reg)
if options.l2reg is not None:
l2_loss = lp_loss(2, self.l2reg)
# Correlation loss (see https://doi.org/10.1007/978-3-319-68612-7_6)
def layer_corr_loss(layer_weights: Tensor, reg: Tensor) -> float:
lw = grad_scale(layer_weights, reg) # Gradient scale factor
assert len(lw.size()) == 4 # Conv2d expected
kernels = lw.view(-1, *lw.size()[:-2])
return sum(self._pearsonr(si.flatten(), sj.flatten()) ** 2
for si, sj in combinations(kernels, 2))
if options.corrreg is not None:
corr_loss_layers = (
l for l in self._model.modules()
if isinstance(l, nn.Conv2d) and l.weight.requires_grad and any(s > 1 for s in l.kernel_size)
)
corr_loss = sum(layer_corr_loss(l.weight, self.corrreg) for l in corr_loss_layers)
extra_loss = l1_loss + l2_loss + corr_loss
assert base_loss.shape == extra_loss.shape
return extra_train_loss(base_loss, extra_loss)
# From https://github.com/pytorch/pytorch/issues/1254
@staticmethod
def _pearsonr(x: Tensor, y: Tensor) -> float:
xm = x.sub(x.mean())
ym = y.sub(y.mean())
r_num = xm.dot(ym)
r_den = xm.norm(2) * ym.norm(2)
return r_num / r_den
class EDL_MSE_Loss_Extra(ExtraTrainLossMixin, EDL_MSE_Loss):
pass
class EDL_Log_Loss_Extra(ExtraTrainLossMixin, EDL_Log_Loss):
pass
class EDL_Digamma_Loss_Extra(ExtraTrainLossMixin, EDL_Digamma_Loss):
pass
def prestep_clipping_optimizer(base_type: Type[Optimizer]) -> Type[Any]:
assert issubclass(base_type, Optimizer)
class PrestepClippingOptimizer(base_type): # type: ignore[misc, valid-type]
def __init__(self, params: Union[Sequence[nn.Parameter], Sequence[Dict[str, Any]]],
norm_params: Sequence[nn.Parameter], **kwargs: Any) -> None:
super().__init__(params, **kwargs)
self._norm_params = norm_params
def step(self, *args: Any, **kwargs: Any) -> Any:
# Only clip if there are gradients already and this is not resnet18
if any(p.grad is not None for p in self._norm_params) and cfg.base_model != 'resnet18':
# Clip gradient
nn.utils.clip_grad_norm_(self._norm_params, .1)
return super().step(*args, **kwargs)
return PrestepClippingOptimizer
def print_predictions(net: NeuralNetClassifier, checkpoint: Dict[str, Any]) -> None:
def format_labels(labels: Iterable[str]) -> str:
labels = frozenset(labels)
def lify(l: str) -> str: return '{},'.format(l) if l in labels else ' ' * (len(l) + 1)
return ''.join(map(lify, cfg.model_classes))[:-1]
metrics = Metrics()
metrics.f_score_eval(net, checkpoint, log=False)
for sample_targets, sample_preds in zip_strict(metrics.true_labels, metrics.predictions):
in_labels = [cn for tl, cn in zip_strict(sample_targets, cfg.model_classes) if tl > .99]
out_labels = [cn for pr, cn, th in zip_strict(sample_preds, cfg.model_classes, metrics.thresholds) if pr > th]
if not in_labels and not out_labels:
continue # Not interesting
print('actual: [{}], predicted: [{}]'.format(
format_labels(in_labels), format_labels(out_labels)))
def geoy(true_labels: Array, predictions: Array, thresholds: Array,
average: Optional[str] = None, i: Optional[int] = None) -> Any:
assert true_labels.shape == predictions.shape
y_true = true_labels if i is None else true_labels[:, i, None]
y_pred = (predictions > thresholds) if i is None else (predictions[:, i, None] > thresholds.item())
MCM = multilabel_confusion_matrix(y_true, y_pred, binary=options.optmode == 2)
with np.errstate(invalid='ignore'):
scores = list(map(fbeta_like_geo_youden, MCM))
del MCM
if average is not None:
score: Any = np.mean(scores)
elif i is None:
score = np.stack(scores)
else:
score, = scores
# Don't use the score if all predictions are true, all predictions are false, there are no true positives, or there
# are no true negatives, for _any_ label. All of those are degenerate cases where the threshold is unusable.
def badlabel(truei: Array, predi: Array) -> bool:
return bool(
np.all(predi > 0.) or np.all(predi < .99)
or np.all(predi[truei > 0.] < .99) or np.all(predi[truei < .99] > 0.)
)
if i is None:
for j in range(true_labels.shape[1]):
if not badlabel(true_labels[:, j], (predictions[:, j] > thresholds[j])):
continue
if average is not None:
return np.zeros(score.shape, score.dtype) if isinstance(score, np.ndarray) else 0.
score[j] = 0.
elif badlabel(y_true, y_pred):
return np.zeros(score.shape, score.dtype) if isinstance(score, np.ndarray) else 0.
return score.tolist() if isinstance(score, np.ndarray) else score
# Scipy tries to minimize the function, so we must get its inverse
def geoy_neg(true: Array, pred: Array, i: Optional[int] = None) -> Callable[[Array], float]:
average = 'macro' if i is None and len(cfg.model_classes) > 1 else 'binary'
return lambda th: - geoy(true, pred, th, average=average, i=i)
def minimizer_bounds(**kwargs: Any) -> bool:
x: float = kwargs['x_new']
tmax = bool(np.all(x <= 1.))
tmin = bool(np.all(x >= 0.))
return tmax and tmin
def minimize_global(true: Array, pred: Array, minimizer_kwargs: Dict[str, Any],
bounds: Callable[..., bool], st_point: float) -> List[Tuple[float, float]]:
# We combine SLSQP with Basinhopping for stochastic search with random steps
thr_0 = np.array([st_point for _ in cfg.model_classes])
opt_output = basinhopping(geoy_neg(true, pred), thr_0, stepsize=.1, niter=150 if options.optmode == 1 else 20,
minimizer_kwargs=minimizer_kwargs, accept_test=bounds, seed=88)
if len(cfg.model_classes) > 1:
scores: List[float] = geoy(true, pred, opt_output.x, average=None)
else:
scores = [-opt_output.fun]
return list(zip_strict(opt_output.x.tolist(), scores))
def refine(true: Array, pred: Array, minimizer_kwargs: Dict[str, Any],
bounds: Callable[..., bool], st_point: float, i: int) -> Tuple[float, float]:
# We combine SLSQP with Basinhopping for stochastic search with random steps
f = geoy_neg(true, pred, i)
thr0 = st_point
fx0 = -f(np.array(thr0))
steps = (((.1, 100), (.01, 50), (.005, 50)) if options.optmode == 1 else
((.1, 30), (.05, 30), (.02, 30)))
for step, niter in steps:
opt_output = basinhopping(f, [thr0], stepsize=step, niter=niter,
minimizer_kwargs=minimizer_kwargs, accept_test=bounds, seed=30)
fx1 = -opt_output.fun
if fx1 > fx0 or options.optmode == 2:
thr0 = opt_output.x.item()
fx0 = fx1
return thr0, fx0
# From https://github.com/mratsim/Amazon-Forest-Computer-Vision/blob/master/src/p2_validation.py
def best_f_score(true_labels: Array, predictions: Array, log: bool = False) -> List[Tuple[float, float]]:
# Initialization of best threshold search
constraints = [(0., 1.) for _ in cfg.model_classes]
# Search using SLSQP, the epsilon step must be big otherwise there is no gradient
minimizer_kwargs = {
'method': 'SLSQP',
'bounds': constraints,
'options': {'eps': .01 if options.optmode == 1 else .05},
}
if log:
print('==> Searching for optimal threshold for each label...', end='')
start_time = timer()
st_points = [.00736893 * math.e ** (.421019 * x) for x in range(11)]
st_points.extend(1. - p for p in reversed(st_points[:-1]))
max_threads = max(len(st_points), len(cfg.model_classes))
cpus = os.cpu_count()
if cpus is not None and max_threads > cpus:
max_threads = cpus
def best(a: List[Tuple[float, float]], b: List[Tuple[float, float]]) -> List[Tuple[float, float]]:
return list(map(
lambda t: max(t, key=itemgetter(1)),
zip_strict(a, b)
))
with multiprocessing.Pool(max_threads) as p:
best_scores = reduce(
best,
p.starmap(
minimize_global,
((true_labels, predictions, minimizer_kwargs, minimizer_bounds, st_point)
for st_point in st_points)
)
)
minimizer_kwargs['bounds'] = [constraints[0]]
assert len(best_scores) == len(cfg.model_classes)
if len(cfg.model_classes) > 1:
new_scores = p.starmap(
refine,
((true_labels, predictions, minimizer_kwargs, minimizer_bounds, best_score[0], i)
for i, best_score in enumerate(best_scores)))
end_time = timer()
if log:
print(' found in {:.2f}s'.format(end_time - start_time))
if len(cfg.model_classes) > 1:
for i, (best_score, new_score) in enumerate(zip_strict(best_scores, new_scores)):
if new_score[1] > best_score[1]:
if log:
print(
'Warning: Found a better threshold locally!'
' Difference in threshold was {:.4f}'.format(
abs(best_score[0] - new_score[0])),
file=sys.stderr)
best_scores[i] = new_score
return best_scores
def plot_roc(true_labels: Array, predictions: Array, fig_dir: StrPath) -> None:
# One for each label
rocs = [roc_curve(truth, pred)[:-1] for truth, pred in zip_strict(true_labels.T, predictions.T)]
assert options.load is not None and len(options.load) == 1
bname = os.path.basename(*options.load)
plt.ioff()
plt.figure()
plt.plot([0, 1], [0, 1], 'k--')
for roc, name in zip_strict(rocs, cfg.model_classes):
plt.plot(*roc, label=name)
plt.xlabel('False positive rate')
plt.ylabel('True positive rate')
plt.title('ROC curve')
plt.legend(loc='lower right')
plt.savefig(os.path.join(fig_dir, '{}_roc.svg'.format(bname)), bbox_inches='tight')
def worker_init_fn(worker_id: int) -> None:
torch_seed = torch.initial_seed()
random.seed(torch_seed + worker_id)
np.random.seed((torch_seed + worker_id) % 2**32)
def make_dataloader(dataset: LabeledDataset) -> DataLoader:
return DataLoader(
dataset,
batch_size=cfg.batch_size,
num_workers=cfg.num_workers,
pin_memory=True,
worker_init_fn=worker_init_fn,
)
def evaluate(net: NeuralNetClassifier, checkpoint: Dict[str, Any], log: bool = True) \
-> Tuple[Array, Array, Optional[Array], Array, Optional[Array]]:
# Use precomputed data if available
if options.from_cpickle is not None:
with open(options.from_cpickle, 'rb') as pf:
pkl = pickle.load(pf)
def load(what: str) -> Array:
return (np.fromiter((y for y in pkl[what] if y is not None), dtype=np.float32)
.reshape(-1, len(cfg.model_classes)))
return load('y_pred'), load('y_u'), None, load('y_true'), pkl['thresh']
elif (
options.test_with_cpickle_thr is None
and not options.ignore_cpeval
and checkpoint.get('opt_eval_dataset') in (None, cfg.data_cv_dir)
):
try:
return (checkpoint['opt_eval_y_pred'], checkpoint['opt_eval_y_u'], checkpoint['opt_eval_tot_ev'],
checkpoint['opt_eval_y_true'], None)
except KeyError:
pass
start_time = None
if log:
print('==> Evaluating...')
start_time = timer()
dataset = transformed_datasets['opt' if options.test_with_cpickle_thr is None else 'test']
preds, us, tot_ev, targets, avg_loss = eval_inner(net, dataset, checkpoint['epoch'] + 1, progress=True)
if start_time is not None:
end_time = timer()
print('==> Done in {:.2f}s.'.format(end_time - start_time))
print('==> Avg. loss: {:.4f}'.format(avg_loss))
return preds, us, tot_ev, targets, None
def eval_inner(net: NeuralNetClassifier, dataset: LabeledDataset, epoch: int, progress: bool = False,
leave: bool = True) -> tuple[Array, Array, Array, Array, float]:
it: Iterator[Tensor] = net.forward_iter(dataset)
it = tqdm(it, total=math.ceil(len(dataset) / cfg.batch_size), leave=leave) if progress else it
alpha = torch.cat(list(it))
predictions = pos_proba(alpha).cpu().numpy()
uncertainties = pred_uncertainty(alpha).cpu().numpy()
total_evidence = torch.sum(alpha - 1, dim=-1).cpu().numpy()
y_true = torch.as_tensor(dataset.targets, device=alpha.device)
avg_loss = net.criterion_(alpha, y_true, epoch)
return predictions, uncertainties, total_evidence, dataset.targets, avg_loss
class Metrics:
predictions: Array
uncertainties: Array
total_evidence: Optional[Array]
true_labels: Array
thresholds: List[float]
def f_score_eval(self, net: NeuralNetClassifier, checkpoint: Dict[str, Any], log: bool = True) \
-> None:
self.predictions, self.uncertainties, self.total_evidence, self.true_labels, cpickle_thresh = \
evaluate(net, checkpoint, log)
if options.threshold_override is not None:
if len(options.threshold_override) == 1:
self.thresholds = [options.threshold_override[0] for _ in cfg.model_classes]
else:
self.thresholds = list(options.threshold_override)
best_f_scores = [(th, 0.) for th in self.thresholds]
elif options.from_cpickle is not None:
self.thresholds = [.5 for _ in cfg.model_classes]
best_f_scores = [(th, 0.) for th in self.thresholds]
elif options.test_with_cpickle_thr is not None:
with open(options.test_with_cpickle_thr, 'rb') as pf:
self.thresholds = pickle.load(pf)['thresh']
best_f_scores = [(th, 0.) for th in self.thresholds]
else:
best_f_scores = best_f_score(self.true_labels, self.predictions, log)
# Softened thresholds to improve generalization
self.thresholds = [(th + .5) / 2. for th, fs in best_f_scores]
if log:
def format_float(vals: Iterable[float]) -> Dict[str, str]:
return dict(zip_strict(cfg.model_classes, map('{:.4f}'.format, vals)))
def format_scores(idx: int) -> Dict[str, str]:
return format_float(tup[idx] for tup in best_f_scores)
thresholds, f_scores = format_scores(0), format_scores(1)
if cpickle_thresh is not None:
thresholds = format_float(cpickle_thresh) # For display only
print()
print('==> Optimal threshold for each label:\n {}'.format(thresholds))
print('==> F-Score for each label:\n {}'.format(f_scores))
def zeros() -> List[int]: return [0 for _ in cfg.model_classes]
true_positives, false_negatives, false_positives, true_negatives = \
zeros(), zeros(), zeros(), zeros()
for sample_targets, sample_preds in zip_strict(self.true_labels, self.predictions):
for j, (label_true, label_pred) in enumerate(zip_strict(sample_targets, sample_preds)):
is_true = label_true > .99
is_pred = label_pred > best_f_scores[j][0]
cat = {
(True, True ): true_positives,
(True, False): false_negatives,
(False, True ): false_positives,
(False, False): true_negatives,
}[(is_true, is_pred)]
cat[j] += 1
def fmt(cat: Iterable[int]) -> Dict[str, str]:
return dict(zip_strict(cfg.model_classes, ('{:3d}'.format(l) for l in cat)))
print('==> True positives for each label:\n {}'.format(fmt(true_positives)))
print('==> False negatives for each label:\n {}'.format(fmt(false_negatives)))
print('==> False positives for each label:\n {}'.format(fmt(false_positives)))
print('==> True negatives for each label:\n {}'.format(fmt(true_negatives)))
if self.total_evidence is not None:
thresholds_ = np.asarray([t for t, s in best_f_scores])
match = np.equal(self.predictions > .99, self.true_labels > thresholds_[None, :]).astype(np.float32)
mean_evidence: Array = np.mean(self.total_evidence, axis=0) # type: ignore[assignment]
mean_evidence_succ = (np.sum(self.total_evidence * match, axis=0)
/ np.sum(match + 1e-20, axis=0))
mean_evidence_fail = (np.sum(self.total_evidence * (1 - match), axis=0)
/ np.sum(1 - match + 1e-20, axis=0))
print('==> Mean evidence for each label:\n {}'.format(format_float(mean_evidence)))
print('==> Mean success evidence for each label:\n {}'.format(format_float(mean_evidence_succ)))
print('==> Mean failure evidence for each label:\n {}'.format(format_float(mean_evidence_fail)))
def metrics_eval(self, net: NeuralNetClassifier, checkpoint: Dict[str, Any]) -> None:
self.f_score_eval(net, checkpoint)
# [(label1_true..., label1_pred...), (label2_true..., label2_pred...), ...]
pred_data = list(zip_strict(self.true_labels.T, self.predictions.T))
def fmt(g: Iterable[float]) -> Dict[str, str]:
return dict(zip_strict(cfg.model_classes, ('{:.4f}'.format(fs) for fs in g)))
mccs = (matthews_corrcoef(truth, [p > th for p in pred])
for (truth, pred), th in zip_strict(pred_data, self.thresholds))
print()
print('==> MCC for each label:\n {}'.format(fmt(mccs)))
if options.from_cpickle is None: # cpickle means binary y_pred, ROC AUC is not meaningful
roc_aucs = (roc_auc_score(truth, pred) for truth, pred in pred_data)
print('==> ROC AUC for each label:\n {}'.format(fmt(roc_aucs)))
def test_eval(self, net: NeuralNetClassifier, checkpoint: Dict[str, Any], log: bool = True) -> None:
assert options.eval_dir is not None
assert options.load is not None and len(options.load) == 1
path = os.path.join(options.eval_dir, os.path.basename(*options.load) + '_eval.pkl')
if os.path.exists(path):
return # Don't clobber it
self.predictions, self.uncertainties, self.total_evidence, self.true_labels, _ = \
evaluate(net, checkpoint, log)
teval: Dict[str, Tuple[Any, Any]] = defaultdict(lambda: ([], []))
for sample_targets, sample_preds in zip_strict(self.true_labels, self.predictions):
for label_name, label_true, label_pred in zip_strict(cfg.model_classes, sample_targets, sample_preds):
pred, true = teval[label_name]
pred.append(label_pred)
true.append(label_true)
teval = {k: (np.asarray(p), np.asarray(t)) for k, (p, t) in teval.items()}
with open(path, 'wb') as pf:
pickle.dump(teval, pf)
if log:
print('\n==> Evaluation results saved to {!r}.'.format(path))
def correct_eval(self, net: NeuralNetClassifier, checkpoint: Dict[str, Any], log: bool = True) -> None:
assert options.correct_dir is not None
assert options.load is not None and len(options.load) == 1
path = os.path.join(options.correct_dir, os.path.basename(*options.load) + '_correct.pkl')
if os.path.exists(path):
return # Don't clobber it
self.f_score_eval(net, checkpoint)
y_true: List[Optional[bool]] = []
y_pred: List[Optional[bool]] = []
y_u: List[Optional[float]] = []
it1 = zip_strict(self.true_labels, self.uncertainties, self.predictions)
for sample_targets, sample_uncertainties, sample_preds in it1:
lbl_to_true: Dict[str, bool] = {}
lbl_to_pred: Dict[str, bool] = {}
lbl_to_uncertainty: Dict[str, float] = {}
it2 = enumerate(zip_strict(cfg.model_classes, sample_targets, sample_preds, sample_uncertainties))
for j, (lblname, lbltrue, lblpred, lblu) in it2:
lbl_to_true[lblname] = lbltrue > .99
lbl_to_pred[lblname] = lblpred > self.thresholds[j]
lbl_to_uncertainty[lblname] = lblu
del it2
# Substitute with None if label not predicted
y_true.extend(map(lbl_to_true.get, cfg.data_classes))
y_pred.extend(map(lbl_to_pred.get, cfg.data_classes))
y_u.extend(map(lbl_to_uncertainty.get, cfg.data_classes))
del it1
with open(path, 'wb') as pf:
data = {
'label_count': len(cfg.data_classes), 'thresh': self.thresholds,
'y_true': y_true, 'y_pred': y_pred, 'y_u': y_u,
}
pickle.dump(data, pf)
if log:
print('\n==> Correctness pickle saved to {!r}.'.format(path))
def roc_eval(net: NeuralNetClassifier, fig_dir: StrPath, checkpoint: Dict[str, Any], log: bool = True) -> None:
predictions, _, _, true_labels, _ = evaluate(net, checkpoint, log)
plot_roc(true_labels, predictions, fig_dir)
if log:
print('\n==> ROC curve plots saved to {!r}.'.format(os.fspath(fig_dir)))
def save_random_state() -> Dict[str, Any]:
return copy.deepcopy({
'python': random.getstate(),
'numpy': np.random.get_state(),
'torch': torch.get_rng_state(),
'cuda': torch.cuda.get_rng_state(device) if torch.cuda.is_available() else None,
})
class TrainerCallback(Callback):
def __init__(
self, scheduler: Optional[_LRScheduler], warmup_scheduler: Optional[UntunedLinearWarmup], pbar: ProgressBar,
) -> None:
self.scheduler = scheduler
self.warmup_scheduler = warmup_scheduler
self.pbar = pbar
self.best_loss = np.inf
self.best_state: Optional[io.BytesIO] = None
self.start_time: Optional[float] = None
def on_epoch_begin(self, net: NeuralNetClassifier, dataset_train: Optional[AnyDataset] = None, # noqa: U100
dataset_valid: Optional[AnyDataset] = None, **kwargs: object) -> None: # noqa: U100
net.history[-1]['epoch'] -= 1 # offset for pre-epoch
self.pbar.batches_per_epoch = (
(0 if dataset_train is None else math.ceil(get_len(dataset_train) / cfg.batch_size)) +
math.ceil(get_len(dataset_valid) / cfg.batch_size)
)
if isinstance(self.scheduler, CyclicLRWithRestarts):
assert self.warmup_scheduler is None
self.scheduler.step()
def on_batch_begin(self, net: NeuralNetClassifier, batch: object = None, # noqa: U100
training: Optional[bool] = None, **kwargs: object) -> None: # noqa: U100
if training and self.warmup_scheduler is not None:
assert self.scheduler is not None
with warnings.catch_warnings():
# Deprecated step() usage is recommended by the warmup scheduler
warnings.filterwarnings('ignore', '.*call them in the opposite order.*', UserWarning)
warnings.filterwarnings('ignore', 'The epoch parameter.*', UserWarning)
self.scheduler.step(net.history[-1]['epoch'] - 1)
self.warmup_scheduler.dampen()
def on_batch_end(self, net: NeuralNetClassifier, batch: object = None, # noqa: U100
training: Optional[bool] = None, **kwargs: object) -> None: # noqa: U100
# CosineAnnealingLR-based scheduler
if training and isinstance(self.scheduler, CyclicLRWithRestarts):
assert self.warmup_scheduler is None
self.scheduler.batch_step()
def on_epoch_end(self, net: NeuralNetClassifier, dataset_train: object = None, *args: object, # noqa: U100
**kwargs: object) -> None: # noqa: U100
if (
dataset_train is not None
and isinstance(self.scheduler, (StepLR, CosineAnnealingLR))
and self.warmup_scheduler is None
):
self.scheduler.step()
if dataset_train is None:
net.history[-1]['train_loss'] = None
# Save the trainer state if the model is still making progress.
if dataset_train is None or net.history[-1, 'train_loss_best'] or net.history[-1, 'valid_loss_best']:
self.best_loss = net.history[-1, 'valid_loss']
self._save_state_dict(net)
def on_train_begin(self, net: NeuralNetClassifier, *args: object, **kwargs: object) -> None: # noqa: U100
self.start_time = timer()
self._save_state_dict(net)
self.best_loss = np.inf
def on_train_end(self, net: NeuralNetClassifier, *args: object, **kwargs: object) -> None: # noqa: U100
assert self.start_time is not None
time_elapsed = timer() - self.start_time
print('==> Training complete in {:.0f}m {:.2f}s.'.format(
time_elapsed // 60, time_elapsed % 60))
print('==> Best validation loss: {:4f}'.format(self.best_loss))
def _save_state_dict(self, net: NeuralNetClassifier) -> None:
self.best_state = io.BytesIO()
save_dict = get_save_state_dict(
cfg=cfg,
options=options,
model_state_dict=net.module_.state_dict(),
optimizer_state_dict=net.optimizer_.state_dict(),
scheduler=self.scheduler,
warmup_scheduler=self.warmup_scheduler,
random_state=save_random_state(),
net=net,
)
torch.save(save_dict, self.best_state, pickle_module=mypickle)
self.best_state.seek(0)
class MyNeuralNetClassifier(NeuralNetClassifier):
def __init__(self, *args: Any, **kwargs: Any) -> None:
self.initial_epoch = kwargs.pop('initial_epoch')
super().__init__(*args, **kwargs)
# skorch: Don't set up the optimizer if we don't intend to use one
def initialize_optimizer(self: AnyNNC, triggered_directly: bool = True) -> AnyNNC:
if self.optimizer is None:
return self
return super().initialize_optimizer(triggered_directly=triggered_directly)
# SciKit-Learn: Don't clone me, I'm fragile (and big)
def __deepcopy__(self, _memo: Dict[int, object]) -> NoReturn:
raise RuntimeError('plz no')
# Passes epoch to get_loss
def validation_step(self, batch: Any, **fit_params: Any) -> Dict[str, Any]:
epoch: int = fit_params.pop('epoch')
self.module_.eval()
Xi, yi = unpack_data(batch)
with torch.no_grad():
y_pred = self.infer(Xi, **fit_params)
loss = self._get_loss(y_pred, yi, epoch)
return {'loss': loss, 'y_pred': y_pred}
# Passes epoch to get_loss
def train_step_single(self, batch: Any, **fit_params: Any) -> Dict[str, Any]:
epoch: int = fit_params.pop('epoch')
self.module_.train()
Xi, yi = unpack_data(batch)
y_pred = self.infer(Xi, **fit_params)
loss = self._get_loss(y_pred, yi, epoch)
loss.backward()
return {'loss': loss, 'y_pred': y_pred}
# Modified train_step that avoids classic zero_grad
# See https://pytorch.org/tutorials/recipes/recipes/tuning_guide.html
def train_step(self, batch: Any, **fit_params: Any) -> Dict[str, Any]:
step_accumulator = self.get_train_step_accumulator()
def step_fn() -> Tensor:
step = self.train_step_single(batch, **fit_params)
step_accumulator.store_step(step)
self.notify(
'on_grad_computed',
named_parameters=TeeGenerator(self.module_.named_parameters()),
batch=batch,
)
return step['loss']
self.optimizer_.step(step_fn)
for param in self.module_.parameters():
param.grad = None
return step_accumulator.get_step()
# Passes the accurate epoch to run_single_epoch so loss can use it
# Gets validation data via ds_valid
def fit_loop(self, X: AnyDataset, y: Optional[Array] = None, epochs: Optional[int] = None, **fit_params: Any) \
-> NeuralNetClassifier:
self.check_data(X, y)
epochs = epochs if epochs is not None else self.max_epochs
dataset_train = self.get_dataset(X, y)
dataset_valid = self.get_dataset(fit_params.pop('valid'))
on_epoch_kwargs = {
'dataset_train': dataset_train,
'dataset_valid': dataset_valid,
}
for epoch in range(self.initial_epoch, self.initial_epoch + epochs):
fit_params['epoch'] = epoch
self.notify('on_epoch_begin', **on_epoch_kwargs)
self.run_single_epoch(dataset_train, training=True, prefix='train',
step_fn=self.train_step, **fit_params)
if dataset_valid is not None:
self.run_single_epoch(dataset_valid, training=False, prefix='valid',
step_fn=self.validation_step, **fit_params)
self.notify('on_epoch_end', **on_epoch_kwargs)
return self
def get_loss(self, y_pred: Tensor, y_true: Tensor, *args: object, **kwargs: object) -> NoReturn: # noqa: U100
raise NotImplementedError('not used by MyNeuralNetClassifier')
# Passes epoch to criterion
def _get_loss(self, y_pred: Tensor, y_true: Tensor, epoch: int) -> Tensor:
y_true = to_tensor(y_true, device=self.device)
return self.criterion_(y_pred, y_true, epoch)
class MyPrintLog(PrintLog):
KEY_ORDER = ('epoch', 'train_loss', 'valid_loss', 'valid_mcc', 'valid_acc', 'dur')
# User-defined key order
def _sorted_keys(self, keys: object) -> list[str]:
skeys = super()._sorted_keys(keys)
if set(skeys) != set(self.KEY_ORDER):
raise ValueError(f'Expected keys: {self.KEY_ORDER}\nGot keys: {skeys}')
return list(self.KEY_ORDER)
class MyAdaBelief(AdaBelief):
def __init__(self, *args: Any, **kwargs: Any) -> None:
kwargs.setdefault('eps', 1e-8)
kwargs.setdefault('rectify', False)
super().__init__(*args, **kwargs)
class MySGDW(SGDW):
def __init__(self, *args: Any, **kwargs: Any) -> None:
kwargs.setdefault('momentum', .9)
super().__init__(*args, **kwargs)
class MyReduceMaxLROnRestart:
def __init__(self, ratio: float, period: int = 1) -> None:
self.ratio = ratio
self.period = period
self.iter = 0
def __call__(self, eta_min: float, eta_max: float) -> tuple[float, float]:
self.iter += 1
if self.iter >= self.period:
eta_max *= self.ratio
self.iter = 0
return eta_min, eta_max
def isclose_nested(a: Union[Tuple[Any, ...], float], b: Union[Tuple[Any, ...], float]) -> bool:
if isinstance(a, tuple):
assert isinstance(b, tuple)
assert len(a) == len(b)
return all(isclose_nested(aa, bb) for aa, bb in zip_strict(a, b))
assert isinstance(a, Real) and isinstance(b, Real)
return math.isclose(a, b)
class ResampleArgs:
def __init__(self, algorithm: Optional[str], kwargs: Dict[str, Any]) -> None:
self.algorithm = algorithm
self.kwargs = kwargs
@classmethod
def parse(cls: Type[AnyResampleArgs], s: str) -> AnyResampleArgs:
if s == 'none':
return cls(None, {})
m, s = s[0], s[1:]
if m not in '+-':
raise ValueError("Resample: Expected mode of '+' or '-', got {!r}".format(m))
alg = 'ML-ROS' if m == '+' else 'ML-RUS'
kwargs: Dict[str, Any] = {}
if not s:
return cls(alg, kwargs)
args = s.split(':')
if len(args) > 3:
raise ValueError('Resample: Expected at most 3 arguments, got {}'.format(len(args)))
it = iter(args)
try:
if arg := next(it):
kwargs['resample_limit'] = float(arg) / 100
if arg := next(it):
kwargs['imbalance_target'] = float(arg)
if arg := next(it):
if arg not in ('pos', 'all'):
raise ValueError("Resample: Expected imbalance mode of 'pos' or 'all', got {!r}".format(arg))
kwargs['mode'] = arg
except StopIteration:
pass
return cls(alg, kwargs)
class ResampledLabeledSubset(LabeledDataset):
def __init__(self, dataset: LabeledDataset, indices: Optional[Sequence[int]], # pytype: disable=module-attr
rand: np.random.RandomState) -> None:
self.dataset = dataset
self.indices = indices
self.rand = rand
@classmethod
def new(cls: Type[AnyRLS], dataset: LabeledDataset) -> AnyRLS:
inst = cls(
dataset, None,
np.random.RandomState(np.random.randint(0, 2**32)), # pytype: disable=module-attr
)
inst._init()
return inst
@classmethod
def load(cls: Type[AnyRLS], dataset: LabeledDataset, # pytype: disable=module-attr
indices: Optional[Sequence[int]], rand: np.random.RandomState) -> AnyRLS:
return cls(dataset, indices, rand)
def __getitem__(self, index: int) -> Tuple[Any, Tensor]:
if self.indices is None:
return self.dataset[index]
return self.dataset[self.indices[index]]
def __len__(self) -> int:
return len(self.dataset) if self.indices is None else len(self.indices)
@property
def labelset(self) -> Sequence[Set[str]]:
if self.indices is None: