-
Notifications
You must be signed in to change notification settings - Fork 3
/
GIB.py
4391 lines (3772 loc) · 203 KB
/
GIB.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 python
# coding: utf-8
# In[ ]:
from __future__ import print_function
import numpy as np
import pprint as pp
from copy import deepcopy
import pickle
from numbers import Number
from collections import OrderedDict
import itertools
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn import functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import ReduceLROnPlateau, LambdaLR
from torch.distributions import constraints
from torch.distributions.normal import Normal
from torch.distributions.multivariate_normal import MultivariateNormal
from torch.distributions.distribution import Distribution
from torch.distributions.utils import broadcast_all
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from pytorch_net.modules import get_Layer, load_layer_dict, Simple_2_Symbolic
from pytorch_net.util import forward, Loss_Fun, get_activation, get_criterion, get_criteria_value, get_optimizer, get_full_struct_param, plot_matrices, get_model_DL, PrecisionFloorLoss, get_list_DL, init_weight
from pytorch_net.util import Early_Stopping, Performance_Monitor, record_data, to_np_array, to_Variable, make_dir, formalize_value, RampupLR, Transform_Label, view_item, load_model, save_model, to_cpu_recur, filter_kwargs
# ## Training functionality:
# In[ ]:
def train(
model,
X = None,
y = None,
train_loader = None,
validation_data = None,
validation_loader = None,
criterion = nn.MSELoss(),
inspect_interval = 10,
isplot = False,
is_cuda = None,
**kwargs
):
"""Training function for generic models. "model" can be a single model or a ordered list of models"""
def get_regularization(model, loss_epoch, **kwargs):
"""Compute regularization."""
reg_dict = kwargs["reg_dict"] if "reg_dict" in kwargs else None
reg = to_Variable([0], is_cuda = is_cuda)
if reg_dict is not None:
for reg_type, reg_coeff in reg_dict.items():
# Setting up regularization strength:
if isinstance(reg_coeff, Number):
reg_coeff_ele = reg_coeff
else:
if loss_epoch < len(reg_coeff):
reg_coeff_ele = reg_coeff[loss_epoch]
else:
reg_coeff_ele = reg_coeff[-1]
# Accumulate regularization:
reg = reg + model.get_regularization(source=[reg_type], mode=reg_mode, **kwargs) * reg_coeff_ele
return reg
if is_cuda is None:
if X is None and y is None:
assert train_loader is not None
is_cuda = train_loader.dataset.tensors[0].is_cuda
else:
is_cuda = X.is_cuda
# Optimization kwargs:
epochs = kwargs["epochs"] if "epochs" in kwargs else 10000
lr = kwargs["lr"] if "lr" in kwargs else 5e-3
lr_rampup_steps = kwargs["lr_rampup"] if "lr_rampup" in kwargs else 200
optim_type = kwargs["optim_type"] if "optim_type" in kwargs else "adam"
optim_kwargs = kwargs["optim_kwargs"] if "optim_kwargs" in kwargs else {}
scheduler_type = kwargs["scheduler_type"] if "scheduler_type" in kwargs else "ReduceLROnPlateau"
gradient_noise = kwargs["gradient_noise"] if "gradient_noise" in kwargs else None
data_loader_apply = kwargs["data_loader_apply"] if "data_loader_apply" in kwargs else None
# Inspection kwargs:
inspect_step = kwargs["inspect_step"] if "inspect_step" in kwargs else None # Whether to inspect each step
inspect_items = kwargs["inspect_items"] if "inspect_items" in kwargs else None
inspect_items_train = get_inspect_items_train(inspect_items)
inspect_functions = kwargs["inspect_functions"] if "inspect_functions" in kwargs else None
if inspect_functions is not None:
for inspect_function_key in inspect_functions:
if inspect_function_key not in inspect_items:
inspect_items.append(inspect_function_key)
inspect_items_interval = kwargs["inspect_items_interval"] if "inspect_items_interval" in kwargs else 1000
inspect_image_interval = kwargs["inspect_image_interval"] if "inspect_image_interval" in kwargs else None
inspect_loss_precision = kwargs["inspect_loss_precision"] if "inspect_loss_precision" in kwargs else 4
callback = kwargs["callback"] if "callback" in kwargs else None
# Saving kwargs:
record_keys = kwargs["record_keys"] if "record_keys" in kwargs else ["loss"]
filename = kwargs["filename"] if "filename" in kwargs else None
if filename is not None:
make_dir(filename)
save_interval = kwargs["save_interval"] if "save_interval" in kwargs else None
save_step = kwargs["save_step"] if "save_step" in kwargs else None
logdir = kwargs["logdir"] if "logdir" in kwargs else None
data_record = {key: [] for key in record_keys}
info_to_save = kwargs["info_to_save"] if "info_to_save" in kwargs else None
if info_to_save is not None:
data_record.update(info_to_save)
patience = kwargs["patience"] if "patience" in kwargs else 20
if patience is not None:
early_stopping_epsilon = kwargs["early_stopping_epsilon"] if "early_stopping_epsilon" in kwargs else 0
early_stopping_monitor = kwargs["early_stopping_monitor"] if "early_stopping_monitor" in kwargs else "loss"
early_stopping = Early_Stopping(patience = patience, epsilon = early_stopping_epsilon, mode = "max" if early_stopping_monitor in ["accuracy"] else "min")
if logdir is not None:
from pytorch_net.logger import Logger
batch_idx = 0
logger = Logger(logdir)
logimages = kwargs["logimages"] if "logimages" in kwargs else None
reg_mode = kwargs["reg_mode"] if "reg_mode" in kwargs else "L1"
if validation_loader is not None:
assert validation_data is None
X_valid, y_valid = None, None
elif validation_data is not None:
X_valid, y_valid = validation_data
else:
X_valid, y_valid = X, y
# Setting up dynamic label noise:
label_noise_matrix = kwargs["label_noise_matrix"] if "label_noise_matrix" in kwargs else None
transform_label = Transform_Label(label_noise_matrix = label_noise_matrix, is_cuda=is_cuda)
# Setting up cotrain optimizer:
co_kwargs = kwargs["co_kwargs"] if "co_kwargs" in kwargs else None
if co_kwargs is not None:
co_optimizer = co_kwargs["co_optimizer"]
co_model = co_kwargs["co_model"]
co_criterion = co_kwargs["co_criterion"] if "co_criterion" in co_kwargs else None
co_multi_step = co_kwargs["co_multi_step"] if "co_multi_step" in co_kwargs else 1
# Get original loss:
if len(inspect_items_train) > 0:
loss_value_train = get_loss(model, train_loader, X, y, criterion=criterion, loss_epoch=-1, transform_label=transform_label, **kwargs)
info_dict_train = prepare_inspection(model, train_loader, X, y, transform_label=transform_label, **kwargs)
if "loss" in record_keys:
record_data(data_record, [loss_value_train], ["loss_tr"])
loss_original = get_loss(model, validation_loader, X_valid, y_valid, criterion=criterion, loss_epoch=-1, transform_label=transform_label, **kwargs)
if "loss" in record_keys:
record_data(data_record, [-1, loss_original], ["iter", "loss"])
if "reg" in record_keys and "reg_dict" in kwargs and len(kwargs["reg_dict"]) > 0:
reg_value = get_regularization(model, loss_epoch=0, **kwargs)
record_data(data_record, [reg_value], ["reg"])
if "param" in record_keys:
record_data(data_record, [model.get_weights_bias(W_source="core", b_source="core")], ["param"])
if "param_grad" in record_keys:
record_data(data_record, [model.get_weights_bias(W_source="core", b_source="core", is_grad=True)], ["param_grad"])
if co_kwargs is not None:
co_loss_original = get_loss(co_model, validation_loader, X_valid, y_valid, criterion=criterion, loss_epoch=-1, transform_label=transform_label, **co_kwargs)
if "co_loss" in record_keys:
record_data(data_record, [co_loss_original], ["co_loss"])
if filename is not None and save_interval is not None:
record_data(data_record, [{}], ["model_dict"])
# Setting up optimizer:
parameters = model.parameters()
num_params = len(list(model.parameters()))
if num_params == 0:
print("No parameters to optimize!")
loss_value = get_loss(model, validation_loader, X_valid, y_valid, criterion = criterion, loss_epoch = -1, transform_label=transform_label, **kwargs)
if "loss" in record_keys:
record_data(data_record, [0, loss_value], ["iter", "loss"])
if "param" in record_keys:
record_data(data_record, [model.get_weights_bias(W_source = "core", b_source = "core")], ["param"])
if "param_grad" in record_keys:
record_data(data_record, [model.get_weights_bias(W_source = "core", b_source = "core", is_grad = True)], ["param_grad"])
if co_kwargs is not None:
co_loss_value = get_loss(co_model, validation_loader, X_valid, y_valid, criterion = criterion, loss_epoch = -1, transform_label=transform_label, **co_kwargs)
record_data(data_record, [co_loss_value], ["co_loss"])
return loss_original, loss_value, data_record
optimizer = get_optimizer(optim_type, lr, parameters, **optim_kwargs) if "optimizer" not in kwargs or ("optimizer" in kwargs and kwargs["optimizer"] is None) else kwargs["optimizer"]
# Initialize inspect_items:
if inspect_items is not None:
print("{}:".format(-1), end = "")
print("\tlr: {0:.3e}\t loss:{1:.{2}f}".format(optimizer.param_groups[0]["lr"], loss_original, inspect_loss_precision), end = "")
info_dict = prepare_inspection(model, validation_loader, X_valid, y_valid, transform_label=transform_label, **kwargs)
if len(inspect_items_train) > 0:
print("\tloss_tr: {0:.{1}f}".format(loss_value_train, inspect_loss_precision), end = "")
info_dict_train = update_key_train(info_dict_train, inspect_items_train)
info_dict.update(info_dict_train)
if "reg" in record_keys and "reg_dict" in kwargs and len(kwargs["reg_dict"]) > 0:
print("\treg:{0:.{1}f}".format(to_np_array(reg_value), inspect_loss_precision), end="")
if len(info_dict) > 0:
for item in inspect_items:
if item in info_dict:
print(" \t{0}: {1:.{2}f}".format(item, info_dict[item], inspect_loss_precision), end = "")
if item in record_keys and item not in ["loss", "reg"]:
record_data(data_record, [to_np_array(info_dict[item])], [item])
if co_kwargs is not None:
co_info_dict = prepare_inspection(co_model, validation_loader, X_valid, y_valid, transform_label=transform_label, **co_kwargs)
if "co_loss" in inspect_items:
co_loss_value = get_loss(co_model, validation_loader, X_valid, y_valid, criterion=criterion, loss_epoch=-1, transform_label=transform_label, **co_kwargs)
print("\tco_loss: {}".format(formalize_value(co_loss_value, inspect_loss_precision)), end="")
if len(co_info_dict) > 0:
for item in inspect_items:
if item in co_info_dict:
print(" \t{0}: {1}".format(item, formalize_value(co_info_dict[item], inspect_loss_precision)), end="")
if item in record_keys and item != "loss":
record_data(data_record, [to_np_array(co_info_dict[item])], [item])
print("\n")
# Setting up gradient noise:
if gradient_noise is not None:
from pytorch_net.util import Gradient_Noise_Scale_Gen
scale_gen = Gradient_Noise_Scale_Gen(epochs=epochs,
gamma=gradient_noise["gamma"], # decay rate
eta=gradient_noise["eta"], # starting variance
gradient_noise_interval_epoch=1,
)
gradient_noise_scale = scale_gen.generate_scale(verbose=True)
# Set up learning rate scheduler:
if scheduler_type is not None:
if scheduler_type == "ReduceLROnPlateau":
scheduler_patience = kwargs["scheduler_patience"] if "scheduler_patience" in kwargs else 40
scheduler_factor = kwargs["scheduler_factor"] if "scheduler_factor" in kwargs else 0.1
scheduler_verbose = kwargs["scheduler_verbose"] if "scheduler_verbose" in kwargs else False
scheduler = ReduceLROnPlateau(optimizer, factor=scheduler_factor, patience=scheduler_patience, verbose=scheduler_verbose)
elif scheduler_type == "LambdaLR":
scheduler_lr_lambda = kwargs["scheduler_lr_lambda"] if "scheduler_lr_lambda" in kwargs else (lambda epoch: 0.97 ** (epoch // 2))
scheduler = LambdaLR(optimizer, lr_lambda=scheduler_lr_lambda)
else:
raise
# Ramping or learning rate for the first lr_rampup_steps steps:
if lr_rampup_steps is not None and train_loader is not None:
scheduler_rampup = RampupLR(optimizer, num_steps=lr_rampup_steps)
if hasattr(train_loader, "dataset"):
data_size = len(train_loader.dataset)
else:
data_size = kwargs["data_size"]
# Initialize logdir:
if logdir is not None:
if logimages is not None:
for tag, image_fun in logimages["image_fun"].items():
image = image_fun(model, logimages["X"], logimages["y"])
logger.log_images(tag, image, -1)
# Training:
to_stop = False
for i in range(epochs + 1):
model.train()
# Updating gradient noise:
if gradient_noise is not None:
hook_handle_list = []
if i % scale_gen.gradient_noise_interval_epoch == 0:
for h in hook_handle_list:
h.remove()
hook_handle_list = []
scale_idx = int(i / scale_gen.gradient_noise_interval_epoch)
if scale_idx >= len(gradient_noise_scale):
current_gradient_noise_scale = gradient_noise_scale[-1]
else:
current_gradient_noise_scale = gradient_noise_scale[scale_idx]
for param_group in optimizer.param_groups:
for param in param_group["params"]:
if param.requires_grad:
h = param.register_hook(lambda grad: grad + Variable(torch.normal(mean=torch.zeros(grad.size()),
std=current_gradient_noise_scale * torch.ones(grad.size()))))
hook_handle_list.append(h)
if X is not None and y is not None:
if optim_type != "LBFGS":
optimizer.zero_grad()
reg = get_regularization(model, loss_epoch=i, **kwargs)
loss = model.get_loss(X, transform_label(y), criterion=criterion, loss_epoch=i, **kwargs) + reg
loss.backward()
optimizer.step()
else:
# "LBFGS" is a second-order optimization algorithm that requires a slightly different procedure:
def closure():
optimizer.zero_grad()
reg = get_regularization(model, loss_epoch=i, **kwargs)
loss = model.get_loss(X, transform_label(y), criterion=criterion, loss_epoch=i, **kwargs) + reg
loss.backward()
return loss
optimizer.step(closure)
# Cotrain step:
if co_kwargs is not None:
if "co_warmup_epochs" not in co_kwargs or "co_warmup_epochs" in co_kwargs and i >= co_kwargs["co_warmup_epochs"]:
for _ in range(co_multi_step):
co_optimizer.zero_grad()
co_reg = get_regularization(co_model, loss_epoch=i, **co_kwargs)
co_loss = co_model.get_loss(X, transform_label(y), criterion=co_criterion, loss_epoch=i, **co_kwargs) + co_reg
co_loss.backward()
co_optimizer.step()
else:
if inspect_step is not None:
info_dict_step = {key: [] for key in inspect_items}
if "loader_process" in kwargs and kwargs["loader_process"] is not None:
train_loader = kwargs["loader_process"]("train")
for k, data_batch in enumerate(train_loader):
if isinstance(data_batch, tuple) or isinstance(data_batch, list):
X_batch, y_batch = data_batch
if data_loader_apply is not None:
X_batch, y_batch = data_loader_apply(X_batch, y_batch)
else:
X_batch, y_batch = data_loader_apply(data_batch)
if optim_type != "LBFGS":
optimizer.zero_grad()
reg = get_regularization(model, loss_epoch=i, **kwargs)
loss = model.get_loss(X_batch, transform_label(y_batch), criterion=criterion, loss_epoch=i, loss_step=k, **kwargs) + reg
loss.backward()
if logdir is not None:
batch_idx += 1
if len(model.info_dict) > 0:
for item in inspect_items:
if item in model.info_dict:
logger.log_scalar(item, model.info_dict[item], batch_idx)
optimizer.step()
else:
def closure():
optimizer.zero_grad()
reg = get_regularization(model, loss_epoch=i, **kwargs)
loss = model.get_loss(X_batch, transform_label(y_batch), criterion=criterion, loss_epoch=i, loss_step=k, **kwargs) + reg
loss.backward()
return loss
if logdir is not None:
batch_idx += 1
if len(model.info_dict) > 0:
for item in inspect_items:
if item in model.info_dict:
logger.log_scalar(item, model.info_dict[item], batch_idx)
optimizer.step(closure)
# Rampup scheduler:
if lr_rampup_steps is not None and i * data_size // len(X_batch) + k < lr_rampup_steps:
scheduler_rampup.step()
# Cotrain step:
if co_kwargs is not None:
if "co_warmup_epochs" not in co_kwargs or "co_warmup_epochs" in co_kwargs and i >= co_kwargs["co_warmup_epochs"]:
for _ in range(co_multi_step):
co_optimizer.zero_grad()
co_reg = get_regularization(co_model, loss_epoch=i, **co_kwargs)
co_loss = co_model.get_loss(X_batch, transform_label(y_batch), criterion=co_criterion, loss_epoch=i, loss_step=k, **co_kwargs) + co_reg
co_loss.backward()
if logdir is not None:
if len(co_model.info_dict) > 0:
for item in inspect_items:
if item in co_model.info_dict:
logger.log_scalar(item, co_model.info_dict[item], batch_idx)
co_optimizer.step()
# Inspect at each step:
if inspect_step is not None:
if k % inspect_step == 0:
print("s{}:".format(k), end = "")
info_dict = prepare_inspection(model, validation_loader, X_valid, y_valid, transform_label=transform_label, **kwargs)
if "loss" in inspect_items:
info_dict_step["loss"].append(loss.item())
print("\tloss: {0:.{1}f}".format(loss.item(), inspect_loss_precision), end="")
if len(info_dict) > 0:
for item in inspect_items:
if item in info_dict:
info_dict_step[item].append(info_dict[item])
print(" \t{0}: {1}".format(item, formalize_value(info_dict[item], inspect_loss_precision)), end = "")
if co_kwargs is not None:
if "co_warmup_epochs" not in co_kwargs or "co_warmup_epochs" in co_kwargs and i >= co_kwargs["co_warmup_epochs"]:
co_info_dict = prepare_inspection(co_model, validation_loader, X_valid, y_valid, transform_label=transform_label, **co_kwargs)
if "co_loss" in inspect_items:
print("\tco_loss: {0:.{1}f}".format(co_loss.item(), inspect_loss_precision), end="")
info_dict_step["co_loss"].append(co_loss.item())
if len(co_info_dict) > 0:
for item in inspect_items:
if item in co_info_dict and item != "co_loss":
info_dict_step[item].append(co_info_dict[item])
print(" \t{0}: {1}".format(item, formalize_value(co_info_dict[item], inspect_loss_precision)), end="")
print()
if k % save_step == 0:
if filename is not None:
pickle.dump(model.model_dict, open(filename[:-2] + "_model.p", "wb"))
if logdir is not None:
# Log values and gradients of the parameters (histogram summary)
# for tag, value in model.named_parameters():
# tag = tag.replace('.', '/')
# logger.log_histogram(tag, to_np_array(value), i)
# logger.log_histogram(tag + '/grad', to_np_array(value.grad), i)
if logimages is not None:
for tag, image_fun in logimages["image_fun"].items():
image = image_fun(model, logimages["X"], logimages["y"])
logger.log_images(tag, image, i)
if i % inspect_interval == 0:
model.eval()
if inspect_items is not None and i % inspect_items_interval == 0 and len(inspect_items_train) > 0:
loss_value_train = get_loss(model, train_loader, X, y, criterion = criterion, loss_epoch = i, transform_label=transform_label, **kwargs)
info_dict_train = prepare_inspection(model, train_loader, X, y, transform_label=transform_label, **kwargs)
loss_value = get_loss(model, validation_loader, X_valid, y_valid, criterion = criterion, loss_epoch = i, transform_label=transform_label, **kwargs)
reg_value = get_regularization(model, loss_epoch = i, **kwargs)
if scheduler_type is not None:
if lr_rampup_steps is None or train_loader is None or (lr_rampup_steps is not None and i * data_size // len(X_batch) + k >= lr_rampup_steps):
if scheduler_type == "ReduceLROnPlateau":
scheduler.step(loss_value)
else:
scheduler.step()
if callback is not None:
assert callable(callback)
callback(model = model,
X = X_valid,
y = y_valid,
iteration = i,
loss = loss_value,
)
if patience is not None:
if early_stopping_monitor == "loss":
to_stop = early_stopping.monitor(loss_value)
else:
info_dict = prepare_inspection(model, validation_loader, X_valid, y_valid, transform_label=transform_label, **kwargs)
to_stop = early_stopping.monitor(info_dict[early_stopping_monitor])
if inspect_items is not None:
if i % inspect_items_interval == 0:
# Get loss:
print("{}:".format(i), end = "")
print("\tlr: {0:.3e}\tloss: {1:.{2}f}".format(optimizer.param_groups[0]["lr"], loss_value, inspect_loss_precision), end = "")
info_dict = prepare_inspection(model, validation_loader, X_valid, y_valid, transform_label=transform_label, **kwargs)
if len(inspect_items_train) > 0:
print("\tloss_tr: {0:.{1}f}".format(loss_value_train, inspect_loss_precision), end = "")
info_dict_train = update_key_train(info_dict_train, inspect_items_train)
info_dict.update(info_dict_train)
if "reg" in inspect_items and "reg_dict" in kwargs and len(kwargs["reg_dict"]) > 0:
print("\treg:{0:.{1}f}".format(to_np_array(reg_value), inspect_loss_precision), end="")
# Print and record:
if len(info_dict) > 0:
for item in inspect_items:
if item + "_val" in info_dict:
print(" \t{0}: {1}".format(item, formalize_value(info_dict[item + "_val"], inspect_loss_precision)), end = "")
if item in record_keys and item not in ["loss", "reg"]:
record_data(data_record, [to_np_array(info_dict[item + "_val"])], [item])
# logger:
if logdir is not None:
for item in inspect_items:
if item + "_val" in info_dict:
logger.log_scalar(item + "_val", info_dict[item + "_val"], i)
# Co_model:
if co_kwargs is not None:
co_loss_value = get_loss(co_model, validation_loader, X_valid, y_valid, criterion = criterion, loss_epoch = i, transform_label=transform_label, **co_kwargs)
co_info_dict = prepare_inspection(co_model, validation_loader, X_valid, y_valid, transform_label=transform_label, **co_kwargs)
if "co_loss" in inspect_items:
print("\tco_loss: {0:.{1}f}".format(co_loss_value, inspect_loss_precision), end="")
if len(co_info_dict) > 0:
for item in inspect_items:
if item + "_val" in co_info_dict:
print(" \t{0}: {1}".format(item, formalize_value(co_info_dict[item + "_val"], inspect_loss_precision)), end="")
if item in record_keys and item != "co_loss":
record_data(data_record, [to_np_array(co_info_dict[item + "_val"])], [item])
if "co_loss" in record_keys:
record_data(data_record, [co_loss_value], ["co_loss"])
# Training metrics:
if inspect_step is not None:
for item in info_dict_step:
if len(info_dict_step[item]) > 0:
print(" \t{0}_s: {1}".format(item, formalize_value(np.mean(info_dict_step[item]), inspect_loss_precision)), end = "")
if item in record_keys and item != "loss":
record_data(data_record, [np.mean(info_dict_step[item])], ["{}_s".format(item)])
# Record loss:
if "loss" in record_keys:
record_data(data_record, [i, loss_value], ["iter", "loss"])
if "reg" in record_keys and "reg_dict" in kwargs and len(kwargs["reg_dict"]) > 0:
record_data(data_record, [reg_value], ["reg"])
if "param" in record_keys:
record_data(data_record, [model.get_weights_bias(W_source = "core", b_source = "core")], ["param"])
if "param_grad" in record_keys:
record_data(data_record, [model.get_weights_bias(W_source = "core", b_source = "core", is_grad = True)], ["param_grad"])
print("\n")
try:
sys.stdout.flush()
except:
pass
if isplot:
if inspect_image_interval is not None and hasattr(model, "plot"):
if i % inspect_image_interval == 0:
if gradient_noise is not None:
print("gradient_noise: {0:.9f}".format(current_gradient_noise_scale))
plot_model(model, data_loader = validation_loader, X = X_valid, y = y_valid, transform_label=transform_label, data_loader_apply=data_loader_apply)
if co_kwargs is not None and "inspect_image_interval" in co_kwargs and co_kwargs["inspect_image_interval"] and hasattr(co_model, "plot"):
if i % co_kwargs["inspect_image_interval"] == 0:
plot_model(co_model, data_loader = validation_loader, X = X_valid, y = y_valid, transform_label=transform_label, data_loader_apply=data_loader_apply)
if save_interval is not None:
if i % save_interval == 0:
record_data(data_record, [model.model_dict], ["model_dict"])
if co_kwargs is not None:
record_data(data_record, [co_model.model_dict], ["co_model_dict"])
if filename is not None:
pickle.dump(data_record, open(filename, "wb"))
if to_stop:
break
loss_value = get_loss(model, validation_loader, X_valid, y_valid, criterion=criterion, loss_epoch=epochs, transform_label=transform_label, **kwargs)
if isplot:
import matplotlib.pylab as plt
for key, item in data_record.items():
if isinstance(item, Number) or len(data_record["iter"]) != len(item):
continue
if key not in ["iter", "model_dict"]:
if key in ["accuracy"]:
plt.figure(figsize = (8,6))
plt.plot(data_record["iter"], data_record[key])
plt.xlabel("epoch")
plt.ylabel(key)
plt.title(key)
plt.show()
else:
plt.figure(figsize = (8,6))
plt.semilogy(data_record["iter"], data_record[key])
plt.xlabel("epoch")
plt.ylabel(key)
plt.title(key)
plt.show()
return loss_original, loss_value, data_record
def train_simple(model, X, y, validation_data = None, inspect_interval = 5, **kwargs):
"""minimal version of training. "model" can be a single model or a ordered list of models"""
def get_regularization(model, **kwargs):
reg_dict = kwargs["reg_dict"] if "reg_dict" in kwargs else None
reg = to_Variable([0], is_cuda = X.is_cuda)
for model_ele in model:
if reg_dict is not None:
for reg_type, reg_coeff in reg_dict.items():
reg = reg + model_ele.get_regularization(source = [reg_type], mode = "L1", **kwargs) * reg_coeff
return reg
if not(isinstance(model, list) or isinstance(model, tuple)):
model = [model]
epochs = kwargs["epochs"] if "epochs" in kwargs else 2000
lr = kwargs["lr"] if "lr" in kwargs else 5e-3
optim_type = kwargs["optim_type"] if "optim_type" in kwargs else "adam"
optim_kwargs = kwargs["optim_kwargs"] if "optim_kwargs" in kwargs else {}
loss_type = kwargs["loss_type"] if "loss_type" in kwargs else "mse"
early_stopping_epsilon = kwargs["early_stopping_epsilon"] if "early_stopping_epsilon" in kwargs else 0
patience = kwargs["patience"] if "patience" in kwargs else 40
record_keys = kwargs["record_keys"] if "record_keys" in kwargs else ["loss", "mse", "data_DL", "model_DL"]
scheduler_type = kwargs["scheduler_type"] if "scheduler_type" in kwargs else "ReduceLROnPlateau"
loss_precision_floor = kwargs["loss_precision_floor"] if "loss_precision_floor" in kwargs else PrecisionFloorLoss
autoencoder = kwargs["autoencoder"] if "autoencoder" in kwargs else None
data_record = {key: [] for key in record_keys}
isplot = kwargs["isplot"] if "isplot" in kwargs else False
if patience is not None:
early_stopping = Early_Stopping(patience = patience, epsilon = early_stopping_epsilon)
if validation_data is not None:
X_valid, y_valid = validation_data
else:
X_valid, y_valid = X, y
# Get original loss:
criterion = get_criterion(loss_type, loss_precision_floor = loss_precision_floor)
DL_criterion = Loss_Fun(core = "DLs", loss_precision_floor = loss_precision_floor, DL_sum = True)
DL_criterion_absolute = Loss_Fun(core = "DLs", loss_precision_floor = PrecisionFloorLoss, DL_sum = True)
pred_valid = forward(model, X_valid, **kwargs)
loss_original = to_np_array(criterion(pred_valid, y_valid))
if "loss" in record_keys:
record_data(data_record, [-1, loss_original], ["iter","loss"])
if "mse" in record_keys:
record_data(data_record, [to_np_array(nn.MSELoss()(pred_valid, y_valid))], ["mse"])
if "data_DL" in record_keys:
record_data(data_record, [to_np_array(DL_criterion(pred_valid, y_valid))], ["data_DL"])
if "data_DL_absolute" in record_keys:
record_data(data_record, [to_np_array(DL_criterion_absolute(pred_valid, y_valid))], ["data_DL_absolute"])
if "model_DL" in record_keys:
record_data(data_record, [get_model_DL(model)], ["model_DL"])
if "param" in record_keys:
record_data(data_record, [model[0].get_weights_bias(W_source = "core", b_source = "core")], ["param"])
if "param_grad" in record_keys:
record_data(data_record, [model[0].get_weights_bias(W_source = "core", b_source = "core", is_grad = True)], ["param_grad"])
if "param_collapse_layers" in record_keys:
record_data(data_record, [simplify(deepcopy(model[0]), X, y, "collapse_layers", verbose = 0)[0] .get_weights_bias(W_source = "core", b_source = "core")], ["param"])
# Setting up optimizer:
parameters = itertools.chain(*[model_ele.parameters() for model_ele in model])
num_params = np.sum([[len(list(model_ele.parameters())) for model_ele in model]])
if num_params == 0:
print("No parameters to optimize!")
pred_valid = forward(model, X_valid, **kwargs)
loss_value = to_np_array(criterion(pred_valid, y_valid))
if "loss" in record_keys:
record_data(data_record, [0, loss_value], ["iter", "loss"])
if "mse" in record_keys:
record_data(data_record, [to_np_array(nn.MSELoss()(pred_valid, y_valid))], ["mse"])
if "data_DL" in record_keys:
record_data(data_record, [to_np_array(DL_criterion(pred_valid, y_valid))], ["data_DL"])
if "data_DL_absolute" in record_keys:
record_data(data_record, [to_np_array(DL_criterion_absolute(pred_valid, y_valid))], ["data_DL_absolute"])
if "model_DL" in record_keys:
record_data(data_record, [get_model_DL(model)], ["model_DL"])
if "param" in record_keys:
record_data(data_record, [model[0].get_weights_bias(W_source = "core", b_source = "core")], ["param"])
if "param_grad" in record_keys:
record_data(data_record, [model[0].get_weights_bias(W_source = "core", b_source = "core", is_grad = True)], ["param_grad"])
if "param_collapse_layers" in record_keys:
record_data(data_record, [simplify(deepcopy(model[0]), X, y, "collapse_layers", verbose = 0)[0] .get_weights_bias(W_source = "core", b_source = "core")], ["param"])
return loss_original, loss_value, data_record
optimizer = get_optimizer(optim_type, lr, parameters, **optim_kwargs)
# Set up learning rate scheduler:
if scheduler_type is not None:
if scheduler_type == "ReduceLROnPlateau":
scheduler_patience = kwargs["scheduler_patience"] if "scheduler_patience" in kwargs else 10
scheduler_factor = kwargs["scheduler_factor"] if "scheduler_factor" in kwargs else 0.1
scheduler = ReduceLROnPlateau(optimizer, factor = scheduler_factor, patience = scheduler_patience)
elif scheduler_type == "LambdaLR":
scheduler_lr_lambda = kwargs["scheduler_lr_lambda"] if "scheduler_lr_lambda" in kwargs else (lambda epoch: 1 / (1 + 0.01 * epoch))
scheduler = LambdaLR(optimizer, lr_lambda = scheduler_lr_lambda)
else:
raise
# Training:
to_stop = False
for i in range(epochs + 1):
if optim_type != "LBFGS":
optimizer.zero_grad()
pred = forward(model, X, **kwargs)
reg = get_regularization(model, **kwargs)
loss = criterion(pred, y) + reg
loss.backward()
optimizer.step()
else:
# "LBFGS" is a second-order optimization algorithm that requires a slightly different procedure:
def closure():
optimizer.zero_grad()
pred = forward(model, X, **kwargs)
reg = get_regularization(model, **kwargs)
loss = criterion(pred, y) + reg
loss.backward()
return loss
optimizer.step(closure)
if i % inspect_interval == 0:
pred_valid = forward(model, X_valid, **kwargs)
loss_value = to_np_array(criterion(pred_valid, y_valid))
if scheduler_type is not None:
if scheduler_type == "ReduceLROnPlateau":
scheduler.step(loss_value)
else:
scheduler.step()
if "loss" in record_keys:
record_data(data_record, [i, loss_value], ["iter", "loss"])
if "mse" in record_keys:
record_data(data_record, [to_np_array(nn.MSELoss()(pred_valid, y_valid))], ["mse"])
if "data_DL" in record_keys:
record_data(data_record, [to_np_array(DL_criterion(pred_valid, y_valid))], ["data_DL"])
if "data_DL_absolute" in record_keys:
record_data(data_record, [to_np_array(DL_criterion_absolute(pred_valid, y_valid))], ["data_DL_absolute"])
if "model_DL" in record_keys:
record_data(data_record, [get_model_DL(model)], ["model_DL"])
if "param" in record_keys:
record_data(data_record, [model[0].get_weights_bias(W_source = "core", b_source = "core")], ["param"])
if "param_grad" in record_keys:
record_data(data_record, [model[0].get_weights_bias(W_source = "core", b_source = "core", is_grad = True)], ["param_grad"])
if "param_collapse_layers" in record_keys:
record_data(data_record, [simplify(deepcopy(model[0]), X, y, "collapse_layers", verbose = 0)[0] .get_weights_bias(W_source = "core", b_source = "core")], ["param"])
if patience is not None:
to_stop = early_stopping.monitor(loss_value)
if to_stop:
break
pred_valid = forward(model, X_valid, **kwargs)
loss_value = to_np_array(criterion(pred_valid, y_valid))
if isplot:
import matplotlib.pylab as plt
if "mse" in data_record:
plt.semilogy(data_record["iter"], data_record["mse"])
plt.xlabel("epochs")
plt.title("MSE")
plt.show()
if "loss" in data_record:
plt.plot(data_record["iter"], data_record["loss"])
plt.xlabel("epochs")
plt.title("Loss")
plt.show()
return loss_original, loss_value, data_record
def load_model_dict_net(model_dict, is_cuda = False):
net_type = model_dict["type"]
if net_type.startswith("MLP"):
return MLP(input_size = model_dict["input_size"],
struct_param = model_dict["struct_param"] if "struct_param" in model_dict else None,
W_init_list = model_dict["weights"] if "weights" in model_dict else None,
b_init_list = model_dict["bias"] if "bias" in model_dict else None,
settings = model_dict["settings"] if "settings" in model_dict else {},
is_cuda = is_cuda,
)
elif net_type == "Labelmix_MLP":
model = Labelmix_MLP(input_size=model_dict["input_size"],
struct_param=model_dict["struct_param"],
idx_label=model_dict["idx_label"] if "idx_label" in model_dict else None,
is_cuda=is_cuda,
)
if "state_dict" in model_dict:
model.load_state_dict(model_dict["state_dict"])
return model
elif net_type == "Multi_MLP":
return Multi_MLP(input_size = model_dict["input_size"],
struct_param = model_dict["struct_param"],
W_init_list = model_dict["weights"] if "weights" in model_dict else None,
b_init_list = model_dict["bias"] if "bias" in model_dict else None,
settings = model_dict["settings"] if "settings" in model_dict else {},
is_cuda = is_cuda,
)
elif net_type == "Branching_Net":
return Branching_Net(net_base_model_dict = model_dict["net_base_model_dict"],
net_1_model_dict = model_dict["net_1_model_dict"],
net_2_model_dict = model_dict["net_2_model_dict"],
is_cuda = is_cuda,
)
elif net_type == "Fan_in_MLP":
return Fan_in_MLP(model_dict_branch1=model_dict["model_dict_branch1"],
model_dict_branch2=model_dict["model_dict_branch2"],
model_dict_joint=model_dict["model_dict_joint"],
is_cuda=is_cuda,
)
elif net_type == "Net_reparam":
return Net_reparam(model_dict=model_dict["model"],
reparam_mode=model_dict["reparam_mode"],
is_cuda=is_cuda,
)
elif net_type == "Wide_ResNet":
model = Wide_ResNet(depth=model_dict["depth"],
widen_factor=model_dict["widen_factor"],
input_channels=model_dict["input_channels"],
output_size=model_dict["output_size"],
dropout_rate=model_dict["dropout_rate"],
is_cuda=is_cuda,
)
if "state_dict" in model_dict:
model.load_state_dict(model_dict["state_dict"])
return model
elif net_type.startswith("ConvNet"):
return ConvNet(input_channels = model_dict["input_channels"],
struct_param = model_dict["struct_param"],
W_init_list = model_dict["weights"] if "weights" in model_dict else None,
b_init_list = model_dict["bias"] if "bias" in model_dict else None,
settings = model_dict["settings"] if "settings" in model_dict else {},
return_indices = model_dict["return_indices"] if "return_indices" in model_dict else False,
is_cuda = is_cuda,
)
elif net_type == "Conv_Autoencoder":
model = Conv_Autoencoder(input_channels_encoder = model_dict["input_channels_encoder"],
input_channels_decoder = model_dict["input_channels_decoder"],
struct_param_encoder = model_dict["struct_param_encoder"],
struct_param_decoder = model_dict["struct_param_decoder"],
settings = model_dict["settings"],
is_cuda = is_cuda,
)
if "encoder" in model_dict:
model.encoder.load_model_dict(model_dict["encoder"])
if "decoder" in model_dict:
model.decoder.load_model_dict(model_dict["decoder"])
return model
elif model_dict["type"] == "Conv_Model":
is_generative = model_dict["is_generative"] if "is_generative" in model_dict else False
return Conv_Model(encoder_model_dict = model_dict["encoder_model_dict"] if not is_generative else None,
core_model_dict = model_dict["core_model_dict"],
decoder_model_dict = model_dict["decoder_model_dict"],
latent_size = model_dict["latent_size"],
is_generative = model_dict["is_generative"] if is_generative else False,
is_res_block = model_dict["is_res_block"] if "is_res_block" in model_dict else False,
is_cuda = is_cuda,
)
else:
raise Exception("net_type {} not recognized!".format(net_type))
def load_model_dict(model_dict, is_cuda = False):
net_type = model_dict["type"]
if net_type not in ["Model_Ensemble", "LSTM", "Model_with_Uncertainty", "Mixture_Model", "Mixture_Gaussian"]:
return load_model_dict_net(model_dict, is_cuda = is_cuda)
elif net_type == "Model_Ensemble":
if model_dict["model_type"] == "MLP":
model_ensemble = Model_Ensemble(
num_models = model_dict["num_models"],
input_size = model_dict["input_size"],
model_type = model_dict["model_type"],
output_size = model_dict["output_size"],
is_cuda = is_cuda,
# Here we just create some placeholder network. The model will be overwritten in the next steps:
struct_param = [[1, "Simple_Layer", {}]],
)
elif model_dict["model_type"] == "LSTM":
model_ensemble = Model_Ensemble(
num_models = model_dict["num_models"],
input_size = model_dict["input_size"],
model_type = model_dict["model_type"],
output_size = model_dict["output_size"],
is_cuda = is_cuda,
# Here we just create some placeholder network. The model will be overwritten in the next steps:
hidden_size = 3,
output_struct_param = [[1, "Simple_Layer", {}]],
)
else:
raise
for k in range(model_ensemble.num_models):
setattr(model_ensemble, "model_{}".format(k), load_model_dict(model_dict["model_{}".format(k)], is_cuda = is_cuda))
return model_ensemble
elif net_type == "Model_with_Uncertainty":
return Model_with_Uncertainty(model_pred = load_model_dict(model_dict["model_pred"], is_cuda = is_cuda),
model_logstd = load_model_dict(model_dict["model_logstd"], is_cuda = is_cuda))
elif net_type == "Mixture_Model":
return Mixture_Model(model_dict_list=model_dict["model_dict_list"],
weight_logits_model_dict=model_dict["weight_logits_model_dict"],
num_components=model_dict["num_components"],
is_cuda=is_cuda,
)
elif net_type == "Mixture_Gaussian":
return load_model_dict_Mixture_Gaussian(model_dict, is_cuda = is_cuda)
else:
raise Exception("net_type {} not recognized!".format(net_type))
## Helper functions:
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 flatten(*tensors):
"""Flatten the tensor except the first dimension"""
new_tensors = []
for tensor in tensors:
new_tensors.append(tensor.view(tensor.size(0), -1))
if len(new_tensors) == 1:
new_tensors = new_tensors[0]
return new_tensors
def fill_triangular(vec, dim, mode = "lower"):
"""Fill an lower or upper triangular matrices with given vectors"""
num_examples, size = vec.shape
assert size == dim * (dim + 1) // 2
matrix = torch.zeros(num_examples, dim, dim).to(vec.device)
idx = (torch.tril(torch.ones(dim, dim)) == 1).unsqueeze(0)
idx = idx.repeat(num_examples,1,1)
if mode == "lower":
matrix[idx] = vec.contiguous().view(-1)
elif mode == "upper":
matrix[idx] = vec.contiguous().view(-1)
else:
raise Exception("mode {} not recognized!".format(mode))
return matrix
def matrix_diag_transform(matrix, fun):
"""Return the matrices whose diagonal elements have been executed by the function 'fun'."""
num_examples = len(matrix)
idx = torch.eye(matrix.size(-1)).bool().unsqueeze(0)
idx = idx.repeat(num_examples, 1, 1)
new_matrix = matrix.clone()
new_matrix[idx] = fun(matrix.diagonal(dim1 = 1, dim2 = 2).contiguous().view(-1))
return new_matrix
def Zip(*data, **kwargs):
"""Recursive unzipping of data structure
Example: Zip(*[(('a',2), 1), (('b',3), 2), (('c',3), 3), (('d',2), 4)])
==> [[['a', 'b', 'c', 'd'], [2, 3, 3, 2]], [1, 2, 3, 4]]
Each subtree in the original data must be in the form of a tuple.
In the **kwargs, you can set the function that is applied to each fully unzipped subtree.
"""
import collections
function = kwargs["function"] if "function" in kwargs else None
if len(data) == 1:
return data[0]
data = [list(element) for element in zip(*data)]
for i, element in enumerate(data):
if isinstance(element[0], tuple):
data[i] = Zip(*element, **kwargs)
elif isinstance(element, list):
if function is not None:
data[i] = function(element)
return data
def get_loss(model, data_loader=None, X=None, y=None, criterion=None, transform_label=None, **kwargs):
"""Get loss using the whole data or data_loader. Return the average validation loss with np.ndarray format"""
max_validation_iter = kwargs["max_validation_iter"] if "max_validation_iter" in kwargs else None
if transform_label is None:
transform_label = Transform_Label()
if "loader_process" in kwargs and kwargs["loader_process"] is not None:
data_loader = kwargs["loader_process"]("test")
if data_loader is not None:
assert X is None and y is None
loss_record = 0
count = 0
# Taking the average of all metrics:
for j, data_batch in enumerate(data_loader):
if isinstance(data_batch, tuple) or isinstance(data_batch, list):
X_batch, y_batch = data_batch
if "data_loader_apply" in kwargs and kwargs["data_loader_apply"] is not None:
X_batch, y_batch = kwargs["data_loader_apply"](X_batch, y_batch)
else:
X_batch, y_batch = kwargs["data_loader_apply"](data_batch)
loss_ele = to_np_array(model.get_loss(X_batch, transform_label(y_batch), criterion = criterion, **kwargs))
if j == 0:
all_info_dict = {key: 0 for key in model.info_dict.keys()}
loss_record = loss_record + loss_ele
count += 1
for key in model.info_dict:
all_info_dict[key] = all_info_dict[key] + model.info_dict[key]
if max_validation_iter is not None and count > max_validation_iter:
break
for key in model.info_dict:
all_info_dict[key] = all_info_dict[key] / count
loss = loss_record / count
model.info_dict = deepcopy(all_info_dict)
else:
assert X is not None and y is not None
loss = to_np_array(model.get_loss(X, transform_label(y), criterion = criterion, **kwargs))
return loss
def plot_model(model, data_loader=None, X=None, y=None, transform_label=None, **kwargs):
data_loader_apply = kwargs["data_loader_apply"] if "data_loader_apply" in kwargs else None
max_validation_iter = kwargs["max_validation_iter"] if "max_validation_iter" in kwargs else None
if transform_label is None:
transform_label = Transform_Label()
if "loader_process" in kwargs and kwargs["loader_process"] is not None:
data_loader = kwargs["loader_process"]("test")
if data_loader is not None:
assert X is None and y is None
X_all = []
y_all = []
for i, data_batch in enumerate(data_loader):
if isinstance(data_batch, tuple) or isinstance(data_batch, list):
X_batch, y_batch = data_batch
if data_loader_apply is not None:
X_batch, y_batch = data_loader_apply(X_batch, y_batch)
else:
X_batch, y_batch = data_loader_apply(data_batch)
X_all.append(X_batch)
y_all.append(y_batch)
if max_validation_iter is not None and i >= max_validation_iter:
break
if not isinstance(X_all[0], torch.Tensor):
X_all = Zip(*X_all, function = torch.cat)
else:
X_all = torch.cat(X_all, 0)
y_all = torch.cat(y_all)
model.plot(X_all, transform_label(y_all))
else:
assert X is not None and y is not None
model.plot(X, transform_label(y))
def prepare_inspection(model, data_loader=None, X=None, y=None, transform_label=None, **kwargs):
inspect_functions = kwargs["inspect_functions"] if "inspect_functions" in kwargs else None
max_validation_iter = kwargs["max_validation_iter"] if "max_validation_iter" in kwargs else None
verbose = kwargs["verbose"] if "verbose" in kwargs else False
if transform_label is None:
transform_label = Transform_Label()
if "loader_process" in kwargs and kwargs["loader_process"] is not None:
data_loader = kwargs["loader_process"]("test")
if data_loader is None:
assert X is not None and y is not None
all_dict_summary = model.prepare_inspection(X, transform_label(y), **kwargs)
if inspect_functions is not None:
for inspect_function_key, inspect_function in inspect_functions.items():
all_dict_summary[inspect_function_key] = inspect_function(model, X, y, **kwargs)
else:
assert X is None and y is None
all_dict = {}
for j, data_batch in enumerate(data_loader):
if verbose is True:
print("valid step: {}".format(j))
if isinstance(data_batch, tuple) or isinstance(data_batch, list):
X_batch, y_batch = data_batch
if "data_loader_apply" in kwargs and kwargs["data_loader_apply"] is not None:
X_batch, y_batch = kwargs["data_loader_apply"](X_batch, y_batch)
else: