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_linear_transformation.py 8.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 LinearTransformation op in DE
  17. """
  18. import numpy as np
  19. import mindspore.dataset as ds
  20. import mindspore.dataset.transforms.py_transforms
  21. import mindspore.dataset.vision.py_transforms as py_vision
  22. from mindspore import log as logger
  23. from util import diff_mse, visualize_list, save_and_check_md5
  24. GENERATE_GOLDEN = False
  25. DATA_DIR = ["../data/dataset/test_tf_file_3_images/train-0000-of-0001.data"]
  26. SCHEMA_DIR = "../data/dataset/test_tf_file_3_images/datasetSchema.json"
  27. def test_linear_transformation_op(plot=False):
  28. """
  29. Test LinearTransformation op: verify if images transform correctly
  30. """
  31. logger.info("test_linear_transformation_01")
  32. # Initialize parameters
  33. height = 50
  34. weight = 50
  35. dim = 3 * height * weight
  36. transformation_matrix = np.eye(dim)
  37. mean_vector = np.zeros(dim)
  38. # Define operations
  39. transforms = [
  40. py_vision.Decode(),
  41. py_vision.CenterCrop([height, weight]),
  42. py_vision.ToTensor()
  43. ]
  44. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  45. # First dataset
  46. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  47. data1 = data1.map(operations=transform, input_columns=["image"])
  48. # Note: if transformation matrix is diagonal matrix with all 1 in diagonal,
  49. # the output matrix in expected to be the same as the input matrix.
  50. data1 = data1.map(operations=py_vision.LinearTransformation(transformation_matrix, mean_vector),
  51. input_columns=["image"])
  52. # Second dataset
  53. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  54. data2 = data2.map(operations=transform, input_columns=["image"])
  55. image_transformed = []
  56. image = []
  57. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True),
  58. data2.create_dict_iterator(num_epochs=1, output_numpy=True)):
  59. image1 = (item1["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  60. image2 = (item2["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
  61. image_transformed.append(image1)
  62. image.append(image2)
  63. mse = diff_mse(image1, image2)
  64. assert mse == 0
  65. if plot:
  66. visualize_list(image, image_transformed)
  67. def test_linear_transformation_md5():
  68. """
  69. Test LinearTransformation op: valid params (transformation_matrix, mean_vector)
  70. Expected to pass
  71. """
  72. logger.info("test_linear_transformation_md5")
  73. # Initialize parameters
  74. height = 50
  75. weight = 50
  76. dim = 3 * height * weight
  77. transformation_matrix = np.ones([dim, dim])
  78. mean_vector = np.zeros(dim)
  79. # Generate dataset
  80. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  81. transforms = [
  82. py_vision.Decode(),
  83. py_vision.CenterCrop([height, weight]),
  84. py_vision.ToTensor(),
  85. py_vision.LinearTransformation(transformation_matrix, mean_vector)
  86. ]
  87. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  88. data1 = data1.map(operations=transform, input_columns=["image"])
  89. # Compare with expected md5 from images
  90. filename = "linear_transformation_01_result.npz"
  91. save_and_check_md5(data1, filename, generate_golden=GENERATE_GOLDEN)
  92. def test_linear_transformation_exception_01():
  93. """
  94. Test LinearTransformation op: transformation_matrix is not provided
  95. Expected to raise ValueError
  96. """
  97. logger.info("test_linear_transformation_exception_01")
  98. # Initialize parameters
  99. height = 50
  100. weight = 50
  101. dim = 3 * height * weight
  102. mean_vector = np.zeros(dim)
  103. # Generate dataset
  104. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  105. try:
  106. transforms = [
  107. py_vision.Decode(),
  108. py_vision.CenterCrop([height, weight]),
  109. py_vision.ToTensor(),
  110. py_vision.LinearTransformation(None, mean_vector)
  111. ]
  112. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  113. data1 = data1.map(operations=transform, input_columns=["image"])
  114. except TypeError as e:
  115. logger.info("Got an exception in DE: {}".format(str(e)))
  116. assert "Argument transformation_matrix with value None is not of type (<class 'numpy.ndarray'>,)" in str(e)
  117. def test_linear_transformation_exception_02():
  118. """
  119. Test LinearTransformation op: mean_vector is not provided
  120. Expected to raise ValueError
  121. """
  122. logger.info("test_linear_transformation_exception_02")
  123. # Initialize parameters
  124. height = 50
  125. weight = 50
  126. dim = 3 * height * weight
  127. transformation_matrix = np.ones([dim, dim])
  128. # Generate dataset
  129. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  130. try:
  131. transforms = [
  132. py_vision.Decode(),
  133. py_vision.CenterCrop([height, weight]),
  134. py_vision.ToTensor(),
  135. py_vision.LinearTransformation(transformation_matrix, None)
  136. ]
  137. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  138. data1 = data1.map(operations=transform, input_columns=["image"])
  139. except TypeError as e:
  140. logger.info("Got an exception in DE: {}".format(str(e)))
  141. assert "Argument mean_vector with value None is not of type (<class 'numpy.ndarray'>,)" in str(e)
  142. def test_linear_transformation_exception_03():
  143. """
  144. Test LinearTransformation op: transformation_matrix is not a square matrix
  145. Expected to raise ValueError
  146. """
  147. logger.info("test_linear_transformation_exception_03")
  148. # Initialize parameters
  149. height = 50
  150. weight = 50
  151. dim = 3 * height * weight
  152. transformation_matrix = np.ones([dim, dim - 1])
  153. mean_vector = np.zeros(dim)
  154. # Generate dataset
  155. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  156. try:
  157. transforms = [
  158. py_vision.Decode(),
  159. py_vision.CenterCrop([height, weight]),
  160. py_vision.ToTensor(),
  161. py_vision.LinearTransformation(transformation_matrix, mean_vector)
  162. ]
  163. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  164. data1 = data1.map(operations=transform, input_columns=["image"])
  165. except ValueError as e:
  166. logger.info("Got an exception in DE: {}".format(str(e)))
  167. assert "square matrix" in str(e)
  168. def test_linear_transformation_exception_04():
  169. """
  170. Test LinearTransformation op: mean_vector does not match dimension of transformation_matrix
  171. Expected to raise ValueError
  172. """
  173. logger.info("test_linear_transformation_exception_04")
  174. # Initialize parameters
  175. height = 50
  176. weight = 50
  177. dim = 3 * height * weight
  178. transformation_matrix = np.ones([dim, dim])
  179. mean_vector = np.zeros(dim - 1)
  180. # Generate dataset
  181. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  182. try:
  183. transforms = [
  184. py_vision.Decode(),
  185. py_vision.CenterCrop([height, weight]),
  186. py_vision.ToTensor(),
  187. py_vision.LinearTransformation(transformation_matrix, mean_vector)
  188. ]
  189. transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
  190. data1 = data1.map(operations=transform, input_columns=["image"])
  191. except ValueError as e:
  192. logger.info("Got an exception in DE: {}".format(str(e)))
  193. assert "should match" in str(e)
  194. if __name__ == '__main__':
  195. test_linear_transformation_op(plot=True)
  196. test_linear_transformation_md5()
  197. test_linear_transformation_exception_01()
  198. test_linear_transformation_exception_02()
  199. test_linear_transformation_exception_03()
  200. test_linear_transformation_exception_04()