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 12 kB

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