keras.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. from copy import copy
  2. from functools import partial
  3. from .auto import tqdm as tqdm_auto
  4. try:
  5. import keras
  6. except (ImportError, AttributeError) as e:
  7. try:
  8. from tensorflow import keras
  9. except ImportError:
  10. raise e
  11. __author__ = {"github.com/": ["casperdcl"]}
  12. __all__ = ['TqdmCallback']
  13. class TqdmCallback(keras.callbacks.Callback):
  14. """Keras callback for epoch and batch progress."""
  15. @staticmethod
  16. def bar2callback(bar, pop=None, delta=(lambda logs: 1)):
  17. def callback(_, logs=None):
  18. n = delta(logs)
  19. if logs:
  20. if pop:
  21. logs = copy(logs)
  22. [logs.pop(i, 0) for i in pop]
  23. bar.set_postfix(logs, refresh=False)
  24. bar.update(n)
  25. return callback
  26. def __init__(self, epochs=None, data_size=None, batch_size=None, verbose=1,
  27. tqdm_class=tqdm_auto, **tqdm_kwargs):
  28. """
  29. Parameters
  30. ----------
  31. epochs : int, optional
  32. data_size : int, optional
  33. Number of training pairs.
  34. batch_size : int, optional
  35. Number of training pairs per batch.
  36. verbose : int
  37. 0: epoch, 1: batch (transient), 2: batch. [default: 1].
  38. Will be set to `0` unless both `data_size` and `batch_size`
  39. are given.
  40. tqdm_class : optional
  41. `tqdm` class to use for bars [default: `tqdm.auto.tqdm`].
  42. tqdm_kwargs : optional
  43. Any other arguments used for all bars.
  44. """
  45. if tqdm_kwargs:
  46. tqdm_class = partial(tqdm_class, **tqdm_kwargs)
  47. self.tqdm_class = tqdm_class
  48. self.epoch_bar = tqdm_class(total=epochs, unit='epoch')
  49. self.on_epoch_end = self.bar2callback(self.epoch_bar)
  50. if data_size and batch_size:
  51. self.batches = batches = (data_size + batch_size - 1) // batch_size
  52. else:
  53. self.batches = batches = None
  54. self.verbose = verbose
  55. if verbose == 1:
  56. self.batch_bar = tqdm_class(total=batches, unit='batch', leave=False)
  57. self.on_batch_end = self.bar2callback(
  58. self.batch_bar, pop=['batch', 'size'],
  59. delta=lambda logs: logs.get('size', 1))
  60. def on_train_begin(self, *_, **__):
  61. params = self.params.get
  62. auto_total = params('epochs', params('nb_epoch', None))
  63. if auto_total is not None and auto_total != self.epoch_bar.total:
  64. self.epoch_bar.reset(total=auto_total)
  65. def on_epoch_begin(self, epoch, *_, **__):
  66. if self.epoch_bar.n < epoch:
  67. ebar = self.epoch_bar
  68. ebar.n = ebar.last_print_n = ebar.initial = epoch
  69. if self.verbose:
  70. params = self.params.get
  71. total = params('samples', params(
  72. 'nb_sample', params('steps', None))) or self.batches
  73. if self.verbose == 2:
  74. if hasattr(self, 'batch_bar'):
  75. self.batch_bar.close()
  76. self.batch_bar = self.tqdm_class(
  77. total=total, unit='batch', leave=True,
  78. unit_scale=1 / (params('batch_size', 1) or 1))
  79. self.on_batch_end = self.bar2callback(
  80. self.batch_bar, pop=['batch', 'size'],
  81. delta=lambda logs: logs.get('size', 1))
  82. elif self.verbose == 1:
  83. self.batch_bar.unit_scale = 1 / (params('batch_size', 1) or 1)
  84. self.batch_bar.reset(total=total)
  85. else:
  86. raise KeyError('Unknown verbosity')
  87. def on_train_end(self, *_, **__):
  88. if self.verbose:
  89. self.batch_bar.close()
  90. self.epoch_bar.close()
  91. def display(self):
  92. """Displays in the current cell in Notebooks."""
  93. container = getattr(self.epoch_bar, 'container', None)
  94. if container is None:
  95. return
  96. from .notebook import display
  97. display(container)
  98. batch_bar = getattr(self, 'batch_bar', None)
  99. if batch_bar is not None:
  100. display(batch_bar.container)
  101. @staticmethod
  102. def _implements_train_batch_hooks():
  103. return True
  104. @staticmethod
  105. def _implements_test_batch_hooks():
  106. return True
  107. @staticmethod
  108. def _implements_predict_batch_hooks():
  109. return True