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_kmnist.py 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. """
  16. Test KMnist dataset operators
  17. """
  18. import os
  19. import matplotlib.pyplot as plt
  20. import numpy as np
  21. import pytest
  22. import mindspore.dataset as ds
  23. import mindspore.dataset.vision.c_transforms as vision
  24. from mindspore import log as logger
  25. DATA_DIR = "../data/dataset/testMnistData"
  26. def load_kmnist(path):
  27. """
  28. Feature: load_kmnist.
  29. Description: load KMnistDataset.
  30. Expectation: get data of KMnistDataset.
  31. """
  32. labels_path = os.path.realpath(os.path.join(path, 't10k-labels-idx1-ubyte'))
  33. images_path = os.path.realpath(os.path.join(path, 't10k-images-idx3-ubyte'))
  34. with open(os.path.realpath(labels_path), 'rb') as lbpath:
  35. lbpath.read(8)
  36. labels = np.fromfile(lbpath, dtype=np.uint8)
  37. with open(os.path.realpath(images_path), 'rb') as imgpath:
  38. imgpath.read(16)
  39. images = np.fromfile(imgpath, dtype=np.uint8)
  40. images = images.reshape(-1, 28, 28, 1)
  41. images[images > 0] = 255 # Perform binarization to maintain consistency with our API
  42. return images, labels
  43. def visualize_dataset(images, labels):
  44. """
  45. Feature: visualize_dataset.
  46. Description: visualize KMnistDataset.
  47. Expectation: plot images.
  48. """
  49. num_samples = len(images)
  50. for i in range(num_samples):
  51. plt.subplot(1, num_samples, i + 1)
  52. plt.imshow(images[i].squeeze(), cmap=plt.cm.gray)
  53. plt.title(labels[i])
  54. plt.show()
  55. def test_kmnist_content_check():
  56. """
  57. Feature: test_kmnist_content_check.
  58. Description: validate KMnistDataset image readings.
  59. Expectation: get correct value.
  60. """
  61. logger.info("Test KMnistDataset Op with content check")
  62. data1 = ds.KMnistDataset(DATA_DIR, num_samples=100, shuffle=False)
  63. images, labels = load_kmnist(DATA_DIR)
  64. num_iter = 0
  65. # in this example, each dictionary has keys "image" and "label"
  66. image_list, label_list = [], []
  67. for i, data in enumerate(data1.create_dict_iterator(num_epochs=1, output_numpy=True)):
  68. image_list.append(data["image"])
  69. label_list.append("label {}".format(data["label"]))
  70. np.testing.assert_array_equal(data["image"], images[i])
  71. np.testing.assert_array_equal(data["label"], labels[i])
  72. num_iter += 1
  73. assert num_iter == 100
  74. def test_kmnist_basic():
  75. """
  76. Feature: test_kmnist_basic.
  77. Description: test basic usage of KMnistDataset.
  78. Expectation: get correct data.
  79. """
  80. logger.info("Test KMnistDataset Op")
  81. # case 1: test loading whole dataset
  82. data1 = ds.KMnistDataset(DATA_DIR)
  83. num_iter1 = 0
  84. for _ in data1.create_dict_iterator(num_epochs=1):
  85. num_iter1 += 1
  86. assert num_iter1 == 10000
  87. # case 2: test num_samples
  88. data2 = ds.KMnistDataset(DATA_DIR, num_samples=500)
  89. num_iter2 = 0
  90. for _ in data2.create_dict_iterator(num_epochs=1):
  91. num_iter2 += 1
  92. assert num_iter2 == 500
  93. # case 3: test repeat
  94. data3 = ds.KMnistDataset(DATA_DIR, num_samples=200)
  95. data3 = data3.repeat(5)
  96. num_iter3 = 0
  97. for _ in data3.create_dict_iterator(num_epochs=1):
  98. num_iter3 += 1
  99. assert num_iter3 == 1000
  100. # case 4: test batch with drop_remainder=False
  101. data4 = ds.KMnistDataset(DATA_DIR, num_samples=100)
  102. assert data4.get_dataset_size() == 100
  103. assert data4.get_batch_size() == 1
  104. data4 = data4.batch(batch_size=7) # drop_remainder is default to be False
  105. assert data4.get_dataset_size() == 15
  106. assert data4.get_batch_size() == 7
  107. num_iter4 = 0
  108. for _ in data4.create_dict_iterator(num_epochs=1):
  109. num_iter4 += 1
  110. assert num_iter4 == 15
  111. # case 5: test batch with drop_remainder=True
  112. data5 = ds.KMnistDataset(DATA_DIR, num_samples=100)
  113. assert data5.get_dataset_size() == 100
  114. assert data5.get_batch_size() == 1
  115. data5 = data5.batch(batch_size=7, drop_remainder=True) # the rest of incomplete batch will be dropped
  116. assert data5.get_dataset_size() == 14
  117. assert data5.get_batch_size() == 7
  118. num_iter5 = 0
  119. for _ in data5.create_dict_iterator(num_epochs=1):
  120. num_iter5 += 1
  121. assert num_iter5 == 14
  122. # case 6: test get_col_names
  123. data6 = ds.KMnistDataset(DATA_DIR, "train", num_samples=10)
  124. assert data6.get_col_names() == ["image", "label"]
  125. #case 7: test batch
  126. data7 = ds.KMnistDataset(DATA_DIR, num_samples=200)
  127. data7 = data7.batch(100, drop_remainder=True)
  128. num_iter7 = 0
  129. for _ in data7.create_dict_iterator(num_epochs=1):
  130. num_iter7 += 1
  131. assert num_iter7 == 2
  132. def test_kmnist_pk_sampler():
  133. """
  134. Feature: test_kmnist_pk_sampler.
  135. Description: test usage of KMnistDataset with PKSampler.
  136. Expectation: get correct data.
  137. """
  138. logger.info("Test KMnistDataset Op with PKSampler")
  139. golden = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4,
  140. 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9]
  141. sampler = ds.PKSampler(3)
  142. data = ds.KMnistDataset(DATA_DIR, sampler=sampler)
  143. num_iter = 0
  144. label_list = []
  145. for item in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  146. label_list.append(item["label"])
  147. num_iter += 1
  148. np.testing.assert_array_equal(golden, label_list)
  149. assert num_iter == 30
  150. def test_kmnist_sequential_sampler():
  151. """
  152. Feature: test_kmnist_sequential_sampler.
  153. Description: test usage of KMnistDataset with SequentialSampler.
  154. Expectation: get correct data.
  155. """
  156. logger.info("Test KMnistDataset Op with SequentialSampler")
  157. num_samples = 50
  158. sampler = ds.SequentialSampler(num_samples=num_samples)
  159. data1 = ds.KMnistDataset(DATA_DIR, sampler=sampler)
  160. data2 = ds.KMnistDataset(DATA_DIR, shuffle=False, num_samples=num_samples)
  161. label_list1, label_list2 = [], []
  162. num_iter = 0
  163. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
  164. label_list1.append(item1["label"].asnumpy())
  165. label_list2.append(item2["label"].asnumpy())
  166. num_iter += 1
  167. np.testing.assert_array_equal(label_list1, label_list2)
  168. assert num_iter == num_samples
  169. def test_kmnist_exception():
  170. """
  171. Feature: test_kmnist_exception.
  172. Description: test error cases for KMnistDataset.
  173. Expectation: raise exception.
  174. """
  175. logger.info("Test error cases for KMnistDataset")
  176. error_msg_1 = "sampler and shuffle cannot be specified at the same time"
  177. with pytest.raises(RuntimeError, match=error_msg_1):
  178. ds.KMnistDataset(DATA_DIR, shuffle=False, sampler=ds.PKSampler(3))
  179. error_msg_2 = "sampler and sharding cannot be specified at the same time"
  180. with pytest.raises(RuntimeError, match=error_msg_2):
  181. ds.KMnistDataset(DATA_DIR, sampler=ds.PKSampler(3), num_shards=2, shard_id=0)
  182. error_msg_3 = "num_shards is specified and currently requires shard_id as well"
  183. with pytest.raises(RuntimeError, match=error_msg_3):
  184. ds.KMnistDataset(DATA_DIR, num_shards=10)
  185. error_msg_4 = "shard_id is specified but num_shards is not"
  186. with pytest.raises(RuntimeError, match=error_msg_4):
  187. ds.KMnistDataset(DATA_DIR, shard_id=0)
  188. error_msg_5 = "Input shard_id is not within the required interval"
  189. with pytest.raises(ValueError, match=error_msg_5):
  190. ds.KMnistDataset(DATA_DIR, num_shards=5, shard_id=-1)
  191. with pytest.raises(ValueError, match=error_msg_5):
  192. ds.KMnistDataset(DATA_DIR, num_shards=5, shard_id=5)
  193. with pytest.raises(ValueError, match=error_msg_5):
  194. ds.KMnistDataset(DATA_DIR, num_shards=2, shard_id=5)
  195. error_msg_6 = "num_parallel_workers exceeds"
  196. with pytest.raises(ValueError, match=error_msg_6):
  197. ds.KMnistDataset(DATA_DIR, shuffle=False, num_parallel_workers=0)
  198. with pytest.raises(ValueError, match=error_msg_6):
  199. ds.KMnistDataset(DATA_DIR, shuffle=False, num_parallel_workers=256)
  200. with pytest.raises(ValueError, match=error_msg_6):
  201. ds.KMnistDataset(DATA_DIR, shuffle=False, num_parallel_workers=-2)
  202. error_msg_7 = "Argument shard_id"
  203. with pytest.raises(TypeError, match=error_msg_7):
  204. ds.KMnistDataset(DATA_DIR, num_shards=2, shard_id="0")
  205. def exception_func(item):
  206. raise Exception("Error occur!")
  207. error_msg_8 = "The corresponding data files"
  208. with pytest.raises(RuntimeError, match=error_msg_8):
  209. data = ds.KMnistDataset(DATA_DIR)
  210. data = data.map(operations=exception_func, input_columns=["image"], num_parallel_workers=1)
  211. for _ in data.__iter__():
  212. pass
  213. with pytest.raises(RuntimeError, match=error_msg_8):
  214. data = ds.KMnistDataset(DATA_DIR)
  215. data = data.map(operations=vision.Decode(), input_columns=["image"], num_parallel_workers=1)
  216. data = data.map(operations=exception_func, input_columns=["image"], num_parallel_workers=1)
  217. for _ in data.__iter__():
  218. pass
  219. with pytest.raises(RuntimeError, match=error_msg_8):
  220. data = ds.KMnistDataset(DATA_DIR)
  221. data = data.map(operations=exception_func, input_columns=["label"], num_parallel_workers=1)
  222. for _ in data.__iter__():
  223. pass
  224. def test_kmnist_visualize(plot=False):
  225. """
  226. Feature: test_kmnist_visualize.
  227. Description: visualize KMnistDataset results.
  228. Expectation: get correct data and plot them.
  229. """
  230. logger.info("Test KMnistDataset visualization")
  231. data1 = ds.KMnistDataset(DATA_DIR, num_samples=10, shuffle=False)
  232. num_iter = 0
  233. image_list, label_list = [], []
  234. for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
  235. image = item["image"]
  236. label = item["label"]
  237. image_list.append(image)
  238. label_list.append("label {}".format(label))
  239. assert isinstance(image, np.ndarray)
  240. assert image.shape == (28, 28, 1)
  241. assert image.dtype == np.uint8
  242. assert label.dtype == np.uint32
  243. num_iter += 1
  244. assert num_iter == 10
  245. if plot:
  246. visualize_dataset(image_list, label_list)
  247. def test_kmnist_usage():
  248. """
  249. Feature: test_kmnist_usage.
  250. Description: validate KMnistDataset image readings.
  251. Expectation: get correct data.
  252. """
  253. logger.info("Test KMnistDataset usage flag")
  254. def test_config(usage, kmnist_path=None):
  255. kmnist_path = DATA_DIR if kmnist_path is None else kmnist_path
  256. try:
  257. data = ds.KMnistDataset(kmnist_path, usage=usage, shuffle=False)
  258. num_rows = 0
  259. for _ in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  260. num_rows += 1
  261. except (ValueError, TypeError, RuntimeError) as e:
  262. return str(e)
  263. return num_rows
  264. assert test_config("test") == 10000
  265. assert test_config("all") == 10000
  266. assert "KMnistDataset API can't read the data file (interface mismatch or no data found)" in test_config("train")
  267. assert "usage is not within the valid set of ['train', 'test', 'all']" in test_config("invalid")
  268. assert "Argument usage with value ['list'] is not of type [<class 'str'>]" in test_config(["list"])
  269. # change this directory to the folder that contains all kmnist files
  270. all_files_path = None
  271. # the following tests on the entire datasets
  272. if all_files_path is not None:
  273. assert test_config("train", all_files_path) == 60000
  274. assert test_config("test", all_files_path) == 10000
  275. assert test_config("all", all_files_path) == 70000
  276. assert ds.KMnistDataset(all_files_path, usage="train").get_dataset_size() == 60000
  277. assert ds.KMnistDataset(all_files_path, usage="test").get_dataset_size() == 10000
  278. assert ds.KMnistDataset(all_files_path, usage="all").get_dataset_size() == 70000
  279. if __name__ == '__main__':
  280. test_kmnist_content_check()
  281. test_kmnist_basic()
  282. test_kmnist_pk_sampler()
  283. test_kmnist_sequential_sampler()
  284. test_kmnist_exception()
  285. test_kmnist_visualize(plot=True)
  286. test_kmnist_usage()