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_caltech256.py 8.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 Caltech256 dataset operators
  17. """
  18. import numpy as np
  19. import pytest
  20. import mindspore.dataset as ds
  21. import mindspore.dataset.vision.c_transforms as c_vision
  22. from mindspore import log as logger
  23. IMAGE_DATA_DIR = "../data/dataset/testPK/data"
  24. WRONG_DIR = "../data/dataset/notExist"
  25. def test_caltech256_basic():
  26. """
  27. Feature: Caltech256Dataset
  28. Description: basic test of Caltech256Dataset
  29. Expectation: the data is processed successfully
  30. """
  31. logger.info("Test Caltech256Dataset Op")
  32. # case 1: test read all data
  33. all_data_1 = ds.Caltech256Dataset(IMAGE_DATA_DIR, shuffle=False)
  34. all_data_2 = ds.Caltech256Dataset(IMAGE_DATA_DIR, shuffle=False)
  35. num_iter = 0
  36. for item1, item2 in zip(all_data_1.create_dict_iterator(num_epochs=1, output_numpy=True),
  37. all_data_2.create_dict_iterator(num_epochs=1, output_numpy=True)):
  38. np.testing.assert_array_equal(item1["label"], item2["label"])
  39. num_iter += 1
  40. assert num_iter == 44
  41. # case 2: test decode
  42. all_data_1 = ds.Caltech256Dataset(IMAGE_DATA_DIR, decode=True, shuffle=False)
  43. all_data_2 = ds.Caltech256Dataset(IMAGE_DATA_DIR, decode=True, shuffle=False)
  44. num_iter = 0
  45. for item1, item2 in zip(all_data_1.create_dict_iterator(num_epochs=1, output_numpy=True),
  46. all_data_2.create_dict_iterator(num_epochs=1, output_numpy=True)):
  47. np.testing.assert_array_equal(item1["label"], item2["label"])
  48. num_iter += 1
  49. assert num_iter == 44
  50. # case 3: test num_samples
  51. all_data = ds.Caltech256Dataset(IMAGE_DATA_DIR, num_samples=4)
  52. num_iter = 0
  53. for _ in all_data.create_dict_iterator(num_epochs=1):
  54. num_iter += 1
  55. assert num_iter == 4
  56. # case 4: test repeat
  57. all_data = ds.Caltech256Dataset(IMAGE_DATA_DIR, num_samples=4)
  58. all_data = all_data.repeat(2)
  59. num_iter = 0
  60. for _ in all_data.create_dict_iterator(num_epochs=1):
  61. num_iter += 1
  62. assert num_iter == 8
  63. # case 5: test get_dataset_size, resize and batch
  64. all_data = ds.Caltech256Dataset(IMAGE_DATA_DIR, num_samples=4)
  65. all_data = all_data.map(operations=[c_vision.Decode(), c_vision.Resize((224, 224))], input_columns=["image"],
  66. num_parallel_workers=1)
  67. assert all_data.get_dataset_size() == 4
  68. assert all_data.get_batch_size() == 1
  69. # drop_remainder is default to be False
  70. all_data = all_data.batch(batch_size=3)
  71. assert all_data.get_batch_size() == 3
  72. assert all_data.get_dataset_size() == 2
  73. num_iter = 0
  74. for _ in all_data.create_dict_iterator(num_epochs=1):
  75. num_iter += 1
  76. assert num_iter == 2
  77. def test_caltech256_decode():
  78. """
  79. Feature: Caltech256Dataset
  80. Description: validate Caltech256Dataset with decode
  81. Expectation: the data is processed successfully
  82. """
  83. logger.info("Validate Caltech256Dataset with decode")
  84. # define parameters
  85. repeat_count = 1
  86. data1 = ds.Caltech256Dataset(IMAGE_DATA_DIR, decode=True)
  87. data1 = data1.repeat(repeat_count)
  88. num_iter = 0
  89. # each data is a dictionary
  90. for item in data1.create_dict_iterator(num_epochs=1):
  91. # in this example, each dictionary has keys "image" and "label"
  92. logger.info("image is {}".format(item["image"]))
  93. logger.info("label is {}".format(item["label"]))
  94. num_iter += 1
  95. logger.info("Number of data in data1: {}".format(num_iter))
  96. assert num_iter == 44
  97. def test_caltech256_sequential_sampler():
  98. """
  99. Feature: Caltech256Dataset
  100. Description: test Caltech256Dataset with SequentialSampler
  101. Expectation: the data is processed successfully
  102. """
  103. logger.info("Test Caltech256Dataset Op with SequentialSampler")
  104. num_samples = 4
  105. sampler = ds.SequentialSampler(num_samples=num_samples)
  106. all_data_1 = ds.Caltech256Dataset(IMAGE_DATA_DIR, sampler=sampler)
  107. all_data_2 = ds.Caltech256Dataset(IMAGE_DATA_DIR, shuffle=False, num_samples=num_samples)
  108. label_list_1, label_list_2 = [], []
  109. num_iter = 0
  110. for item1, item2 in zip(all_data_1.create_dict_iterator(num_epochs=1),
  111. all_data_2.create_dict_iterator(num_epochs=1)):
  112. label_list_1.append(item1["label"].asnumpy())
  113. label_list_2.append(item2["label"].asnumpy())
  114. num_iter += 1
  115. np.testing.assert_array_equal(label_list_1, label_list_2)
  116. assert num_iter == num_samples
  117. def test_caltech256_random_sampler():
  118. """
  119. Feature: Caltech256Dataset
  120. Description: test Caltech256Dataset with RandomSampler
  121. Expectation: the data is processed successfully
  122. """
  123. logger.info("Test Caltech256Dataset Op with RandomSampler")
  124. # define parameters
  125. repeat_count = 1
  126. # apply dataset operations
  127. sampler = ds.RandomSampler()
  128. data1 = ds.Caltech256Dataset(IMAGE_DATA_DIR, sampler=sampler)
  129. data1 = data1.repeat(repeat_count)
  130. num_iter = 0
  131. # each data is a dictionary
  132. for item in data1.create_dict_iterator(num_epochs=1):
  133. # in this example, each dictionary has keys "image" and "label"
  134. logger.info("image is {}".format(item["image"]))
  135. logger.info("label is {}".format(item["label"]))
  136. num_iter += 1
  137. logger.info("Number of data in data1: {}".format(num_iter))
  138. assert num_iter == 44
  139. def test_caltech256_exception():
  140. """
  141. Feature: Caltech256Dataset
  142. Description: test error cases for Caltech256Dataset
  143. Expectation: throw correct error and message
  144. """
  145. logger.info("Test error cases for Caltech256Dataset")
  146. error_msg_1 = "sampler and shuffle cannot be specified at the same time"
  147. with pytest.raises(RuntimeError, match=error_msg_1):
  148. ds.Caltech256Dataset(IMAGE_DATA_DIR, shuffle=False, sampler=ds.SequentialSampler(1))
  149. error_msg_2 = "sampler and sharding cannot be specified at the same time"
  150. with pytest.raises(RuntimeError, match=error_msg_2):
  151. ds.Caltech256Dataset(IMAGE_DATA_DIR, sampler=ds.SequentialSampler(1), num_shards=2, shard_id=0)
  152. error_msg_3 = "num_shards is specified and currently requires shard_id as well"
  153. with pytest.raises(RuntimeError, match=error_msg_3):
  154. ds.Caltech256Dataset(IMAGE_DATA_DIR, num_shards=10)
  155. error_msg_4 = "shard_id is specified but num_shards is not"
  156. with pytest.raises(RuntimeError, match=error_msg_4):
  157. ds.Caltech256Dataset(IMAGE_DATA_DIR, shard_id=0)
  158. error_msg_5 = "Input shard_id is not within the required interval"
  159. with pytest.raises(ValueError, match=error_msg_5):
  160. ds.Caltech256Dataset(IMAGE_DATA_DIR, num_shards=5, shard_id=-1)
  161. with pytest.raises(ValueError, match=error_msg_5):
  162. ds.Caltech256Dataset(IMAGE_DATA_DIR, num_shards=5, shard_id=5)
  163. with pytest.raises(ValueError, match=error_msg_5):
  164. ds.Caltech256Dataset(IMAGE_DATA_DIR, num_shards=2, shard_id=5)
  165. error_msg_6 = "num_parallel_workers exceeds"
  166. with pytest.raises(ValueError, match=error_msg_6):
  167. ds.Caltech256Dataset(IMAGE_DATA_DIR, shuffle=False, num_parallel_workers=0)
  168. with pytest.raises(ValueError, match=error_msg_6):
  169. ds.Caltech256Dataset(IMAGE_DATA_DIR, shuffle=False, num_parallel_workers=256)
  170. with pytest.raises(ValueError, match=error_msg_6):
  171. ds.Caltech256Dataset(IMAGE_DATA_DIR, shuffle=False, num_parallel_workers=-2)
  172. error_msg_7 = "Argument shard_id"
  173. with pytest.raises(TypeError, match=error_msg_7):
  174. ds.Caltech256Dataset(IMAGE_DATA_DIR, num_shards=2, shard_id="0")
  175. error_msg_8 = "does not exist or is not a directory or permission denied!"
  176. with pytest.raises(ValueError, match=error_msg_8):
  177. all_data = ds.Caltech256Dataset(WRONG_DIR)
  178. for _ in all_data.create_dict_iterator(num_epochs=1):
  179. pass
  180. if __name__ == '__main__':
  181. test_caltech256_basic()
  182. test_caltech256_decode()
  183. test_caltech256_sequential_sampler()
  184. test_caltech256_random_sampler()
  185. test_caltech256_exception()