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 pytest
  20. import mindspore.dataset.engine as de
  21. import mindspore.dataset.transforms.vision.c_transforms as C
  22. import mindspore.dataset.transforms.vision.py_transforms as F
  23. from mindspore import log as logger
  24. from util import visualize_list, diff_mse
  25. DATA_DIR = "../data/dataset/testImageNetData/train/"
  26. def test_uniform_augment(plot=False, num_ops=2):
  27. """
  28. Test UniformAugment
  29. """
  30. logger.info("Test UniformAugment")
  31. # Original Images
  32. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  33. transforms_original = F.ComposeOp([F.Decode(),
  34. F.Resize((224, 224)),
  35. F.ToTensor()])
  36. ds_original = ds.map(input_columns="image",
  37. operations=transforms_original())
  38. ds_original = ds_original.batch(512)
  39. for idx, (image, _) in enumerate(ds_original):
  40. if idx == 0:
  41. images_original = np.transpose(image, (0, 2, 3, 1))
  42. else:
  43. images_original = np.append(images_original,
  44. np.transpose(image, (0, 2, 3, 1)),
  45. axis=0)
  46. # UniformAugment Images
  47. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  48. transform_list = [F.RandomRotation(45),
  49. F.RandomColor(),
  50. F.RandomSharpness(),
  51. F.Invert(),
  52. F.AutoContrast(),
  53. F.Equalize()]
  54. transforms_ua = F.ComposeOp([F.Decode(),
  55. F.Resize((224, 224)),
  56. F.UniformAugment(transforms=transform_list, num_ops=num_ops),
  57. F.ToTensor()])
  58. ds_ua = ds.map(input_columns="image",
  59. operations=transforms_ua())
  60. ds_ua = ds_ua.batch(512)
  61. for idx, (image, _) in enumerate(ds_ua):
  62. if idx == 0:
  63. images_ua = np.transpose(image, (0, 2, 3, 1))
  64. else:
  65. images_ua = np.append(images_ua,
  66. np.transpose(image, (0, 2, 3, 1)),
  67. axis=0)
  68. num_samples = images_original.shape[0]
  69. mse = np.zeros(num_samples)
  70. for i in range(num_samples):
  71. mse[i] = diff_mse(images_ua[i], images_original[i])
  72. logger.info("MSE= {}".format(str(np.mean(mse))))
  73. if plot:
  74. visualize_list(images_original, images_ua)
  75. def test_cpp_uniform_augment(plot=False, num_ops=2):
  76. """
  77. Test UniformAugment
  78. """
  79. logger.info("Test CPP UniformAugment")
  80. # Original Images
  81. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  82. transforms_original = [C.Decode(), C.Resize(size=[224, 224]),
  83. F.ToTensor()]
  84. ds_original = ds.map(input_columns="image",
  85. operations=transforms_original)
  86. ds_original = ds_original.batch(512)
  87. for idx, (image, _) in enumerate(ds_original):
  88. if idx == 0:
  89. images_original = np.transpose(image, (0, 2, 3, 1))
  90. else:
  91. images_original = np.append(images_original,
  92. np.transpose(image, (0, 2, 3, 1)),
  93. axis=0)
  94. # UniformAugment Images
  95. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  96. transforms_ua = [C.RandomCrop(size=[224, 224], padding=[32, 32, 32, 32]),
  97. C.RandomHorizontalFlip(),
  98. C.RandomVerticalFlip(),
  99. C.RandomColorAdjust(),
  100. C.RandomRotation(degrees=45)]
  101. uni_aug = C.UniformAugment(transforms=transforms_ua, num_ops=num_ops)
  102. transforms_all = [C.Decode(), C.Resize(size=[224, 224]),
  103. uni_aug,
  104. F.ToTensor()]
  105. ds_ua = ds.map(input_columns="image",
  106. operations=transforms_all, num_parallel_workers=1)
  107. ds_ua = ds_ua.batch(512)
  108. for idx, (image, _) in enumerate(ds_ua):
  109. if idx == 0:
  110. images_ua = np.transpose(image, (0, 2, 3, 1))
  111. else:
  112. images_ua = np.append(images_ua,
  113. np.transpose(image, (0, 2, 3, 1)),
  114. axis=0)
  115. if plot:
  116. visualize_list(images_original, images_ua)
  117. num_samples = images_original.shape[0]
  118. mse = np.zeros(num_samples)
  119. for i in range(num_samples):
  120. mse[i] = diff_mse(images_ua[i], images_original[i])
  121. logger.info("MSE= {}".format(str(np.mean(mse))))
  122. def test_cpp_uniform_augment_exception_pyops(num_ops=2):
  123. """
  124. Test UniformAugment invalid op in operations
  125. """
  126. logger.info("Test CPP UniformAugment invalid OP exception")
  127. transforms_ua = [C.RandomCrop(size=[224, 224], padding=[32, 32, 32, 32]),
  128. C.RandomHorizontalFlip(),
  129. C.RandomVerticalFlip(),
  130. C.RandomColorAdjust(),
  131. C.RandomRotation(degrees=45),
  132. F.Invert()]
  133. with pytest.raises(TypeError) as e:
  134. C.UniformAugment(transforms=transforms_ua, num_ops=num_ops)
  135. logger.info("Got an exception in DE: {}".format(str(e)))
  136. assert "Argument tensor_ops[5] with value" \
  137. " <mindspore.dataset.transforms.vision.py_transforms.Invert" in str(e.value)
  138. assert "is not of type (<class 'mindspore._c_dataengine.TensorOp'>,)" in str(e.value)
  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(transforms=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(transforms=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(transforms=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(transforms=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)