You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_uniform_augment.py 9.7 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  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. # ==============================================================================
  15. """
  16. Testing UniformAugment in DE
  17. """
  18. import numpy as np
  19. import mindspore.dataset.engine as de
  20. import mindspore.dataset.transforms.vision.c_transforms as C
  21. import mindspore.dataset.transforms.vision.py_transforms as F
  22. from mindspore import log as logger
  23. from util import visualize_list, diff_mse
  24. DATA_DIR = "../data/dataset/testImageNetData/train/"
  25. def test_uniform_augment(plot=False, num_ops=2):
  26. """
  27. Test UniformAugment
  28. """
  29. logger.info("Test UniformAugment")
  30. # Original Images
  31. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  32. transforms_original = F.ComposeOp([F.Decode(),
  33. F.Resize((224, 224)),
  34. F.ToTensor()])
  35. ds_original = ds.map(input_columns="image",
  36. operations=transforms_original())
  37. ds_original = ds_original.batch(512)
  38. for idx, (image, _) in enumerate(ds_original):
  39. if idx == 0:
  40. images_original = np.transpose(image, (0, 2, 3, 1))
  41. else:
  42. images_original = np.append(images_original,
  43. np.transpose(image, (0, 2, 3, 1)),
  44. axis=0)
  45. # UniformAugment Images
  46. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  47. transform_list = [F.RandomRotation(45),
  48. F.RandomColor(),
  49. F.RandomSharpness(),
  50. F.Invert(),
  51. F.AutoContrast(),
  52. F.Equalize()]
  53. transforms_ua = F.ComposeOp([F.Decode(),
  54. F.Resize((224, 224)),
  55. F.UniformAugment(transforms=transform_list, num_ops=num_ops),
  56. F.ToTensor()])
  57. ds_ua = ds.map(input_columns="image",
  58. operations=transforms_ua())
  59. ds_ua = ds_ua.batch(512)
  60. for idx, (image, _) in enumerate(ds_ua):
  61. if idx == 0:
  62. images_ua = np.transpose(image, (0, 2, 3, 1))
  63. else:
  64. images_ua = np.append(images_ua,
  65. np.transpose(image, (0, 2, 3, 1)),
  66. axis=0)
  67. num_samples = images_original.shape[0]
  68. mse = np.zeros(num_samples)
  69. for i in range(num_samples):
  70. mse[i] = diff_mse(images_ua[i], images_original[i])
  71. logger.info("MSE= {}".format(str(np.mean(mse))))
  72. if plot:
  73. visualize_list(images_original, images_ua)
  74. def test_cpp_uniform_augment(plot=False, num_ops=2):
  75. """
  76. Test UniformAugment
  77. """
  78. logger.info("Test CPP UniformAugment")
  79. # Original Images
  80. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  81. transforms_original = [C.Decode(), C.Resize(size=[224, 224]),
  82. F.ToTensor()]
  83. ds_original = ds.map(input_columns="image",
  84. operations=transforms_original)
  85. ds_original = ds_original.batch(512)
  86. for idx, (image, _) in enumerate(ds_original):
  87. if idx == 0:
  88. images_original = np.transpose(image, (0, 2, 3, 1))
  89. else:
  90. images_original = np.append(images_original,
  91. np.transpose(image, (0, 2, 3, 1)),
  92. axis=0)
  93. # UniformAugment Images
  94. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  95. transforms_ua = [C.RandomCrop(size=[224, 224], padding=[32, 32, 32, 32]),
  96. C.RandomHorizontalFlip(),
  97. C.RandomVerticalFlip(),
  98. C.RandomColorAdjust(),
  99. C.RandomRotation(degrees=45)]
  100. uni_aug = C.UniformAugment(operations=transforms_ua, num_ops=num_ops)
  101. transforms_all = [C.Decode(), C.Resize(size=[224, 224]),
  102. uni_aug,
  103. F.ToTensor()]
  104. ds_ua = ds.map(input_columns="image",
  105. operations=transforms_all, num_parallel_workers=1)
  106. ds_ua = ds_ua.batch(512)
  107. for idx, (image, _) in enumerate(ds_ua):
  108. if idx == 0:
  109. images_ua = np.transpose(image, (0, 2, 3, 1))
  110. else:
  111. images_ua = np.append(images_ua,
  112. np.transpose(image, (0, 2, 3, 1)),
  113. axis=0)
  114. if plot:
  115. visualize_list(images_original, images_ua)
  116. num_samples = images_original.shape[0]
  117. mse = np.zeros(num_samples)
  118. for i in range(num_samples):
  119. mse[i] = diff_mse(images_ua[i], images_original[i])
  120. logger.info("MSE= {}".format(str(np.mean(mse))))
  121. def test_cpp_uniform_augment_exception_pyops(num_ops=2):
  122. """
  123. Test UniformAugment invalid op in operations
  124. """
  125. logger.info("Test CPP UniformAugment invalid OP exception")
  126. transforms_ua = [C.RandomCrop(size=[224, 224], padding=[32, 32, 32, 32]),
  127. C.RandomHorizontalFlip(),
  128. C.RandomVerticalFlip(),
  129. C.RandomColorAdjust(),
  130. C.RandomRotation(degrees=45),
  131. F.Invert()]
  132. try:
  133. _ = C.UniformAugment(operations=transforms_ua, num_ops=num_ops)
  134. except Exception as e:
  135. logger.info("Got an exception in DE: {}".format(str(e)))
  136. assert "Argument tensor_op_5 with value" \
  137. " <mindspore.dataset.transforms.vision.py_transforms.Invert" in str(e)
  138. assert "is not of type (<class 'mindspore._c_dataengine.TensorOp'>,)" in str(e)
  139. def test_cpp_uniform_augment_exception_large_numops(num_ops=6):
  140. """
  141. Test UniformAugment invalid large number of ops
  142. """
  143. logger.info("Test CPP UniformAugment invalid large num_ops exception")
  144. transforms_ua = [C.RandomCrop(size=[224, 224], padding=[32, 32, 32, 32]),
  145. C.RandomHorizontalFlip(),
  146. C.RandomVerticalFlip(),
  147. C.RandomColorAdjust(),
  148. C.RandomRotation(degrees=45)]
  149. try:
  150. _ = C.UniformAugment(operations=transforms_ua, num_ops=num_ops)
  151. except Exception as e:
  152. logger.info("Got an exception in DE: {}".format(str(e)))
  153. assert "num_ops" in str(e)
  154. def test_cpp_uniform_augment_exception_nonpositive_numops(num_ops=0):
  155. """
  156. Test UniformAugment invalid non-positive number of ops
  157. """
  158. logger.info("Test CPP UniformAugment invalid non-positive num_ops exception")
  159. transforms_ua = [C.RandomCrop(size=[224, 224], padding=[32, 32, 32, 32]),
  160. C.RandomHorizontalFlip(),
  161. C.RandomVerticalFlip(),
  162. C.RandomColorAdjust(),
  163. C.RandomRotation(degrees=45)]
  164. try:
  165. _ = C.UniformAugment(operations=transforms_ua, num_ops=num_ops)
  166. except Exception as e:
  167. logger.info("Got an exception in DE: {}".format(str(e)))
  168. assert "Input num_ops must be greater than 0" in str(e)
  169. def test_cpp_uniform_augment_exception_float_numops(num_ops=2.5):
  170. """
  171. Test UniformAugment invalid float number of ops
  172. """
  173. logger.info("Test CPP UniformAugment invalid float num_ops exception")
  174. transforms_ua = [C.RandomCrop(size=[224, 224], padding=[32, 32, 32, 32]),
  175. C.RandomHorizontalFlip(),
  176. C.RandomVerticalFlip(),
  177. C.RandomColorAdjust(),
  178. C.RandomRotation(degrees=45)]
  179. try:
  180. _ = C.UniformAugment(operations=transforms_ua, num_ops=num_ops)
  181. except Exception as e:
  182. logger.info("Got an exception in DE: {}".format(str(e)))
  183. assert "Argument num_ops with value 2.5 is not of type (<class 'int'>,)" in str(e)
  184. def test_cpp_uniform_augment_random_crop_badinput(num_ops=1):
  185. """
  186. Test UniformAugment with greater crop size
  187. """
  188. logger.info("Test CPP UniformAugment with random_crop bad input")
  189. batch_size = 2
  190. cifar10_dir = "../data/dataset/testCifar10Data"
  191. ds1 = de.Cifar10Dataset(cifar10_dir, shuffle=False) # shape = [32,32,3]
  192. transforms_ua = [
  193. # Note: crop size [224, 224] > image size [32, 32]
  194. C.RandomCrop(size=[224, 224]),
  195. C.RandomHorizontalFlip()
  196. ]
  197. uni_aug = C.UniformAugment(operations=transforms_ua, num_ops=num_ops)
  198. ds1 = ds1.map(input_columns="image", operations=uni_aug)
  199. # apply DatasetOps
  200. ds1 = ds1.batch(batch_size, drop_remainder=True, num_parallel_workers=1)
  201. num_batches = 0
  202. try:
  203. for _ in ds1.create_dict_iterator():
  204. num_batches += 1
  205. except Exception as e:
  206. assert "Crop size" in str(e)
  207. if __name__ == "__main__":
  208. test_uniform_augment(num_ops=1, plot=True)
  209. test_cpp_uniform_augment(num_ops=1, plot=True)
  210. test_cpp_uniform_augment_exception_pyops(num_ops=1)
  211. test_cpp_uniform_augment_exception_large_numops(num_ops=6)
  212. test_cpp_uniform_augment_exception_nonpositive_numops(num_ops=0)
  213. test_cpp_uniform_augment_exception_float_numops(num_ops=2.5)
  214. test_cpp_uniform_augment_random_crop_badinput(num_ops=1)