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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 FashionMnist 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_fashion_mnist(path):
  27. """
  28. Feature: load_fashion_mnist.
  29. Description: load FashionMnistDataset.
  30. Expectation: get data of FashionMnistDataset.
  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(labels_path, 'rb') as lbpath:
  35. lbpath.read(8)
  36. labels = np.fromfile(lbpath, dtype=np.uint8)
  37. with open(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 FashionMnistDataset.
  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_fashion_mnist_content_check():
  56. """
  57. Feature: test_fashion_mnist_content_check.
  58. Description: validate FashionMnistDataset image readings.
  59. Expectation: get correct value.
  60. """
  61. logger.info("Test FashionMnistDataset Op with content check")
  62. data1 = ds.FashionMnistDataset(DATA_DIR, num_samples=100, shuffle=False)
  63. images, labels = load_fashion_mnist(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_fashion_mnist_basic():
  75. """
  76. Feature: test_fashion_mnist_basic.
  77. Description: test basic usage of FashionMnistDataset.
  78. Expectation: get correct data.
  79. """
  80. logger.info("Test FashionMnistDataset Op")
  81. # case 1: test loading whole dataset
  82. data1 = ds.FashionMnistDataset(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.FashionMnistDataset(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.FashionMnistDataset(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.FashionMnistDataset(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.FashionMnistDataset(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.FashionMnistDataset(DATA_DIR, "train", num_samples=10)
  124. assert data6.get_col_names() == ["image", "label"]
  125. def test_fashion_mnist_pk_sampler():
  126. """
  127. Feature: test_fashion_mnist_pk_sampler.
  128. Description: test usage of FashionMnistDataset with PKSampler.
  129. Expectation: get correct data.
  130. """
  131. logger.info("Test FashionMnistDataset Op with PKSampler")
  132. golden = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4,
  133. 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9]
  134. sampler = ds.PKSampler(3)
  135. data = ds.FashionMnistDataset(DATA_DIR, sampler=sampler)
  136. num_iter = 0
  137. label_list = []
  138. for item in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  139. label_list.append(item["label"])
  140. num_iter += 1
  141. np.testing.assert_array_equal(golden, label_list)
  142. assert num_iter == 30
  143. def test_fashion_mnist_sequential_sampler():
  144. """
  145. Feature: test_fashion_mnist_sequential_sampler.
  146. Description: test usage of FashionMnistDataset with SequentialSampler.
  147. Expectation: get correct data.
  148. """
  149. logger.info("Test FashionMnistDataset Op with SequentialSampler")
  150. num_samples = 50
  151. sampler = ds.SequentialSampler(num_samples=num_samples)
  152. data1 = ds.FashionMnistDataset(DATA_DIR, sampler=sampler)
  153. data2 = ds.FashionMnistDataset(DATA_DIR, shuffle=False, num_samples=num_samples)
  154. label_list1, label_list2 = [], []
  155. num_iter = 0
  156. for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
  157. label_list1.append(item1["label"].asnumpy())
  158. label_list2.append(item2["label"].asnumpy())
  159. num_iter += 1
  160. np.testing.assert_array_equal(label_list1, label_list2)
  161. assert num_iter == num_samples
  162. def test_fashion_mnist_exception():
  163. """
  164. Feature: test_fashion_mnist_exception.
  165. Description: test error cases for FashionMnistDataset.
  166. Expectation: raise exception.
  167. """
  168. logger.info("Test error cases for FashionMnistDataset")
  169. error_msg_1 = "sampler and shuffle cannot be specified at the same time"
  170. with pytest.raises(RuntimeError, match=error_msg_1):
  171. ds.FashionMnistDataset(DATA_DIR, shuffle=False, sampler=ds.PKSampler(3))
  172. error_msg_2 = "sampler and sharding cannot be specified at the same time"
  173. with pytest.raises(RuntimeError, match=error_msg_2):
  174. ds.FashionMnistDataset(DATA_DIR, sampler=ds.PKSampler(3), num_shards=2, shard_id=0)
  175. error_msg_3 = "num_shards is specified and currently requires shard_id as well"
  176. with pytest.raises(RuntimeError, match=error_msg_3):
  177. ds.FashionMnistDataset(DATA_DIR, num_shards=10)
  178. error_msg_4 = "shard_id is specified but num_shards is not"
  179. with pytest.raises(RuntimeError, match=error_msg_4):
  180. ds.FashionMnistDataset(DATA_DIR, shard_id=0)
  181. error_msg_5 = "Input shard_id is not within the required interval"
  182. with pytest.raises(ValueError, match=error_msg_5):
  183. ds.FashionMnistDataset(DATA_DIR, num_shards=5, shard_id=-1)
  184. with pytest.raises(ValueError, match=error_msg_5):
  185. ds.FashionMnistDataset(DATA_DIR, num_shards=5, shard_id=5)
  186. with pytest.raises(ValueError, match=error_msg_5):
  187. ds.FashionMnistDataset(DATA_DIR, num_shards=2, shard_id=5)
  188. error_msg_6 = "num_parallel_workers exceeds"
  189. with pytest.raises(ValueError, match=error_msg_6):
  190. ds.FashionMnistDataset(DATA_DIR, shuffle=False, num_parallel_workers=0)
  191. with pytest.raises(ValueError, match=error_msg_6):
  192. ds.FashionMnistDataset(DATA_DIR, shuffle=False, num_parallel_workers=256)
  193. with pytest.raises(ValueError, match=error_msg_6):
  194. ds.FashionMnistDataset(DATA_DIR, shuffle=False, num_parallel_workers=-2)
  195. error_msg_7 = "Argument shard_id"
  196. with pytest.raises(TypeError, match=error_msg_7):
  197. ds.FashionMnistDataset(DATA_DIR, num_shards=2, shard_id="0")
  198. def exception_func(item):
  199. raise Exception("Error occur!")
  200. error_msg_8 = "The corresponding data files"
  201. with pytest.raises(RuntimeError, match=error_msg_8):
  202. data = ds.FashionMnistDataset(DATA_DIR)
  203. data = data.map(operations=exception_func, input_columns=["image"], num_parallel_workers=1)
  204. for _ in data.__iter__():
  205. pass
  206. with pytest.raises(RuntimeError, match=error_msg_8):
  207. data = ds.FashionMnistDataset(DATA_DIR)
  208. data = data.map(operations=vision.Decode(), input_columns=["image"], num_parallel_workers=1)
  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.FashionMnistDataset(DATA_DIR)
  214. data = data.map(operations=exception_func, input_columns=["label"], num_parallel_workers=1)
  215. for _ in data.__iter__():
  216. pass
  217. def test_fashion_mnist_visualize(plot=False):
  218. """
  219. Feature: test_fashion_mnist_visualize.
  220. Description: visualize FashionMnistDataset results.
  221. Expectation: get correct data and plot them.
  222. """
  223. logger.info("Test FashionMnistDataset visualization")
  224. data1 = ds.FashionMnistDataset(DATA_DIR, num_samples=10, shuffle=False)
  225. num_iter = 0
  226. image_list, label_list = [], []
  227. for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
  228. image = item["image"]
  229. label = item["label"]
  230. image_list.append(image)
  231. label_list.append("label {}".format(label))
  232. assert isinstance(image, np.ndarray)
  233. assert image.shape == (28, 28, 1)
  234. assert image.dtype == np.uint8
  235. assert label.dtype == np.uint32
  236. num_iter += 1
  237. assert num_iter == 10
  238. if plot:
  239. visualize_dataset(image_list, label_list)
  240. def test_fashion_mnist_usage():
  241. """
  242. Feature: test_fashion_mnist_usage.
  243. Description: validate FashionMnistDataset image readings.
  244. Expectation: get correct data.
  245. """
  246. logger.info("Test FashionMnistDataset usage flag")
  247. def test_config(usage, fashion_mnist_path=None):
  248. fashion_mnist_path = DATA_DIR if fashion_mnist_path is None else fashion_mnist_path
  249. try:
  250. data = ds.FashionMnistDataset(fashion_mnist_path, usage=usage, shuffle=False)
  251. num_rows = 0
  252. for _ in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  253. num_rows += 1
  254. except (ValueError, TypeError, RuntimeError) as e:
  255. return str(e)
  256. return num_rows
  257. assert test_config("test") == 10000
  258. assert test_config("all") == 10000
  259. assert "FashionMnistDataset API can't read the data file (interface mismatch or no data found)" \
  260. in test_config("train")
  261. assert "usage is not within the valid set of ['train', 'test', 'all']" in test_config("invalid")
  262. assert "Argument usage with value ['list'] is not of type [<class 'str'>]" in test_config(["list"])
  263. # change this directory to the folder that contains all fashionmnist files
  264. all_files_path = None
  265. # the following tests on the entire datasets
  266. if all_files_path is not None:
  267. assert test_config("train", all_files_path) == 60000
  268. assert test_config("test", all_files_path) == 10000
  269. assert test_config("all", all_files_path) == 70000
  270. assert ds.FashionMnistDataset(all_files_path, usage="train").get_dataset_size() == 60000
  271. assert ds.FashionMnistDataset(all_files_path, usage="test").get_dataset_size() == 10000
  272. assert ds.FashionMnistDataset(all_files_path, usage="all").get_dataset_size() == 70000
  273. if __name__ == '__main__':
  274. test_fashion_mnist_content_check()
  275. test_fashion_mnist_basic()
  276. test_fashion_mnist_pk_sampler()
  277. test_fashion_mnist_sequential_sampler()
  278. test_fashion_mnist_exception()
  279. test_fashion_mnist_visualize(plot=True)
  280. test_fashion_mnist_usage()