-
Notifications
You must be signed in to change notification settings - Fork 2
/
util.py
6164 lines (5373 loc) · 227 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
from __future__ import print_function
import argparse
from collections import Counter, OrderedDict, Iterable
import contextlib
from datetime import datetime
import os
import pdb
import math
from math import gcd
from numbers import Number
import numpy as np
from copy import deepcopy, copy
from functools import reduce
from IPython.display import Image, display
import itertools
import json
import operator
import pickle
import random
from sklearn.cluster import SpectralClustering
from sklearn.model_selection import train_test_split
import scipy.linalg
import sys
from termcolor import colored
import time
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import torch.optim as optim
from torch.nn.modules.loss import _Loss
from torch.autograd import Function
from torch.utils.data import Dataset, Sampler
from torch.optim.lr_scheduler import _LRScheduler
import torch.distributed as dist
from typing import Iterator, Iterable, Optional, Sequence, List, TypeVar, Generic, Sized, Union
PrecisionFloorLoss = 2 ** (-32)
CLASS_TYPES = ["MLP", "Multi_MLP", "Branching_Net", "Fan_in_MLP", "Model_Ensemble", "Model_with_uncertainty",
"RNNCellBase", "LSTM", "Wide_ResNet", "Conv_Net", "Conv_Model", "Conv_Autoencoder", "VAE", "Net_reparam", "Mixture_Gaussian", "Triangular_dist"]
ACTIVATION_LIST = ["relu", "leakyRelu", "leakyReluFlat", "tanh", "softplus", "sigmoid", "selu", "elu", "sign", "heaviside", "softmax", "negLogSoftmax", "naturalLogSoftmax"]
COLOR_LIST = ["b", "r", "g", "y", "c", "m", "skyblue", "indigo", "goldenrod", "salmon", "pink",
"silver", "darkgreen", "lightcoral", "navy", "orchid", "steelblue", "saddlebrown",
"orange", "olive", "tan", "firebrick", "maroon", "darkslategray", "crimson", "dodgerblue", "aquamarine",
"b", "r", "g", "y", "c", "m", "skyblue", "indigo", "goldenrod", "salmon", "pink",
"silver", "darkgreen", "lightcoral", "navy", "orchid", "steelblue", "saddlebrown",
"orange", "olive", "tan", "firebrick", "maroon", "darkslategray", "crimson", "dodgerblue", "aquamarine"]
LINESTYLE_LIST = ["-", "--", ":", "-."]
MARKER_LIST = ["o", "+", "x", "v", ".", "D"]
T_co = TypeVar('T_co', covariant=True)
def plot_matrices(
matrix_list,
shape = None,
images_per_row = 10,
scale_limit = None,
figsize = None,
x_axis_list = None,
filename = None,
title = None,
subtitles = [],
highlight_bad_values = True,
plt = None,
pdf = None,
verbose = False,
no_xlabel = False,
cmap = None,
is_balanced = False,
):
"""Plot the images for each matrix in the matrix_list.
Adapted from https://github.com/tailintalent/pytorch_net/blob/c1cfda5e90fef9503c887f5061cb7b1262133ac0/util.py#L54
Args:
is_balanced: if True, the scale_min and scale_max will have the same absolute value but opposite sign.
cmap: choose from None, "PiYG", "jet", etc.
"""
import matplotlib
from matplotlib import pyplot as plt
n_rows = max(len(matrix_list) // images_per_row, 1)
fig = plt.figure(figsize=(24, n_rows*5) if figsize is None else figsize)
fig.set_canvas(plt.gcf().canvas)
if title is not None:
fig.suptitle(title, fontsize = 18, horizontalalignment = 'left', x=0.1)
# To np array. If None, will transform to NaN:
matrix_list_new = []
for i, element in enumerate(matrix_list):
if element is not None:
matrix_list_new.append(to_np_array(element))
else:
matrix_list_new.append(np.array([[np.NaN]]))
matrix_list = matrix_list_new
num_matrixs = len(matrix_list)
rows = int(np.ceil(num_matrixs / float(images_per_row)))
try:
matrix_list_reshaped = np.reshape(np.array(matrix_list), (-1, shape[0],shape[1])) \
if shape is not None else np.array(matrix_list)
except:
matrix_list_reshaped = matrix_list
if scale_limit == "auto":
scale_min = np.Inf
scale_max = -np.Inf
for matrix in matrix_list:
scale_min = min(scale_min, np.min(matrix))
scale_max = max(scale_max, np.max(matrix))
scale_limit = (scale_min, scale_max)
if is_balanced:
scale_min, scale_max = -max(abs(scale_min), abs(scale_max)), max(abs(scale_min), abs(scale_max))
for i in range(len(matrix_list)):
ax = fig.add_subplot(rows, images_per_row, i + 1)
image = matrix_list_reshaped[i].astype(float)
if len(image.shape) == 1:
image = np.expand_dims(image, 1)
if highlight_bad_values:
cmap = copy(plt.cm.get_cmap("binary" if cmap is None else cmap))
cmap.set_bad('red', alpha = 0.2)
mask_key = []
mask_key.append(np.isnan(image))
mask_key.append(np.isinf(image))
mask_key = np.any(np.array(mask_key), axis = 0)
image = np.ma.array(image, mask = mask_key)
else:
cmap = matplotlib.cm.binary if cmap is None else cmap
if scale_limit is None:
ax.matshow(image, cmap = cmap)
else:
assert len(scale_limit) == 2, "scale_limit should be a 2-tuple!"
if is_balanced:
scale_min, scale_max = scale_limit
scale_limit = -max(abs(scale_min), abs(scale_max)), max(abs(scale_min), abs(scale_max))
ax.matshow(image, cmap = cmap, vmin = scale_limit[0], vmax = scale_limit[1])
if len(subtitles) > 0:
ax.set_title(subtitles[i])
if not no_xlabel:
try:
xlabel = "({0:.4f},{1:.4f})\nshape: ({2}, {3})".format(np.min(image), np.max(image), image.shape[0], image.shape[1])
if x_axis_list is not None:
xlabel += "\n{}".format(x_axis_list[i])
plt.xlabel(xlabel)
except:
pass
plt.xticks(np.array([]))
plt.yticks(np.array([]))
# if cmap is not None:
# cax = plt.axes([0.85, 0.1, 0.075, 0.8])
# plt.colorbar(cax=cax)
# cbar_ax = fig.add_axes([0.92, 0.3, 0.01, 0.4])
# plt.colorbar(cax=cbar_ax)
if filename is not None:
plt.tight_layout()
plt.savefig(filename, bbox_inches="tight", dpi=400)
if pdf is not None:
pdf.savefig() # saves the current figure into a pdf page
plt.close()
else:
plt.show()
if scale_limit is not None:
if verbose:
print("scale_limit: ({0:.6f}, {1:.6f})".format(scale_limit[0], scale_limit[1]))
print()
def plot_simple(
x=None,
y=None,
title=None,
xlabel=None,
ylabel=None,
ylim=None,
figsize=(7,5),
):
plt.figure(figsize=figsize)
if x is None:
plt.plot(y)
else:
plt.plot(x, y)
if title is not None:
plt.title(title, fontsize=fontsize)
if xlabel is not None:
plt.xlabel(xlabel, fontsize=fontsize)
if ylabel is not None:
plt.ylabel(ylabel, fontsize=fontsize)
plt.tick_params(labelsize=fontsize)
if ylim is not None:
plt.ylim(ylim)
plt.show()
def plot_2_axis(
x,
y1,
y2,
xlabel=None,
ylabel1=None,
ylabel2=None,
ylim1=None,
ylim2=None,
title=None,
figsize=(7,5),
fontsize=14,
):
import matplotlib.pylab as plt
fig, ax1 = plt.subplots(figsize=figsize)
color = 'tab:blue'
if xlabel is not None:
ax1.set_xlabel(xlabel, fontsize=fontsize)
if ylabel1 is not None:
ax1.set_ylabel(ylabel1, color=color, fontsize=fontsize)
ax1.plot(x, y1, color=color)
ax1.tick_params(axis='y', labelcolor=color, labelsize=fontsize-1)
if ylim1 is not None:
ax1.set_ylim(ylim1)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
color = 'tab:red'
if ylabel2 is not None:
ax2.set_ylabel(ylabel2, color=color, fontsize=fontsize) # we already handled the x-label with ax1
ax2.plot(x, y2, color=color)
ax2.tick_params(axis='y', labelcolor=color, labelsize=fontsize-1)
if ylim2 is not None:
ax2.set_ylim(ylim2)
fig.tight_layout() # otherwise the right y-label is slightly clipped
if title is not None:
plt.title(title, fontsize=fontsize)
plt.show()
def plot_vectors(
Dict,
x_range=None,
xlabel=None,
ylabel=None,
title=None,
ylim=None,
fontsize=14,
linestyle_dict=None,
figsize=(15,5),
is_logscale=True,
is_standard_error=False,
**kwargs
):
"""Plot learning curve (all losses)."""
def get_setting(key, setting_dict):
setting = "-"
if setting_dict is not None:
for setting_key in setting_dict:
if setting_key in key:
setting = setting_dict[setting_key]
break
return setting
from matplotlib import pyplot as plt
if not isinstance(Dict, dict):
Dict = {"item": Dict}
plt.figure(figsize=figsize)
if is_logscale:
plt.subplot(1,2,1)
first_key = next(iter(Dict))
if x_range is None:
if isinstance(Dict[first_key][0], Number):
x_range = np.arange(len(Dict[first_key]))
else:
x_range = np.arange(Dict[first_key].shape[1])
for key in Dict:
#pdb.set_trace()
if type(Dict[key])!=list:
continue
if len(Dict[key])!=len(x_range):
continue
if isinstance(Dict[key][0], Number):
plt.plot(x_range, to_np_array(Dict[key]), label=key, linestyle=get_setting(key, linestyle_dict), **kwargs)
else:
if is_standard_error:
plt.errorbar(x_range, to_np_array(Dict[key]).mean(-1), to_np_array(Dict[key]).std(-1) / np.sqrt(to_np_array(Dict[key]).shape[0]), label=key, linestyle=get_setting(key, linestyle_dict), capsize=2, **kwargs)
else:
plt.errorbar(x_range, to_np_array(Dict[key]).mean(-1), to_np_array(Dict[key]).std(-1), label=key, linestyle=get_setting(key, linestyle_dict), capsize=2, **kwargs)
#pdb.set_trace()
if xlabel is not None:
plt.xlabel(xlabel, fontsize=fontsize)
if ylabel is not None:
plt.ylabel(ylabel, fontsize=fontsize)
if title is not None:
plt.title(title, fontsize=fontsize)
if ylim is not None:
plt.ylim(ylim)
plt.tick_params(labelsize=fontsize)
if is_logscale:
plt.subplot(1,2,2)
for key in Dict:
#pdb.set_trace()
if type(Dict[key])!=list:
continue
if len(Dict[key])!=len(x_range):
continue
if isinstance(Dict[key][0], Number):
plt.semilogy(x_range, to_np_array(Dict[key]), label=key, linestyle=get_setting(key, linestyle_dict), **kwargs)
else:
if is_standard_error:
plt.errorbar(x_range, to_np_array(Dict[key]).mean(-1), to_np_array(Dict[key]).std(-1) / np.sqrt(to_np_array(Dict[key]).shape[0]), label=key, linestyle=get_setting(key, linestyle_dict), capsize=2, **kwargs)
else:
plt.errorbar(x_range, to_np_array(Dict[key]).mean(-1), to_np_array(Dict[key]).std(-1), label=key, linestyle=get_setting(key, linestyle_dict), capsize=2, **kwargs)
ax = plt.gca()
ax.set_yscale("log")
if xlabel is not None:
plt.xlabel(xlabel, fontsize=fontsize)
if ylabel is not None:
plt.ylabel(ylabel, fontsize=fontsize)
if title is not None:
plt.title("{} (log-scale)".format(title), fontsize=fontsize)
if ylim is not None:
plt.ylim(ylim)
plt.tick_params(labelsize=fontsize)
plt.legend(bbox_to_anchor=[1, 1], fontsize=fontsize-2)
plt.show()
class Recursive_Loader(object):
"""A recursive loader, able to deal with any depth of X"""
def __init__(self, X, y, batch_size):
self.X = X
self.y = y
self.batch_size = batch_size
self.length = int(len(self.y) / self.batch_size)
self.idx_list = torch.randperm(len(self.y))
def __iter__(self):
self.current = 0
return self
def __next__(self):
if self.current < self.length:
idx = self.idx_list[self.current * self.batch_size: (self.current + 1) * self.batch_size]
self.current += 1
return recursive_index((self.X, self.y), idx)
else:
self.idx_list = torch.randperm(len(self.y))
raise StopIteration
def recursive_index(data, idx):
"""Recursively obtain the idx of data"""
data_new = []
for i, element in enumerate(data):
if isinstance(element, tuple):
data_new.append(recursive_index(element, idx))
else:
data_new.append(element[idx])
return data_new
def record_data(data_record_dict, data_list, key_list, nolist=False, ignore_duplicate=False, recent_record=-1):
"""Record data to the dictionary data_record_dict. It records each key: value pair in the corresponding location of
key_list and data_list into the dictionary."""
if not isinstance(data_list, list):
data_list = [data_list]
if not isinstance(key_list, list):
key_list = [key_list]
assert len(data_list) == len(key_list), "the data_list and key_list should have the same length!"
for data, key in zip(data_list, key_list):
if nolist:
data_record_dict[key] = data
else:
if key not in data_record_dict:
data_record_dict[key] = [data]
else:
if (not ignore_duplicate) or (data not in data_record_dict[key]):
data_record_dict[key].append(data)
if recent_record != -1:
# Only keep the most recent records
data_record_dict[key] = data_record_dict[key][-recent_record:]
def transform_dict(Dict, mode="array"):
if mode == "array":
return {key: np.array(item) for key, item in Dict.items()}
if mode == "concatenate":
return {key: np.concatenate(item) for key, item in Dict.items()}
elif mode == "torch":
return {key: torch.FloatTensor(item) for key, item in Dict.items()}
elif mode == "mean":
return {key: np.mean(item) for key, item in Dict.items()}
elif mode == "std":
return {key: np.std(item) for key, item in Dict.items()}
elif mode == "sum":
return {key: np.sum(item) for key, item in Dict.items()}
elif mode == "prod":
return {key: np.prod(item) for key, item in Dict.items()}
else:
raise
def to_np_array(*arrays, **kwargs):
array_list = []
for array in arrays:
if array is None:
array_list.append(array)
continue
if isinstance(array, Variable):
if array.is_cuda:
array = array.cpu()
array = array.data
if isinstance(array, torch.Tensor) or isinstance(array, torch.FloatTensor) or isinstance(array, torch.LongTensor) or isinstance(array, torch.ByteTensor) or \
isinstance(array, torch.cuda.FloatTensor) or isinstance(array, torch.cuda.LongTensor) or isinstance(array, torch.cuda.ByteTensor):
if array.is_cuda:
array = array.cpu()
array = array.numpy()
if isinstance(array, Number):
pass
elif isinstance(array, list) or isinstance(array, tuple):
array = np.array(array)
elif array.shape == (1,):
if "full_reduce" in kwargs and kwargs["full_reduce"] is False:
pass
else:
array = array[0]
elif array.shape == ():
array = array.tolist()
array_list.append(array)
if len(array_list) == 1:
if not ("keep_list" in kwargs and kwargs["keep_list"]):
array_list = array_list[0]
return array_list
def to_Variable(*arrays, **kwargs):
"""Transform numpy arrays into torch tensors/Variables"""
is_cuda = kwargs["is_cuda"] if "is_cuda" in kwargs else False
requires_grad = kwargs["requires_grad"] if "requires_grad" in kwargs else False
array_list = []
for array in arrays:
is_int = False
if isinstance(array, Number):
is_int = True if isinstance(array, int) else False
array = [array]
if isinstance(array, np.ndarray) or isinstance(array, list) or isinstance(array, tuple):
is_int = True if np.array(array).dtype.name == "int64" else False
array = torch.tensor(array).float()
if isinstance(array, torch.FloatTensor) or isinstance(array, torch.LongTensor) or isinstance(array, torch.ByteTensor):
array = Variable(array, requires_grad=requires_grad)
if "preserve_int" in kwargs and kwargs["preserve_int"] is True and is_int:
array = array.long()
array = set_cuda(array, is_cuda)
array_list.append(array)
if len(array_list) == 1:
array_list = array_list[0]
return array_list
def to_Variable_recur(item, type='float'):
"""Recursively transform numpy array into PyTorch tensor."""
if isinstance(item, dict):
return {key: to_Variable_recur(value, type=type) for key, value in item.items()}
elif isinstance(item, tuple):
return tuple(to_Variable_recur(element, type=type) for element in item)
else:
try:
if type == "long":
return torch.LongTensor(item)
elif type == "float":
return torch.FloatTensor(item)
elif type == "bool":
return torch.BoolTensor(item)
except:
return [to_Variable_recur(element, type=type) for element in item]
def to_Boolean(tensor):
"""Transform to Boolean tensor. For PyTorch version >= 1.2, use bool(). Otherwise use byte()"""
version = torch.__version__
version = eval(".".join(version.split(".")[:-1]))
if version >= 1.2:
return tensor.bool()
else:
return tensor.byte()
def init_module_weights(module_list, init_weights_mode = "glorot-normal"):
if not isinstance(module_list, list):
module_list = [module_list]
for module in module_list:
if init_weights_mode == "glorot-uniform":
glorot_uniform_limit = np.sqrt(6 / float(module.in_features + module.out_features))
module.weight.data.uniform_(-glorot_uniform_limit, glorot_uniform_limit)
elif init_weights_mode == "glorot-normal":
glorot_normal_std = np.sqrt(2 / float(module.in_features + module.out_features))
module.weight.data.normal_(mean = 0, std = glorot_normal_std)
else:
raise Exception("init_weights_mode '{0}' not recognized!".format(init_weights_mode))
def init_module_bias(module_list, init_bias_mode = "zeros"):
if not isinstance(module_list, list):
module_list = [module_list]
for module in module_list:
if init_bias_mode == "zeros":
module.bias.data.fill_(0)
else:
raise Exception("init_bias_mode '{0}' not recognized!".format(init_bias_mode))
def init_weight(weight_list, init):
"""Initialize the weights"""
if not isinstance(weight_list, list):
weight_list = [weight_list]
for weight in weight_list:
if len(weight.size()) == 2:
rows = weight.size(0)
columns = weight.size(1)
elif len(weight.size()) == 1:
rows = 1
columns = weight.size(0)
if init is None:
init = "glorot-normal"
if not isinstance(init, str):
weight.data.copy_(torch.FloatTensor(init))
else:
if init == "glorot-normal":
glorot_normal_std = np.sqrt(2 / float(rows + columns))
weight.data.normal_(mean = 0, std = glorot_normal_std)
else:
raise Exception("init '{0}' not recognized!".format(init))
def init_bias(bias_list, init):
"""Initialize the bias"""
if not isinstance(bias_list, list):
bias_list = [bias_list]
for bias in bias_list:
if init is None:
init = "zeros"
if not isinstance(init, str):
bias.data.copy_(torch.FloatTensor(init))
else:
if init == "zeros":
bias.data.fill_(0)
else:
raise Exception("init '{0}' not recognized!".format(init))
def get_activation(activation):
"""Get activation"""
assert activation in ACTIVATION_LIST + ["linear"]
if activation == "linear":
f = lambda x: x
elif activation == "relu":
f = F.relu
elif activation == "leakyRelu":
f = nn.LeakyReLU(negative_slope = 0.3)
elif activation == "leakyReluFlat":
f = nn.LeakyReLU(negative_slope = 0.01)
elif activation == "tanh":
f = torch.tanh
elif activation == "softplus":
f = F.softplus
elif activation == "sigmoid":
f = torch.sigmoid
elif activation == "selu":
f = F.selu
elif activation == "elu":
f = F.elu
elif activation == "sign":
f = lambda x: torch.sign(x)
elif activation == "heaviside":
f = lambda x: (torch.sign(x) + 1) / 2.
elif activation == "softmax":
f = lambda x: nn.Softmax(dim=-1)(x)
elif activation == "negLogSoftmax":
f = lambda x: -torch.log(nn.Softmax(dim=-1)(x))
elif activation == "naturalLogSoftmax":
def natlogsoftmax(x):
x = torch.cat((x, torch.zeros_like(x[..., :1])), axis=-1)
norm = torch.logsumexp(x, axis=-1, keepdim=True)
return -(x - norm)
f = natlogsoftmax
elif act_name == "silu":
f = F.silu
elif act_name == "selu":
f = F.selu
elif act_name == "prelu":
f = F.prelu
elif act_name == "rrelu":
f = F.rrelu
elif act_name == "mish":
f = F.mish
elif act_name == "celu":
f = F.celu
else:
raise Exception("activation {0} not recognized!".format(activation))
return f
def get_activation_noise(act_noise):
noise_type = act_noise["type"]
if noise_type == "identity":
f = lambda x: x
elif noise_type == "gaussian":
f = lambda x: x + torch.randn(x.shape) * act_noise["scale"]
elif noise_type == "uniform":
f = lambda x: x + (torch.rand(x.shape) - 0.5) * act_noise["scale"]
else:
raise Exception("act_noise {} is not valid!".format(noise_type))
return f
class MAELoss(_Loss):
"""Mean absolute loss"""
def __init__(self, size_average=None, reduce=None):
super(MAELoss, self).__init__(size_average)
self.reduce = reduce
def forward(self, input, target):
assert not target.requires_grad, \
"nn criterions don't compute the gradient w.r.t. targets - please " \
"mark these variables as volatile or not requiring gradients"
loss = (input - target).abs()
if self.reduce:
if self.size_average:
loss = loss.mean()
else:
loss = loss.sum()
return loss
class L2Loss(nn.Module):
"""L2 loss, square root of MSE on each example."""
def __init__(self, reduction="mean", first_dim=1, keepdims=False, epsilon=1e-10):
super().__init__()
self.reduction = reduction
self.first_dim = first_dim
self.keepdims = keepdims
self.epsilon = epsilon
def forward(self, pred, y):
reduction_dims = tuple(range(self.first_dim,len(pred.shape)))
loss = ((pred - y).square().sum(reduction_dims) + self.epsilon).sqrt()
if self.reduction == "mean":
loss = loss.mean(dim=tuple(range(self.first_dim)), keepdims=self.keepdims)
elif self.reduction == "sum":
loss = loss.sum(dim=tuple(range(self.first_dim)), keepdim=self.keepdims)
elif self.reduction == "none":
pass
else:
raise
return loss
class MultihotBinaryCrossEntropy(_Loss):
"""Multihot cross-entropy loss."""
def __init__(self, size_average=None, reduce=None):
super(MultihotBinaryCrossEntropy, self).__init__(size_average)
self.reduce = reduce
def forward(self, input, target):
assert not target.requires_grad, \
"nn criterions don't compute the gradient w.r.t. targets - please " \
"mark these variables as volatile or not requiring gradients"
target = torch.tensor(np.concatenate(([np.eye(10)[target[:,c]] for c in range(target.shape[1])]), axis=1))
return F.binary_cross_entropy_with_logits(input, target, reduce=self.reduce)
def get_criterion(loss_type, reduce=None, **kwargs):
"""Get loss function"""
if loss_type == "huber":
criterion = nn.SmoothL1Loss(reduce=reduce)
elif loss_type == "mse":
criterion = nn.MSELoss(reduce=reduce)
elif loss_type == "mae":
criterion = MAELoss(reduce=reduce)
elif loss_type == "DL":
criterion = Loss_Fun(core="DL",
loss_precision_floor=kwargs["loss_precision_floor"] if "loss_precision_floor" in kwargs and kwargs["loss_precision_floor"] is not None else PrecisionFloorLoss,
DL_sum=kwargs["DL_sum"] if "DL_sum" in kwargs else False,
)
elif loss_type == "DLs":
criterion = Loss_Fun(core="DLs",
loss_precision_floor=kwargs["loss_precision_floor"] if "loss_precision_floor" in kwargs and kwargs["loss_precision_floor"] is not None else PrecisionFloorLoss,
DL_sum = kwargs["DL_sum"] if "DL_sum" in kwargs else False,
)
elif loss_type == "mlse":
epsilon = 1e-10
criterion = lambda pred, target: torch.log(nn.MSELoss(reduce=reduce)(pred, target) + epsilon)
elif loss_type == "mse+mlse":
epsilon = 1e-10
criterion = lambda pred, target: torch.log(nn.MSELoss(reduce=reduce)(pred, target) + epsilon) + nn.MSELoss(reduce=reduce)(pred, target).mean()
elif loss_type == "cross-entropy":
criterion = nn.CrossEntropyLoss(reduce=reduce)
elif loss_type == "multihot-bce":
criterion = MultihotBinaryCrossEntropy(reduce=reduce)
elif loss_type == "Loss_with_uncertainty":
criterion = Loss_with_uncertainty(core=kwargs["loss_core"] if "loss_core" in kwargs else "mse", epsilon = 1e-6)
elif loss_type[:11] == "Contrastive":
criterion_name = loss_type.split("-")[1]
beta = eval(loss_type.split("-")[2])
criterion = ContrastiveLoss(get_criterion(criterion_name, reduce=reduce, **kwargs), beta=beta)
else:
raise Exception("loss_type {0} not recognized!".format(loss_type))
return criterion
def get_criteria_value(model, X, y, criteria_type, criterion, **kwargs):
loss_precision_floor = kwargs["loss_precision_floor"] if "loss_precision_floor" in kwargs else PrecisionFloorLoss
pred = forward(model, X, **kwargs)
# Get loss:
loss = to_np_array(criterion(pred, y))
result = {"loss": loss}
# Get DL:
DL_type = criteria_type if "DL" in criteria_type else "DLs"
data_DL = get_criterion(loss_type = DL_type, loss_precision_floor = loss_precision_floor, DL_sum = True)(pred, y)
data_DL = to_np_array(data_DL)
if not isinstance(model, list):
model = [model]
model_DL = np.sum([model_ele.DL for model_ele in model])
DL = data_DL + model_DL
result["DL"] = DL
result["model_DL"] = model_DL
result["data_DL"] = data_DL
# Specify criteria_value:
if criteria_type == "loss":
criteria_value = loss
elif "DL" in criteria_type:
criteria_value = DL
else:
raise Exception("criteria type {0} not valid".format(criteria_type))
print(result)
return criteria_value, result
def get_optimizer(optim_type, lr, parameters, **kwargs):
"""Get optimizer"""
momentum = kwargs["momentum"] if "momentum" in kwargs else 0
if optim_type == "adam":
amsgrad = kwargs["amsgrad"] if "amsgrad" in kwargs else False
optimizer = optim.Adam(parameters, lr=lr, amsgrad=amsgrad)
elif optim_type == "sgd":
nesterov = kwargs["nesterov"] if "nesterov" in kwargs else False
optimizer = optim.SGD(parameters, lr=lr, momentum=momentum, nesterov=nesterov)
elif optim_type == "adabound":
import adabound
optimizer = adabound.AdaBound(parameters, lr=lr, final_lr=0.1 if "final_lr" not in kwargs else kwargs["final_lr"])
elif optim_type == "RMSprop":
optimizer = optim.RMSprop(parameters, lr=lr, momentum=momentum)
elif optim_type == "LBFGS":
optimizer = optim.LBFGS(parameters, lr=lr)
else:
raise Exception("optim_type {0} not recognized!".format(optim_type))
return optimizer
def get_full_struct_param_ele(struct_param, settings):
struct_param_new = deepcopy(struct_param)
for i, layer_struct_param in enumerate(struct_param_new):
if settings is not None and layer_struct_param[1] != "Symbolic_Layer":
layer_struct_param[2] = {key: value for key, value in deepcopy(settings).items() if key in ["activation"]}
layer_struct_param[2].update(struct_param[i][2])
else:
layer_struct_param[2] = deepcopy(struct_param[i][2])
return struct_param_new
def get_full_struct_param(struct_param, settings):
struct_param_new_list = []
if isinstance(struct_param, tuple):
for i, struct_param_ele in enumerate(struct_param):
if isinstance(settings, tuple):
settings_ele = settings[i]
else:
settings_ele = settings
struct_param_new_list.append(get_full_struct_param_ele(struct_param_ele, settings_ele))
return tuple(struct_param_new_list)
else:
return get_full_struct_param_ele(struct_param, settings)
class Early_Stopping(object):
"""Class for monitoring and suggesting early stopping"""
def __init__(self, patience=100, epsilon=0, mode="min"):
self.patience = patience
self.epsilon = epsilon
self.mode = mode
self.best_value = None
self.wait = 0
def reset(self, value=None):
self.best_value = value
self.wait = 0
def monitor(self, value):
if self.patience == -1:
self.wait += 1
return False
to_stop = False
if self.patience is not None:
if self.best_value is None:
self.best_value = value
self.wait = 0
else:
if (self.mode == "min" and value < self.best_value - self.epsilon) or \
(self.mode == "max" and value > self.best_value + self.epsilon):
self.best_value = value
self.wait = 0
else:
if self.wait >= self.patience:
to_stop = True
else:
self.wait += 1
return to_stop
def __repr__(self):
return "Early_Stopping(patience={}, epsilon={}, mode={}, wait={})".format(self.patience, self.epsilon, self.mode, self.wait)
class Performance_Monitor(object):
def __init__(self, patience = 100, epsilon = 0, compare_mode = "absolute"):
self.patience = patience
self.epsilon = epsilon
self.compare_mode = compare_mode
self.reset()
def reset(self):
self.best_value = None
self.model_list = []
self.wait = 0
self.pivot_id = 0
def monitor(self, value, **kwargs):
to_stop = False
is_accept = False
if self.best_value is None:
self.best_value = value
self.wait = 0
self.model_list = [deepcopy(kwargs)]
log = deepcopy(self.model_list)
is_accept = True
else:
self.model_list.append(deepcopy(kwargs))
log = deepcopy(self.model_list)
if self.compare_mode == "absolute":
is_better = (value <= self.best_value + self.epsilon)
elif self.compare_mode == "relative":
is_better = (value <= self.best_value * (1 + self.epsilon))
else:
raise
if is_better:
self.best_value = value
self.pivot_id = self.pivot_id + 1 + self.wait
self.wait = 0
self.model_list = [deepcopy(kwargs)]
is_accept = True
else:
if self.wait >= self.patience:
to_stop = True
else:
self.wait += 1
return to_stop, deepcopy(self.model_list[0]), log, is_accept, deepcopy(self.pivot_id)
def flatten(*tensors):
"""Flatten the tensor except the first dimension"""
new_tensors = []
for tensor in tensors:
if isinstance(tensor, torch.Tensor):
new_tensor = tensor.contiguous().view(tensor.shape[0], -1)
elif isinstance(tensor, np.ndarray):
new_tensor = tensor.reshape(tensor.shape[0], -1)
else:
print(new_tensor)
raise Exception("tensors must be either torch.Tensor or np.ndarray!")
new_tensors.append(new_tensor)
if len(new_tensors) == 1:
new_tensors = new_tensors[0]
return new_tensors
def expand_indices(vector, expand_size):
"""Expand each element ele in the vector to range(ele * expand_size, (ele + 1) * expand_size)"""
assert isinstance(vector, torch.Tensor)
vector *= expand_size
vector_expand = [vector + i for i in range(expand_size)]
vector_expand = torch.stack(vector_expand, 0)
vector_expand = vector_expand.transpose(0, 1).contiguous().view(-1)
return vector_expand
def to_one_hot(idx, num):
"""Transform a 1D vector into a one-hot vector with num classes"""
if len(idx.size()) == 1:
idx = idx.unsqueeze(-1)
if not isinstance(idx, Variable):
if isinstance(idx, np.ndarray):
idx = torch.LongTensor(idx)
idx = Variable(idx, requires_grad=False)
onehot = Variable(torch.zeros(idx.size(0), num), requires_grad=False)
onehot = onehot.to(idx.device)
onehot.scatter_(1, idx, 1)
return onehot
def train_test_split(*args, test_size = 0.1):
"""Split the dataset into training and testing sets"""
import torch
num_examples = len(args[0])
train_list = []
test_list = []
if test_size is not None:
num_test = int(num_examples * test_size)
num_train = num_examples - num_test
idx_train = np.random.choice(range(num_examples), size = num_train, replace = False)
idx_test = set(range(num_examples)) - set(idx_train)
device = args[0].device
idx_train = torch.LongTensor(list(idx_train)).to(device)
idx_test = torch.LongTensor(list(idx_test)).to(device)
for arg in args:
train_list.append(arg[idx_train])
test_list.append(arg[idx_test])
else:
train_list = args
test_list = args
return train_list, test_list
def make_dir(filename):
"""Make directory using filename if the directory does not exist"""
import os
import errno
if not os.path.exists(os.path.dirname(filename)):
print("directory {0} does not exist, created.".format(os.path.dirname(filename)))
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
print(exc)
raise
def get_accuracy(pred, target):
"""Get accuracy from prediction and target"""
assert len(pred.shape) == len(target.shape) == 1
assert len(pred) == len(target)
pred, target = to_np_array(pred, target)
accuracy = ((pred == target).sum().astype(float) / len(pred))
return accuracy
def get_model_accuracy(model, X, y, **kwargs):
"""Get accuracy from model, X and target"""
is_tensor = kwargs["is_tensor"] if "is_tensor" in kwargs else False
pred = model(X)
assert len(pred.shape) == 2
assert isinstance(y, torch.LongTensor) or isinstance(y, torch.cuda.LongTensor)
assert len(y.shape) == 1
pred_max = pred.max(-1)[1]
acc = (y == pred_max).float().mean()
if not is_tensor:
acc = to_np_array(acc)
return acc
def normalize_tensor(X, new_range = None, mean = None, std = None):
"""Normalize the tensor's value range to new_range"""
X = X.float()
if new_range is not None:
assert mean is None and std is None
X_min, X_max = X.min().item(), X.max().item()
X_normalized = (X - X_min) / float(X_max - X_min)
X_normalized = X_normalized * (new_range[1] - new_range[0]) + new_range[0]
else:
X_mean = X.mean().item()
X_std = X.std().item()
X_normalized = (X - X_mean) / X_std
X_normalized = X_normalized * std + mean
return X_normalized
def try_eval(string):
"""Try to evaluate a string. If failed, use original string."""
try:
return eval(string)
except:
return string
def try_remove(List, item, is_copy=True):
"""Try to remove an item from the List. If failed, return the original List."""
if is_copy:
List = deepcopy(List)