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 10 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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.py_transforms
  22. import mindspore.dataset.vision.c_transforms as C
  23. import mindspore.dataset.vision.py_transforms as F
  24. from mindspore import log as logger
  25. from util import visualize_list, diff_mse
  26. DATA_DIR = "../data/dataset/testImageNetData/train/"
  27. def test_uniform_augment(plot=False, num_ops=2):
  28. """
  29. Test UniformAugment
  30. """
  31. logger.info("Test UniformAugment")
  32. # Original Images
  33. ds = de.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  34. transforms_original = mindspore.dataset.transforms.py_transforms.Compose([F.Decode(),
  35. F.Resize((224, 224)),
  36. F.ToTensor()])
  37. ds_original = ds.map(operations=transforms_original, input_columns="image")
  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.asnumpy(), (0, 2, 3, 1))
  42. else:
  43. images_original = np.append(images_original,
  44. np.transpose(image.asnumpy(), (0, 2, 3, 1)),
  45. axis=0)
  46. # UniformAugment Images
  47. ds = de.ImageFolderDataset(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 = \
  55. mindspore.dataset.transforms.py_transforms.Compose([F.Decode(),
  56. F.Resize((224, 224)),
  57. F.UniformAugment(transforms=transform_list,
  58. num_ops=num_ops),
  59. F.ToTensor()])
  60. ds_ua = ds.map(operations=transforms_ua, input_columns="image")
  61. ds_ua = ds_ua.batch(512)
  62. for idx, (image, _) in enumerate(ds_ua):
  63. if idx == 0:
  64. images_ua = np.transpose(image.asnumpy(), (0, 2, 3, 1))
  65. else:
  66. images_ua = np.append(images_ua,
  67. np.transpose(image.asnumpy(), (0, 2, 3, 1)),
  68. axis=0)
  69. num_samples = images_original.shape[0]
  70. mse = np.zeros(num_samples)
  71. for i in range(num_samples):
  72. mse[i] = diff_mse(images_ua[i], images_original[i])
  73. logger.info("MSE= {}".format(str(np.mean(mse))))
  74. if plot:
  75. visualize_list(images_original, images_ua)
  76. def test_cpp_uniform_augment(plot=False, num_ops=2):
  77. """
  78. Test UniformAugment
  79. """
  80. logger.info("Test CPP UniformAugment")
  81. # Original Images
  82. ds = de.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  83. transforms_original = [C.Decode(), C.Resize(size=[224, 224]),
  84. F.ToTensor()]
  85. ds_original = ds.map(operations=transforms_original, input_columns="image")
  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.asnumpy(), (0, 2, 3, 1))
  90. else:
  91. images_original = np.append(images_original,
  92. np.transpose(image.asnumpy(), (0, 2, 3, 1)),
  93. axis=0)
  94. # UniformAugment Images
  95. ds = de.ImageFolderDataset(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(operations=transforms_all, input_columns="image", 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.asnumpy(), (0, 2, 3, 1))
  110. else:
  111. images_ua = np.append(images_ua,
  112. np.transpose(image.asnumpy(), (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. with pytest.raises(TypeError) as e:
  133. C.UniformAugment(transforms=transforms_ua, num_ops=num_ops)
  134. logger.info("Got an exception in DE: {}".format(str(e)))
  135. assert "Argument tensor_ops[5] with value" \
  136. " <mindspore.dataset.vision.py_transforms.Invert" in str(e.value)
  137. assert "is not of type (<class 'mindspore._c_dataengine.TensorOp'>,)" in str(e.value)
  138. def test_cpp_uniform_augment_exception_large_numops(num_ops=6):
  139. """
  140. Test UniformAugment invalid large number of ops
  141. """
  142. logger.info("Test CPP UniformAugment invalid large num_ops exception")
  143. transforms_ua = [C.RandomCrop(size=[224, 224], padding=[32, 32, 32, 32]),
  144. C.RandomHorizontalFlip(),
  145. C.RandomVerticalFlip(),
  146. C.RandomColorAdjust(),
  147. C.RandomRotation(degrees=45)]
  148. try:
  149. _ = C.UniformAugment(transforms=transforms_ua, num_ops=num_ops)
  150. except Exception as e:
  151. logger.info("Got an exception in DE: {}".format(str(e)))
  152. assert "num_ops" in str(e)
  153. def test_cpp_uniform_augment_exception_nonpositive_numops(num_ops=0):
  154. """
  155. Test UniformAugment invalid non-positive number of ops
  156. """
  157. logger.info("Test CPP UniformAugment invalid non-positive num_ops exception")
  158. transforms_ua = [C.RandomCrop(size=[224, 224], padding=[32, 32, 32, 32]),
  159. C.RandomHorizontalFlip(),
  160. C.RandomVerticalFlip(),
  161. C.RandomColorAdjust(),
  162. C.RandomRotation(degrees=45)]
  163. try:
  164. _ = C.UniformAugment(transforms=transforms_ua, num_ops=num_ops)
  165. except Exception as e:
  166. logger.info("Got an exception in DE: {}".format(str(e)))
  167. assert "Input num_ops must be greater than 0" in str(e)
  168. def test_cpp_uniform_augment_exception_float_numops(num_ops=2.5):
  169. """
  170. Test UniformAugment invalid float number of ops
  171. """
  172. logger.info("Test CPP UniformAugment invalid float num_ops exception")
  173. transforms_ua = [C.RandomCrop(size=[224, 224], padding=[32, 32, 32, 32]),
  174. C.RandomHorizontalFlip(),
  175. C.RandomVerticalFlip(),
  176. C.RandomColorAdjust(),
  177. C.RandomRotation(degrees=45)]
  178. try:
  179. _ = C.UniformAugment(transforms=transforms_ua, num_ops=num_ops)
  180. except Exception as e:
  181. logger.info("Got an exception in DE: {}".format(str(e)))
  182. assert "Argument num_ops with value 2.5 is not of type (<class 'int'>,)" in str(e)
  183. def test_cpp_uniform_augment_random_crop_badinput(num_ops=1):
  184. """
  185. Test UniformAugment with greater crop size
  186. """
  187. logger.info("Test CPP UniformAugment with random_crop bad input")
  188. batch_size = 2
  189. cifar10_dir = "../data/dataset/testCifar10Data"
  190. ds1 = de.Cifar10Dataset(cifar10_dir, shuffle=False) # shape = [32,32,3]
  191. transforms_ua = [
  192. # Note: crop size [224, 224] > image size [32, 32]
  193. C.RandomCrop(size=[224, 224]),
  194. C.RandomHorizontalFlip()
  195. ]
  196. uni_aug = C.UniformAugment(transforms=transforms_ua, num_ops=num_ops)
  197. ds1 = ds1.map(operations=uni_aug, input_columns="image")
  198. # apply DatasetOps
  199. ds1 = ds1.batch(batch_size, drop_remainder=True, num_parallel_workers=1)
  200. num_batches = 0
  201. try:
  202. for _ in ds1.create_dict_iterator(num_epochs=1, output_numpy=True):
  203. num_batches += 1
  204. except Exception as e:
  205. assert "Crop size" in str(e)
  206. if __name__ == "__main__":
  207. test_uniform_augment(num_ops=1, plot=True)
  208. test_cpp_uniform_augment(num_ops=1, plot=True)
  209. test_cpp_uniform_augment_exception_pyops(num_ops=1)
  210. test_cpp_uniform_augment_exception_large_numops(num_ops=6)
  211. test_cpp_uniform_augment_exception_nonpositive_numops(num_ops=0)
  212. test_cpp_uniform_augment_exception_float_numops(num_ops=2.5)
  213. test_cpp_uniform_augment_random_crop_badinput(num_ops=1)