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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. # Copyright 2021 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. import os
  16. import matplotlib.pyplot as plt
  17. import numpy as np
  18. import pytest
  19. import mindspore.dataset as ds
  20. import mindspore.dataset.vision.c_transforms as c_vision
  21. DATA_DIR_SEMEION = "../data/dataset/testSemeionData"
  22. def load_semeion(path):
  23. """
  24. load Semeion data
  25. """
  26. fp = os.path.realpath(os.path.join(path, "semeion.data"))
  27. data = np.loadtxt(fp)
  28. images = (data[:, :256]).astype('uint8')
  29. images = images.reshape(-1, 16, 16)
  30. labels = np.nonzero(data[:, 256:])[1]
  31. return images, labels
  32. def visualize_dataset(images, labels):
  33. """
  34. Helper function to visualize the dataset samples
  35. """
  36. num_samples = len(images)
  37. for i in range(num_samples):
  38. plt.subplot(1, num_samples, i + 1)
  39. plt.imshow(images[i])
  40. plt.title(labels[i])
  41. plt.show()
  42. def test_semeion_content_check():
  43. """
  44. Feature: SemeionDataset
  45. Description: Check content of each sample
  46. Expectation: correct content
  47. """
  48. data1 = ds.SemeionDataset(DATA_DIR_SEMEION, num_samples=10, shuffle=False)
  49. images, labels = load_semeion(DATA_DIR_SEMEION)
  50. num_iter = 0
  51. # in this example, each dictionary has keys "image" and "label"
  52. for i, d in enumerate(data1.create_dict_iterator(num_epochs=1, output_numpy=True)):
  53. np.testing.assert_array_equal(d["image"], images[i])
  54. np.testing.assert_array_equal(d["label"], labels[i])
  55. num_iter += 1
  56. assert num_iter == 10
  57. def test_semeion_basic():
  58. """
  59. Feature: SemeionDataset
  60. Description: use different data to test the functions of different versions
  61. Expectation: all samples(10)
  62. num_samples
  63. set 5
  64. get 5
  65. num_parallel_workers
  66. set 1(num_samples=6)
  67. get 6
  68. num repeat
  69. set 3(num_samples=3)
  70. get 9
  71. """
  72. # case 0: test loading all samples
  73. data0 = ds.SemeionDataset(DATA_DIR_SEMEION)
  74. num_iter0 = 0
  75. for _ in data0.create_dict_iterator(num_epochs=1):
  76. num_iter0 += 1
  77. assert num_iter0 == 10
  78. # case 1: test num_samples
  79. data1 = ds.SemeionDataset(DATA_DIR_SEMEION, num_samples=5)
  80. num_iter1 = 0
  81. for _ in data1.create_dict_iterator(num_epochs=1):
  82. num_iter1 += 1
  83. assert num_iter1 == 5
  84. # case 2: test num_parallel_workers
  85. data2 = ds.SemeionDataset(DATA_DIR_SEMEION, num_samples=6, num_parallel_workers=1)
  86. num_iter2 = 0
  87. for _ in data2.create_dict_iterator(num_epochs=1):
  88. num_iter2 += 1
  89. assert num_iter2 == 6
  90. # case 3: test repeat
  91. data3 = ds.SemeionDataset(DATA_DIR_SEMEION, num_samples=3)
  92. data3 = data3.repeat(3)
  93. num_iter3 = 0
  94. for _ in data3.create_dict_iterator(num_epochs=1):
  95. num_iter3 += 1
  96. assert num_iter3 == 9
  97. def test_semeion_sequential_sampler():
  98. """
  99. Feature: SemeionDataset
  100. Description: test semeion sequential sampler
  101. Expectation: correct data
  102. """
  103. num_samples = 4
  104. sampler = ds.SequentialSampler(num_samples=num_samples)
  105. data1 = ds.SemeionDataset(DATA_DIR_SEMEION, sampler=sampler)
  106. data2 = ds.SemeionDataset(DATA_DIR_SEMEION, shuffle=False, num_samples=num_samples)
  107. num_iter = 0
  108. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True),
  109. data2.create_dict_iterator(num_epochs=1, output_numpy=True)):
  110. np.testing.assert_equal(item1["label"], item2["label"])
  111. np.testing.assert_equal(item1["image"], item2["image"])
  112. num_iter += 1
  113. assert num_iter == num_samples
  114. def test_semeion_exceptions():
  115. """
  116. Feature: SemeionDataset
  117. Description: error test
  118. Expectation: throw error
  119. """
  120. error_msg_1 = "sampler and shuffle cannot be specified at the same time"
  121. with pytest.raises(RuntimeError, match=error_msg_1):
  122. ds.SemeionDataset(DATA_DIR_SEMEION, shuffle=False, sampler=ds.PKSampler(3))
  123. error_msg_2 = "sampler and sharding cannot be specified at the same time"
  124. with pytest.raises(RuntimeError, match=error_msg_2):
  125. ds.SemeionDataset(DATA_DIR_SEMEION, sampler=ds.PKSampler(3), num_shards=2, shard_id=0)
  126. error_msg_3 = "num_shards is specified and currently requires shard_id as well"
  127. with pytest.raises(RuntimeError, match=error_msg_3):
  128. ds.SemeionDataset(DATA_DIR_SEMEION, num_shards=10)
  129. error_msg_4 = "shard_id is specified but num_shards is not"
  130. with pytest.raises(RuntimeError, match=error_msg_4):
  131. ds.SemeionDataset(DATA_DIR_SEMEION, shard_id=0)
  132. error_msg_5 = "Input shard_id is not within the required interval"
  133. with pytest.raises(ValueError, match=error_msg_5):
  134. ds.SemeionDataset(DATA_DIR_SEMEION, num_shards=2, shard_id=-1)
  135. with pytest.raises(ValueError, match=error_msg_5):
  136. ds.SemeionDataset(DATA_DIR_SEMEION, num_shards=2, shard_id=5)
  137. error_msg_6 = "num_parallel_workers exceeds"
  138. with pytest.raises(ValueError, match=error_msg_6):
  139. ds.SemeionDataset(DATA_DIR_SEMEION, shuffle=False, num_parallel_workers=0)
  140. with pytest.raises(ValueError, match=error_msg_6):
  141. ds.SemeionDataset(DATA_DIR_SEMEION, shuffle=False, num_parallel_workers=256)
  142. def test_semeion_visualize(plot=False):
  143. """
  144. Feature: SemeionDataset
  145. Description: visualize SemeionDataset results
  146. Expectation: visualization
  147. """
  148. data1 = ds.SemeionDataset(DATA_DIR_SEMEION, num_samples=10, shuffle=False)
  149. num_iter = 0
  150. image_list, label_list = [], []
  151. for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
  152. image = item["image"]
  153. label = item["label"]
  154. image_list.append(image)
  155. label_list.append("label {}".format(label))
  156. assert isinstance(image, np.ndarray)
  157. assert image.shape == (16, 16)
  158. assert image.dtype == np.uint8
  159. assert label.dtype == np.uint32
  160. num_iter += 1
  161. assert num_iter == 10
  162. if plot:
  163. visualize_dataset(image_list, label_list)
  164. def test_semeion_exception_file_path():
  165. """
  166. Feature: SemeionDataset
  167. Description: error test
  168. Expectation: throw error
  169. """
  170. def exception_func(item):
  171. raise Exception("Error occur!")
  172. try:
  173. data = ds.SemeionDataset(DATA_DIR_SEMEION)
  174. data = data.map(operations=exception_func, input_columns=["image"], num_parallel_workers=1)
  175. num_rows = 0
  176. for _ in data.create_dict_iterator():
  177. num_rows += 1
  178. assert False
  179. except RuntimeError as e:
  180. assert "map operation: [PyFunc] failed. The corresponding data files" in str(e)
  181. try:
  182. data = ds.SemeionDataset(DATA_DIR_SEMEION)
  183. data = data.map(operations=exception_func, input_columns=["label"], num_parallel_workers=1)
  184. num_rows = 0
  185. for _ in data.create_dict_iterator():
  186. num_rows += 1
  187. assert False
  188. except RuntimeError as e:
  189. assert "map operation: [PyFunc] failed. The corresponding data files" in str(e)
  190. def test_semeion_pipeline():
  191. """
  192. Feature: SemeionDataset
  193. Description: Read a sample
  194. Expectation: The amount of each function are equal
  195. """
  196. # Original image
  197. dataset = ds.SemeionDataset(DATA_DIR_SEMEION, num_samples=1)
  198. resize_op = c_vision.Resize((100, 100))
  199. # Filtered image by Resize
  200. dataset = dataset.map(operations=resize_op, input_columns=["image"], num_parallel_workers=1)
  201. i = 0
  202. for _ in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):
  203. i += 1
  204. assert i == 1
  205. if __name__ == '__main__':
  206. test_semeion_content_check()
  207. test_semeion_basic()
  208. test_semeion_sequential_sampler()
  209. test_semeion_exceptions()
  210. test_semeion_visualize(plot=False)
  211. test_semeion_exception_file_path()
  212. test_semeion_pipeline()