batch_operators.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. from __future__ import unicode_literals
  18. import random
  19. import numpy as np
  20. from paddlex.ppcls.utils import logger
  21. from paddlex.ppcls.data.preprocess.ops.fmix import sample_mask
  22. class BatchOperator(object):
  23. """ BatchOperator """
  24. def __init__(self, *args, **kwargs):
  25. pass
  26. def _unpack(self, batch):
  27. """ _unpack """
  28. assert isinstance(batch, list), \
  29. 'batch should be a list filled with tuples (img, label)'
  30. bs = len(batch)
  31. assert bs > 0, 'size of the batch data should > 0'
  32. #imgs, labels = list(zip(*batch))
  33. imgs = []
  34. labels = []
  35. for item in batch:
  36. imgs.append(item[0])
  37. labels.append(item[1])
  38. return np.array(imgs), np.array(labels), bs
  39. def _one_hot(self, targets):
  40. return np.eye(self.class_num, dtype="float32")[targets]
  41. def _mix_target(self, targets0, targets1, lam):
  42. one_hots0 = self._one_hot(targets0)
  43. one_hots1 = self._one_hot(targets1)
  44. return one_hots0 * lam + one_hots1 * (1 - lam)
  45. def __call__(self, batch):
  46. return batch
  47. class MixupOperator(BatchOperator):
  48. """ Mixup operator
  49. reference: https://arxiv.org/abs/1710.09412
  50. """
  51. def __init__(self, class_num, alpha: float=1.):
  52. """Build Mixup operator
  53. Args:
  54. alpha (float, optional): The parameter alpha of mixup. Defaults to 1..
  55. Raises:
  56. Exception: The value of parameter is illegal.
  57. """
  58. if alpha <= 0:
  59. raise Exception(
  60. f"Parameter \"alpha\" of Mixup should be greater than 0. \"alpha\": {alpha}."
  61. )
  62. if not class_num:
  63. msg = "Please set \"Arch.class_num\" in config if use \"MixupOperator\"."
  64. logger.error(Exception(msg))
  65. raise Exception(msg)
  66. self._alpha = alpha
  67. self.class_num = class_num
  68. def __call__(self, batch):
  69. imgs, labels, bs = self._unpack(batch)
  70. idx = np.random.permutation(bs)
  71. lam = np.random.beta(self._alpha, self._alpha)
  72. imgs = lam * imgs + (1 - lam) * imgs[idx]
  73. targets = self._mix_target(labels, labels[idx], lam)
  74. return list(zip(imgs, targets))
  75. class CutmixOperator(BatchOperator):
  76. """ Cutmix operator
  77. reference: https://arxiv.org/abs/1905.04899
  78. """
  79. def __init__(self, class_num, alpha=0.2):
  80. """Build Cutmix operator
  81. Args:
  82. alpha (float, optional): The parameter alpha of cutmix. Defaults to 0.2.
  83. Raises:
  84. Exception: The value of parameter is illegal.
  85. """
  86. if alpha <= 0:
  87. raise Exception(
  88. f"Parameter \"alpha\" of Cutmix should be greater than 0. \"alpha\": {alpha}."
  89. )
  90. if not class_num:
  91. msg = "Please set \"Arch.class_num\" in config if use \"CutmixOperator\"."
  92. logger.error(Exception(msg))
  93. raise Exception(msg)
  94. self._alpha = alpha
  95. self.class_num = class_num
  96. def _rand_bbox(self, size, lam):
  97. """ _rand_bbox """
  98. w = size[2]
  99. h = size[3]
  100. cut_rat = np.sqrt(1. - lam)
  101. cut_w = int(w * cut_rat)
  102. cut_h = int(h * cut_rat)
  103. # uniform
  104. cx = np.random.randint(w)
  105. cy = np.random.randint(h)
  106. bbx1 = np.clip(cx - cut_w // 2, 0, w)
  107. bby1 = np.clip(cy - cut_h // 2, 0, h)
  108. bbx2 = np.clip(cx + cut_w // 2, 0, w)
  109. bby2 = np.clip(cy + cut_h // 2, 0, h)
  110. return bbx1, bby1, bbx2, bby2
  111. def __call__(self, batch):
  112. imgs, labels, bs = self._unpack(batch)
  113. idx = np.random.permutation(bs)
  114. lam = np.random.beta(self._alpha, self._alpha)
  115. bbx1, bby1, bbx2, bby2 = self._rand_bbox(imgs.shape, lam)
  116. imgs[:, :, bbx1:bbx2, bby1:bby2] = imgs[idx, :, bbx1:bbx2, bby1:bby2]
  117. lam = 1 - (float(bbx2 - bbx1) * (bby2 - bby1) /
  118. (imgs.shape[-2] * imgs.shape[-1]))
  119. targets = self._mix_target(labels, labels[idx], lam)
  120. return list(zip(imgs, targets))
  121. class FmixOperator(BatchOperator):
  122. """ Fmix operator
  123. reference: https://arxiv.org/abs/2002.12047
  124. """
  125. def __init__(self,
  126. class_num,
  127. alpha=1,
  128. decay_power=3,
  129. max_soft=0.,
  130. reformulate=False):
  131. if not class_num:
  132. msg = "Please set \"Arch.class_num\" in config if use \"FmixOperator\"."
  133. logger.error(Exception(msg))
  134. raise Exception(msg)
  135. self._alpha = alpha
  136. self._decay_power = decay_power
  137. self._max_soft = max_soft
  138. self._reformulate = reformulate
  139. self.class_num = class_num
  140. def __call__(self, batch):
  141. imgs, labels, bs = self._unpack(batch)
  142. idx = np.random.permutation(bs)
  143. size = (imgs.shape[2], imgs.shape[3])
  144. lam, mask = sample_mask(self._alpha, self._decay_power, \
  145. size, self._max_soft, self._reformulate)
  146. imgs = mask * imgs + (1 - mask) * imgs[idx]
  147. targets = self._mix_target(labels, labels[idx], lam)
  148. return list(zip(imgs, targets))
  149. class OpSampler(object):
  150. """ Sample a operator from """
  151. def __init__(self, class_num, **op_dict):
  152. """Build OpSampler
  153. Raises:
  154. Exception: The parameter \"prob\" of operator(s) are be set error.
  155. """
  156. if not class_num:
  157. msg = "Please set \"Arch.class_num\" in config if use \"OpSampler\"."
  158. logger.error(Exception(msg))
  159. raise Exception(msg)
  160. if len(op_dict) < 1:
  161. msg = f"ConfigWarning: No operator in \"OpSampler\". \"OpSampler\" has been skipped."
  162. logger.warning(msg)
  163. self.ops = {}
  164. total_prob = 0
  165. for op_name in op_dict:
  166. param = op_dict[op_name]
  167. if "prob" not in param:
  168. msg = f"ConfigWarning: Parameter \"prob\" should be set when use operator in \"OpSampler\". The operator \"{op_name}\"'s prob has been set \"0\"."
  169. logger.warning(msg)
  170. prob = param.pop("prob", 0)
  171. total_prob += prob
  172. param.update({"class_num": class_num})
  173. op = eval(op_name)(**param)
  174. self.ops.update({op: prob})
  175. if total_prob > 1:
  176. msg = f"ConfigError: The total prob of operators in \"OpSampler\" should be less 1."
  177. logger.error(Exception(msg))
  178. raise Exception(msg)
  179. # add "None Op" when total_prob < 1, "None Op" do nothing
  180. self.ops[None] = 1 - total_prob
  181. def __call__(self, batch):
  182. op = random.choices(
  183. list(self.ops.keys()), weights=list(self.ops.values()), k=1)[0]
  184. # return batch directly when None Op
  185. return op(batch) if op else batch