/
core.py
2047 lines (1886 loc) · 78 KB
/
core.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 . import utils as U
from .graph.predictor import LinkPredictor, NodePredictor
from .graph.preprocessor import LinkPreprocessor, NodePreprocessor
from .imports import *
from .lroptimize.lrfinder import *
from .tabular.predictor import TabularPredictor
from .tabular.preprocessor import TabularPreprocessor
from .text.ner.predictor import NERPredictor
from .text.ner.preprocessor import NERPreprocessor
from .text.predictor import TextPredictor
from .text.preprocessor import (
BERTPreprocessor,
TextPreprocessor,
TransformersPreprocessor,
)
from .vision.predictor import ImagePredictor
from .vision.preprocessor import ImagePreprocessor
class Learner(ABC):
"""
```
Abstract class used to tune and train Keras models. The fit method is
an abstract method and must be implemented by subclasses.
```
"""
def __init__(self, model, workers=1, use_multiprocessing=False):
if not isinstance(model, keras.Model):
raise ValueError("model must be of instance keras.Model")
self.model = model
self.lr_finder = LRFinder(self.model)
self.workers = workers
self.use_multiprocessing = use_multiprocessing
self.history = None
# save original weights of model
try:
new_file, weightfile = tempfile.mkstemp()
self.model.save_weights(weightfile)
self._original_weights = weightfile
except Exception as e:
warnings.warn("Could not save original model weights: %s" % (e))
self._original_weights = None
@property
def _monitor_metrics(self):
"""
```
monitor metrics
```
"""
metrics = ["loss"]
try:
m = U.metrics_from_model(self.model)
if isinstance(m, list):
metrics.extend(m)
except:
pass
if self.val_data is not None:
for m in metrics[:]:
metrics.append("val_%s" % (m))
return metrics
def get_weight_decay(self):
"""
```
Get current weight decay rate
```
"""
if type(self.model.optimizer).__name__ == "AdamWeightDecay":
return self.model.optimizer.weight_decay_rate
else:
return None
def set_weight_decay(self, wd=U.DEFAULT_WD):
"""
```
Sets global weight decay via AdamWeightDecay optimizer
Args:
wd(float): weight decay
Returns:
None
```
"""
self._recompile(wd=wd)
return
def evaluate(
self,
test_data=None,
print_report=True,
save_path="ktrain_classification_report.csv",
class_names=[],
):
"""
```
alias for self.validate().
Returns confusion matrix and optionally prints
a classification report.
This is currently only supported for binary and multiclass
classification, not multilabel classification.
By default, this uses val_data, as supplied to ktrain.get_learner().
Other validation or test data can be optionally be supplied as argument via <test_data> argument.
Supply class_names to include labels instead of intenger class integer values in classification report.
Args:
test_data(Dataset|np.ndarray): test or validation data. If None, self.val_data is used.
print_report(bool): If True, classification report will be printed. If False, report will be saved to CSV
at save_path. Not applicable to regression models.
Not applicable to regression models.
save_path(str): Classification report will be saved to this file path/name if print_report=False
Not applicable to regression models.
class_names(list): list of class names to be used in classification report instead of
class integer IDs.
```
"""
return self.validate(
val_data=test_data,
print_report=print_report,
save_path=save_path,
class_names=class_names,
)
def validate(
self,
val_data=None,
print_report=True,
save_path="ktrain_classification_report.csv",
class_names=[],
):
"""
```
Returns confusion matrix and optionally prints
a classification report.
This is currently only supported for binary and multiclass
classification, not multilabel classification.
By default, this uses val_data, as supplied to ktrain.get_learner().
Other validation or test data can be optionally be supplied as argument.
Supply class_names to include labels instead of intenger class integer values in classification report.
Args:
val_data(Dataset|np.ndarray): validation data. If None, self.val_data is used.
print_report(bool): If True, classification report will be printed. If False, report will be saved to CSV
at save path. Not applicable to regression models.
save_path(str): Classification report will be saved to this file path/name if print_report=False
class_names(list): list of class names to be used in classification report instead of
class integer IDs.
```
"""
if val_data is not None:
val = val_data
else:
val = self.val_data
classification, multilabel = U.is_classifier(self.model)
if not classification:
# warnings.warn('learner.validate is only for classification problems. '
#'For regression, etc., use learner.predict and learner.ground_truth '
#'to manually validate.')
# return
pass
if U.is_multilabel(val) or multilabel:
warnings.warn("multilabel confusion matrices not yet supported")
return
y_pred = self.predict(val_data=val)
y_true = self.ground_truth(val_data=val)
y_pred = np.squeeze(y_pred)
y_true = np.squeeze(y_true)
# regression evaluation
if not classification:
from sklearn.metrics import mean_absolute_error, mean_squared_error
regout = []
metrics = U.metrics_from_model(self.model)
for m in metrics:
if m in ["mae", "mean_absolute_error"]:
regout.append((m, mean_absolute_error(y_true, y_pred)))
elif m in ["mse", "mean_squared_error"]:
regout.append((m, mean_squared_error(y_true, y_pred)))
if not regout:
warnings.warn(
"%s is not supported by validate/evaluate - falling back to MAE"
)
regout.append(("mae", mean_absolute_error(y_true, y_pred)))
return regout
if len(y_pred.shape) == 1:
y_pred = np.where(y_pred > 0.5, 1, 0)
y_true = np.where(y_true > 0.5, 1, 0)
else:
y_pred = np.argmax(y_pred, axis=1)
y_true = np.argmax(y_true, axis=1)
if print_report or save_path is not None:
if class_names:
try:
class_names = [str(s) for s in class_names]
except:
pass
report = classification_report(
y_true,
y_pred,
target_names=class_names,
output_dict=not print_report,
)
else:
report = classification_report(
y_true, y_pred, output_dict=not print_report
)
if print_report:
print(report)
else:
df = pd.DataFrame(report).transpose()
df.to_csv(save_path)
print("classification report saved to: %s" % (save_path))
cm_func = confusion_matrix
cm = confusion_matrix(y_true, y_pred)
return cm
def _check_val(self, val_data):
if val_data is not None:
val = val_data
else:
val = self.val_data
if val is None:
raise Exception(
"val_data must be supplied to get_learner or view_top_losses"
)
return val
def top_losses(self, n=4, val_data=None, preproc=None):
"""
```
Computes losses on validation set sorted by examples with top losses
Args:
n(int or tuple): a range to select in form of int or tuple
e.g., n=8 is treated as n=(0,8)
val_data: optional val_data to use instead of self.val_data
preproc (Preprocessor): A TextPreprocessor or ImagePreprocessor.
For some data like text data, a preprocessor
is required to undo the pre-processing
to correctly view raw data.
Returns:
list of n tuples where first element is either
filepath or id of validation example and second element
is loss.
```
"""
# check validation data and arguments
if val_data is not None:
val = val_data
else:
val = self.val_data
if val is None:
raise Exception("val_data must be supplied to get_learner or top_losses")
if type(n) == type(42):
n = (0, n)
# multilabel = True if U.is_multilabel(val) else False
classification, multilabel = U.is_classifier(self.model)
# get predicictions and ground truth
y_pred = self.predict(val_data=val)
y_true = self.ground_truth(val_data=val)
y_true = y_true.astype("float32")
# adjust y_true for regression problems
if (
not classification
and len(y_true.shape) == 1
and (len(y_pred.shape) == 2 and y_pred.shape[1] == 1)
):
y_true = np.expand_dims(y_true, -1)
# compute loss
# this doesn't work in tf.keras 1.14
# losses = self.model.loss_functions[0](tf.convert_to_tensor(y_true), tf.convert_to_tensor(y_pred))
# if U.is_tf_keras():
# L = self.model.loss_functions[0].fn
# else:
# L = self.model.loss_functions[0]
L = U.loss_fn_from_model(self.model)
losses = L(tf.convert_to_tensor(y_true), tf.convert_to_tensor(y_pred))
if DISABLE_V2_BEHAVIOR:
losses = tf.Session().run(losses)
else:
losses = losses.numpy()
class_names = [] if preproc is None else preproc.get_classes()
if preproc is None:
class_fcn = lambda x: "%s" % (x)
else:
class_fcn = lambda x: class_names[x]
# regression output modifications
if not classification:
if len(y_pred.shape) == 2 and y_pred.shape[1] == 1:
y_pred = np.squeeze(y_pred)
y_pred = np.around(y_pred, 2)
if len(y_true.shape) == 2 and y_true.shape[1] == 1:
y_true = np.squeeze(y_true)
y_true = np.around(y_true, 2)
# sort by loss and prune correct classifications, if necessary
if classification and not multilabel:
y_pred = np.squeeze(y_pred)
y_true = np.squeeze(y_true)
if len(y_pred.shape) == 1:
y_p = np.where(y_pred > 0.5, 1, 0)
y_t = np.where(y_true > 0.5, 1, 0)
else:
y_p = np.argmax(y_pred, axis=1)
y_t = np.argmax(y_true, axis=1)
tups = [
(i, x, class_fcn(y_t[i]), class_fcn(y_p[i]))
for i, x in enumerate(losses)
if y_p[i] != y_t[i]
]
else:
tups = [
(i, x, y_true[i], np.around(y_pred[i], 2)) for i, x in enumerate(losses)
]
tups.sort(key=operator.itemgetter(1), reverse=True)
# prune by given range
tups = tups[n[0] : n[1]] if n is not None else tups
return tups
def view_top_losses(self, n=4, preproc=None, val_data=None):
"""
```
View observations with top losses in validation set.
Musta be overridden by Learner subclasses.
```
"""
raise NotImplementedError(
"view_top_losses must be overriden by Learner subclass"
)
def _make_model_folder(self, fpath):
if os.path.isfile(fpath):
raise ValueError(
f"There is an existing file named {fpath}. "
+ "Please use dfferent value for fpath."
)
elif os.path.exists(fpath):
# warnings.warn('model is being saved to folder that already exists: %s' % (fpath))
pass
elif not os.path.exists(fpath):
os.makedirs(fpath)
def save_model(self, fpath):
"""
```
a wrapper to model.save
Args:
fpath(str): path to folder in which to save model
Returns:
None
```
"""
self._make_model_folder(fpath)
self.model.save(os.path.join(fpath, U.MODEL_NAME), save_format="h5")
return
def load_model(self, fpath, custom_objects=None, **kwargs):
"""
```
loads model from folder.
Note: **kwargs included for backwards compatibility only, as TransformerTextClassLearner.load_model was removed in v0.18.0.
Args:
fpath(str): path to folder containing model
custom_objects(dict): custom objects required to load model.
For models included with ktrain, this is populated automatically
and can be disregarded.
```
"""
self.model = _load_model(
fpath, train_data=self.train_data, custom_objects=custom_objects
)
return
def _is_adamlike(self):
"""
```
checks whether optimizer attached to model is an
"Adam-like" optimizer with beta_1 parameter.
```
"""
return self.model is not None and hasattr(self.model.optimizer, "beta_1")
def _recompile(self, wd=None):
metrics = U.metrics_from_model(self.model)
if (
wd is not None
and wd > 0
and type(self.model.optimizer).__name__ != "AdamWeightDecay"
):
warnings.warn(
"recompiling model to use AdamWeightDecay as opimizer with weight decay of %s"
% (wd)
)
optimizer = U.get_default_optimizer(wd=wd)
elif wd is not None and wd > 0:
optimizer = U.get_default_optimizer(wd=wd)
elif wd is not None and wd == 0:
optimizer = U.DEFAULT_OPT
else: # wd is None -> don't modify optimizer
optimizer = self.model.optimizer
self.model.compile(optimizer=optimizer, loss=self.model.loss, metrics=metrics)
return
def set_model(self, model):
"""
```
replace model in this Learner instance
```
"""
if not isinstance(model, keras.Model):
raise ValueError("model must be of instance keras.Model")
self.model = model
self.history = None
return
def freeze(self, freeze_range=None):
"""
```
If freeze_range is None, makes all layers trainable=False except last Dense layer.
If freeze_range is given, freezes the first <freeze_range> layers and
unfrezes all remaining layers.
NOTE: Freeze method does not currently work with
multi-GPU models. If you are using the load_imagemodel method,
please use the freeze_layers argument of load_imagemodel
to freeze layers.
Args:
freeze_range(int): number of layers to freeze
Returns:
None
```
"""
if freeze_range is None:
# freeze everything except last Dense layer
# first find last dense layer
dense_id = None
for i, layer in reversed(list(enumerate(self.model.layers))):
if isinstance(layer, keras.layers.Dense):
dense_id = i
break
if dense_id is None:
raise Exception("cannot find Dense layer in this model")
for i, layer in enumerate(self.model.layers):
if i < dense_id:
layer.trainable = False
else:
layer.trainable = True
else:
# freeze all layers up to and including layer_id
if type(freeze_range) != type(1) or freeze_range < 1:
raise ValueError("freeze_range must be integer > 0")
for i, layer in enumerate(self.model.layers):
if i < freeze_range:
layer.trainable = False
else:
layer.trainable = True
self._recompile()
return
def unfreeze(self, exclude_range=None):
"""
```
Make every layer trainable except those in exclude_range.
unfreeze is simply a proxy method to freeze.
NOTE: Unfreeze method does not currently work with
multi-GPU models. If you are using the load_imagemodel method,
please use the freeze_layers argument of load_imagemodel
to freeze layers.
```
"""
# make all layers trainable
for i, layer in enumerate(self.model.layers):
layer.trainable = True
if exclude_range:
for i, layer in enumerate(self.model.layers[:exclude_range]):
layer.trainable = False
self._recompile()
return
def reset_weights(self, verbose=1):
"""
```
Re-initializes network with original weights
```
"""
if os.path.isfile(self._original_weights):
self.model.load_weights(self._original_weights)
self.history = None
U.vprint("Model weights have been reset.", verbose=verbose)
else:
warnings.warn(
"Weights have not been reset because the original weights file "
+ "(%s) no longer exists." % (self._original_weights)
)
return
def lr_find(
self,
start_lr=1e-7,
lr_mult=1.01,
max_epochs=None,
class_weight=None,
stop_factor=4,
show_plot=False,
suggest=False,
restore_weights_only=False,
verbose=1,
):
"""
```
Plots loss as learning rate is increased. Highest learning rate
corresponding to a still falling loss should be chosen.
If you find the LR finder is running for more epochs than you'd prefer,
you can set max_epochs (e.g., max_epochs=5) to estimate LR with a
smaller sample size.
If lr_mult is supplied and max_epochs is None, LR will increase until loss diverges.
Reasonable values of lr_mult are between 1.01 and 1.05.
If max_epochs is supplied, lr_mult argument is ignored and computed automatically.
Reference: https://arxiv.org/abs/1506.01186
Args:
start_lr (float): smallest lr to start simulation
lr_mult (float): multiplication factor to increase LR.
Ignored if max_epochs is supplied.
max_epochs (int): maximum number of epochs to simulate.
lr_mult is ignored if max_epoch is supplied.
Default is None. Set max_epochs to an integer
(e.g., 5) if lr_find is taking too long
and running for more epochs than desired.
class_weight(dict): class_weight parameter passed to model.fit
for imbalanced datasets.
stop_factor(int): factor used to determine threhsold that loss
must exceed to stop training simulation.
Increase this if loss is erratic and lr_find
exits too early.
show_plot (bool): If True, automatically invoke lr_plot
restore_weights_only(bool): If True, when training simulation is complete,
the model weights only are restored, but not
the original optimizer weights.
In at least a few cases, this seems to improve performance
when actual training begins. Further investigation is needed,
so it is False by default.
verbose (bool): specifies how much output to print
Returns:
None
```
"""
# dep_fix: bug in TF 2.2 and 2.3
if version.parse(tf.__version__) > version.parse("2.1") and version.parse(
tf.__version__
) < version.parse("2.4"):
if max_epochs is None:
raise ValueError(
"Due to a bug in TensorFlow 2.2 and 2.3, the max_epochs argument is temporarily required. "
+ "Please re-run with max_epochs (e.g., max_epochs=5). \n"
+ "More info: https://github.com/tensorflow/tensorflow/issues/41174#issuecomment-656330268"
)
U.vprint(
"simulating training for different learning rates... this may take a few moments...",
verbose=verbose,
)
# save current weights and temporarily restore original weights
# dep_fix: temporarily use save_model instead of save_weights as default due to https://github.com/tensorflow/tensorflow/issues/41116
_weights_only = True
if restore_weights_only:
new_file, weightfile = tempfile.mkstemp()
self.model.save_weights(weightfile)
else:
temp_folder = tempfile.mkdtemp()
self.save_model(temp_folder)
# compute steps_per_epoch
num_samples = U.nsamples_from_data(self.train_data)
bs = (
self.train_data.batch_size
if hasattr(self.train_data, "batch_size")
else self.batch_size
)
if U.is_iter(self.train_data):
use_gen = True
steps_per_epoch = num_samples // bs
else:
use_gen = False
steps_per_epoch = np.ceil(num_samples / bs)
# check steps_per_epoch
if steps_per_epoch <= 64 and max_epochs is None:
warnings.warn(
"max_epochs is being set to 5 since steps per epoch is small. "
+ "If you wish to estimate LR using more epochs, set max_epochs manually."
)
max_epochs = 5
try:
# track and plot learning rates
self.lr_finder = LRFinder(self.model, stop_factor=stop_factor)
self.lr_finder.find(
self._prepare(self.train_data),
steps_per_epoch,
use_gen=use_gen,
start_lr=start_lr,
lr_mult=lr_mult,
max_epochs=max_epochs,
class_weight=class_weight,
workers=self.workers,
use_multiprocessing=self.use_multiprocessing,
batch_size=self.batch_size,
verbose=verbose,
)
except KeyboardInterrupt:
# re-load current weights
# self.model.load_weights(weightfile)
self.load_model(temp_folder)
return
# re-load current weights
# dep_fix: temporarily use load_model instead of load_weights as default due to https://github.com/tensorflow/tensorflow/issues/41116
if restore_weights_only:
self.model.load_weights(weightfile)
else:
self.load_model(temp_folder)
# instructions to invoker
U.vprint("\n", verbose=verbose)
U.vprint("done.", verbose=verbose)
if show_plot:
U.vprint(
"Visually inspect loss plot and select learning rate associated with falling loss",
verbose=verbose,
)
self.lr_plot(suggest=suggest)
else:
U.vprint(
"Please invoke the Learner.lr_plot() method to visually inspect "
"the loss plot to help identify the maximal learning rate "
"associated with falling loss.",
verbose=verbose,
)
return
def lr_estimate(self):
"""
```
Return numerical estimates of lr using two different methods:
1. learning rate associated with minimum numerical gradient
2. learning rate associated with minimum loss divided by 10
Since neither of these methods are fool-proof and can
potentially return bad estimates, it is recommended that you
examine the plot generated by lr_plot to estimate the learning rate.
Returns:
tuple: tuple of the form (float, float), where
First element is lr associated with minimum numerical gradient (None if gradient computation fails).
Second element is lr associated with minimum loss divided by 10.
```
"""
if self.lr_finder is None or not self.lr_finder.find_called():
raise ValueError("Please call lr_find first.")
return self.lr_finder.estimate_lr()
def lr_plot(
self, n_skip_beginning=10, n_skip_end=5, suggest=False, return_fig=False
):
"""
```
Plots the loss vs. learning rate to help identify
The maximal learning rate associated with a falling loss.
The nskip_beginning and n_skip_end arguments can be used
to "zoom in" on the plot.
Args:
n_skip_beginning(int): number of batches to skip on the left.
n_skip_end(int): number of batches to skip on the right.
suggest(bool): will highlight numerical estimate
of best lr if True - methods adapted from fastai
return_fig(bool): If True, return matplotlib.figure.Figure
Returns:
matplotlib.figure.Figure if return_fig else None
```
"""
# dep_fix: bug in TF 2.2 and 2.3
if version.parse(tf.__version__) > version.parse("2.1") and version.parse(
tf.__version__
) < version.parse("2.4"):
if n_skip_end == 5:
n_skip_end = 10
if self.lr_finder is None or not self.lr_finder.find_called():
raise ValueError("Please call lr_find first.")
return self.lr_finder.plot_loss(
n_skip_beginning=n_skip_beginning,
n_skip_end=n_skip_end,
suggest=suggest,
return_fig=return_fig,
)
def plot(self, plot_type="loss", return_fig=False):
"""
```
plots training history
Args:
plot_type (str): A valid value in tf.keras History. Either a built-in value {'loss', 'lr', 'momentum'} or
other values previously specified by user. For instance, if 'mae' and/or 'mse' is previously specified as metrics
when creating model, then these values can also be specified.
return_fig(bool): If True, return matplotlib.figure.Figure
Return:
matplotlib.figure.Figure if return_fig else None
```
"""
if self.history is None:
raise Exception("No training history - did you train the model yet?")
if not isinstance(plot_type, str):
raise ValueError("plot_type must be str/string")
fig = None
if plot_type == "loss":
plt.plot(self.history.history["loss"])
if "val_loss" in self.history.history:
plt.plot(self.history.history["val_loss"])
legend_items = ["train", "validation"]
else:
legend_items = ["train"]
plt.title("Model Loss")
plt.ylabel("loss")
plt.xlabel("epoch")
plt.legend(legend_items, loc="upper left")
elif plot_type == "lr":
if "lr" not in self.history.history:
raise ValueError(
"no lr in history: are you sure you used autofit or fit_onecycle to train?"
)
plt.plot(self.history.history["lr"])
plt.title("LR Schedule")
plt.ylabel("lr")
plt.xlabel("iterations")
elif plot_type == "momentum":
if "momentum" not in self.history.history:
raise ValueError(
"no momentum history: are you sure you used autofit or fit_onecycle to train?"
)
plt.plot(self.history.history["momentum"])
plt.title("Momentum Schedule")
plt.ylabel("momentum")
plt.xlabel("iterations")
else:
if plot_type not in self.history.history:
raise ValueError(
f"no {plot_type} in history: are you sure {plot_type} exists in history?"
)
plt.plot(self.history.history[plot_type])
val_key = f"val_{plot_type}"
if val_key in self.history.history:
plt.plot(self.history.history[val_key])
legend_items = ["train", "validation"]
else:
warnings.warn(
f"Validation value for {plot_type} wasn't found in history"
)
legend_items = ["train"]
plt.title(f"History of {plot_type}")
plt.ylabel(plot_type)
plt.xlabel("epoch")
plt.legend(legend_items, loc="upper left")
fig = plt.gcf()
plt.show()
if return_fig:
return fig
return
def print_layers(self, show_wd=False):
"""
```
prints the layers of the model along with indices
```
"""
if show_wd:
warnings.warn(
"set_weight_decay now uses AdamWeightDecay instead of kernel_regularizers."
)
for i, layer in enumerate(self.model.layers):
if show_wd and hasattr(layer, "kernel_regularizer"):
reg = layer.kernel_regularizer
if hasattr(reg, "l2"):
wd = reg.l2
elif hasattr(reg, "l1"):
wd = reg.l1
else:
wd = None
print("%s (trainable=%s, wd=%s) : %s" % (i, layer.trainable, wd, layer))
else:
print("%s (trainable=%s) : %s" % (i, layer.trainable, layer))
return
def layer_output(self, layer_id, example_id=0, use_val=False):
# should implemented in subclass
raise NotImplementedError
def set_lr(self, lr):
K.set_value(self.model.optimizer.lr, lr)
return
def _check_cycles(self, n_cycles, cycle_len, cycle_mult):
if type(n_cycles) != type(1) or n_cycles < 1:
raise ValueError("n_cycles must be >= 1")
if type(cycle_mult) != type(1) or cycle_mult < 1:
raise ValueError("cycle_mult must by >= 1")
if cycle_len is not None:
if type(cycle_len) != type(1) or cycle_len < 1:
raise ValueError("cycle_len must either be None or >= 1")
# calculate number of epochs
if cycle_len is None:
epochs = n_cycles
else:
epochs = 0
tmp_cycle_len = cycle_len
for i in range(n_cycles):
epochs += tmp_cycle_len
tmp_cycle_len *= cycle_mult
return epochs
def _cb_sgdr(
self, max_lr, steps_per_epoch, cycle_len, cycle_mult, lr_decay=1.0, callbacks=[]
):
if callbacks and "SGDRScheduler" in [type(cb).__name__ for cb in callbacks]:
return callbacks
# configuration
min_lr = 1e-9
if max_lr <= min_lr:
min_lr = max_lr / 10
# use learning_rate schedule
if cycle_len is not None:
if not isinstance(callbacks, list):
callbacks = []
from .lroptimize.sgdr import SGDRScheduler
schedule = SGDRScheduler(
min_lr=min_lr,
max_lr=max_lr,
steps_per_epoch=steps_per_epoch,
lr_decay=lr_decay,
cycle_length=cycle_len,
mult_factor=cycle_mult,
)
callbacks.append(schedule)
if not callbacks:
callbacks = None
return callbacks
def _cb_checkpoint(self, folder, callbacks=[]):
if callbacks and "ModelCheckpoint" in [type(cb).__name__ for cb in callbacks]:
return callbacks
if folder is not None:
os.makedirs(folder, exist_ok=True)
if not isinstance(callbacks, list):
callbacks = []
# filepath=os.path.join(folder, "weights-{epoch:02d}-{val_loss:.2f}.hdf5")
filepath = os.path.join(folder, "weights-{epoch:02d}.hdf5")
callbacks.append(
keras.callbacks.ModelCheckpoint(
filepath, save_best_only=False, save_weights_only=True
)
)
if not callbacks:
callbacks = None
return callbacks
def _cb_earlystopping(self, early_stopping, callbacks=[]):
if callbacks and "EarlyStopping" in [type(cb).__name__ for cb in callbacks]:
return callbacks
if early_stopping:
if not isinstance(callbacks, list):
callbacks = []
# if StrictVersion(keras.__version__) >= StrictVersion('2.2.3'):
try:
callbacks.append(
keras.callbacks.EarlyStopping(
monitor="val_loss",
min_delta=0,
patience=early_stopping,
restore_best_weights=True,
verbose=0,
mode="auto",
)
)
except TypeError:
warnings.warn(
"""
The early_stopping=True argument relies on EarlyStopping.restore_best_weights,
which is only supported on Keras 2.2.3 or greater.
For now, we are falling back to EarlyStopping.restore_best_weights=False.
Please use checkpoint_folder option in fit() to restore best weights."""
)
callbacks.append(
keras.callbacks.EarlyStopping(
monitor="val_loss",
min_delta=0,
patience=early_stopping,
verbose=0,
mode="auto",
)
)
if not callbacks:
callbacks = None
return callbacks
def _prepare(self, data, train=True):
"""
```
Subclasses can override this method if data
needs to be specially-prepared prior to invoking fit methods
Args:
data: dataset
train(bool): If True, prepare for training. Otherwise, prepare for evaluation.
```
"""
if data is None:
return None
if hasattr(data, "to_tfdataset"):
return data.to_tfdataset(train=train)
else:
return data
@abstractmethod
def fit(self, lr, n_cycles, cycle_len=None, cycle_mult=1, batch_size=U.DEFAULT_BS):
pass
def fit_onecycle(
self,
lr,
epochs,
checkpoint_folder=None,
cycle_momentum=True,
max_momentum=0.95,
min_momentum=0.85,
class_weight=None,
callbacks=[],
steps_per_epoch=None,
verbose=1,
):
"""
```
Train model using a version of Leslie Smith's 1cycle policy.
This method can be used with any optimizer. Thus,
cyclical momentum is not currently implemented.
Args:
lr (float): (maximum) learning rate.
It is recommended that you estimate lr yourself by
running lr_finder (and lr_plot) and visually inspect plot
for dramatic loss drop.
epochs (int): Number of epochs. Number of epochs
checkpoint_folder (string): Folder path in which to save the model weights
for each epoch.
File name will be of the form:
weights-{epoch:02d}-{val_loss:.2f}.hdf5
cycle_momentum (bool): If True and optimizer is Adam, Nadam, or Adamax, momentum of
optimzer will be cycled between 0.95 and 0.85 as described in
https://arxiv.org/abs/1803.09820.
Only takes effect if Adam, Nadam, or Adamax optimizer is used.
max_momentum(float): Maximum momentum to use if cycle_momentum=True
min_momentum(float): minimum momentum to use if cycle_momentum=True
class_weight (dict): Optional dictionary mapping class indices (integers) to a weight (float)
callbacks (list): list of Callback instances to employ during training
steps_per_epoch(int): Steps per epoch. If None, then, math.ceil(num_samples/batch_size) is used.
Ignored unless training dataset is generator.
verbose (bool): verbose mode
```
"""
if not self._is_adamlike() and cycle_momentum:
warnings.warn(
"cyclical momentum has been disabled because "
+ 'optimizer is not "Adam-like" with beta_1 param'
)
cycle_momentum = False