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_sampler.py 10 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. # Copyright 2020 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 numpy as np
  16. import pytest
  17. import mindspore.dataset as ds
  18. from mindspore import log as logger
  19. # test5trainimgs.json contains 5 images whose un-decoded shape is [83554, 54214, 65512, 54214, 64631]
  20. # the label of each image is [0,0,0,1,1] each image can be uniquely identified
  21. # via the following lookup table (dict){(83554, 0): 0, (54214, 0): 1, (54214, 1): 2, (65512, 0): 3, (64631, 1): 4}
  22. def test_sequential_sampler(print_res=False):
  23. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  24. map_ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  25. def test_config(num_samples, num_repeats=None):
  26. sampler = ds.SequentialSampler(num_samples=num_samples)
  27. data1 = ds.ManifestDataset(manifest_file, sampler=sampler)
  28. if num_repeats is not None:
  29. data1 = data1.repeat(num_repeats)
  30. res = []
  31. for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
  32. logger.info("item[image].shape[0]: {}, item[label].item(): {}"
  33. .format(item["image"].shape[0], item["label"].item()))
  34. res.append(map_[(item["image"].shape[0], item["label"].item())])
  35. if print_res:
  36. logger.info("image.shapes and labels: {}".format(res))
  37. return res
  38. assert test_config(num_samples=3, num_repeats=None) == [0, 1, 2]
  39. assert test_config(num_samples=None, num_repeats=2) == [0, 1, 2, 3, 4] * 2
  40. assert test_config(num_samples=4, num_repeats=2) == [0, 1, 2, 3] * 2
  41. def test_random_sampler(print_res=False):
  42. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  43. map_ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  44. def test_config(replacement, num_samples, num_repeats):
  45. sampler = ds.RandomSampler(replacement=replacement, num_samples=num_samples)
  46. data1 = ds.ManifestDataset(manifest_file, sampler=sampler)
  47. data1 = data1.repeat(num_repeats)
  48. res = []
  49. for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
  50. res.append(map_[(item["image"].shape[0], item["label"].item())])
  51. if print_res:
  52. logger.info("image.shapes and labels: {}".format(res))
  53. return res
  54. # this tests that each epoch COULD return different samples than the previous epoch
  55. assert len(set(test_config(replacement=False, num_samples=2, num_repeats=6))) > 2
  56. # the following two tests test replacement works
  57. ordered_res = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
  58. assert sorted(test_config(replacement=False, num_samples=None, num_repeats=4)) == ordered_res
  59. assert sorted(test_config(replacement=True, num_samples=None, num_repeats=4)) != ordered_res
  60. def test_random_sampler_multi_iter(print_res=False):
  61. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  62. map_ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  63. def test_config(replacement, num_samples, num_repeats, validate):
  64. sampler = ds.RandomSampler(replacement=replacement, num_samples=num_samples)
  65. data1 = ds.ManifestDataset(manifest_file, sampler=sampler)
  66. while num_repeats > 0:
  67. res = []
  68. for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
  69. res.append(map_[(item["image"].shape[0], item["label"].item())])
  70. if print_res:
  71. logger.info("image.shapes and labels: {}".format(res))
  72. if validate != sorted(res):
  73. break
  74. num_repeats -= 1
  75. assert num_repeats > 0
  76. test_config(replacement=True, num_samples=5, num_repeats=5, validate=[0, 1, 2, 3, 4, 5])
  77. def test_sampler_py_api():
  78. sampler = ds.SequentialSampler().create()
  79. sampler.set_num_rows(128)
  80. sampler.set_num_samples(64)
  81. sampler.initialize()
  82. sampler.get_indices()
  83. sampler = ds.RandomSampler().create()
  84. sampler.set_num_rows(128)
  85. sampler.set_num_samples(64)
  86. sampler.initialize()
  87. sampler.get_indices()
  88. sampler = ds.DistributedSampler(8, 4).create()
  89. sampler.set_num_rows(128)
  90. sampler.set_num_samples(64)
  91. sampler.initialize()
  92. sampler.get_indices()
  93. def test_python_sampler():
  94. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  95. map_ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  96. class Sp1(ds.Sampler):
  97. def __iter__(self):
  98. return iter([i for i in range(self.dataset_size)])
  99. class Sp2(ds.Sampler):
  100. def __init__(self, num_samples=None):
  101. super(Sp2, self).__init__(num_samples)
  102. # at this stage, self.dataset_size and self.num_samples are not yet known
  103. self.cnt = 0
  104. def __iter__(self): # first epoch, all 0, second epoch all 1, third all 2 etc.. ...
  105. return iter([self.cnt for i in range(self.num_samples)])
  106. def reset(self):
  107. self.cnt = (self.cnt + 1) % self.dataset_size
  108. def test_config(num_repeats, sampler):
  109. data1 = ds.ManifestDataset(manifest_file, sampler=sampler)
  110. if num_repeats is not None:
  111. data1 = data1.repeat(num_repeats)
  112. res = []
  113. for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
  114. logger.info("item[image].shape[0]: {}, item[label].item(): {}"
  115. .format(item["image"].shape[0], item["label"].item()))
  116. res.append(map_[(item["image"].shape[0], item["label"].item())])
  117. # print(res)
  118. return res
  119. def test_generator():
  120. class MySampler(ds.Sampler):
  121. def __iter__(self):
  122. for i in range(99, -1, -1):
  123. yield i
  124. data1 = ds.GeneratorDataset([(np.array(i),) for i in range(100)], ["data"], sampler=MySampler())
  125. i = 99
  126. for data in data1:
  127. assert data[0].asnumpy() == (np.array(i),)
  128. i = i - 1
  129. assert test_config(2, Sp1(5)) == [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
  130. assert test_config(6, Sp2(2)) == [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 0, 0]
  131. test_generator()
  132. sp1 = Sp1().create()
  133. sp1.set_num_rows(5)
  134. sp1.set_num_samples(5)
  135. sp1.initialize()
  136. assert list(sp1.get_indices()) == [0, 1, 2, 3, 4]
  137. def test_subset_sampler():
  138. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  139. map_ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  140. def test_config(start_index, num_samples):
  141. sampler = ds.SequentialSampler(start_index, num_samples)
  142. d = ds.ManifestDataset(manifest_file, sampler=sampler)
  143. res = []
  144. for item in d.create_dict_iterator(num_epochs=1, output_numpy=True):
  145. res.append(map_[(item["image"].shape[0], item["label"].item())])
  146. return res
  147. assert test_config(0, 1) == [0]
  148. assert test_config(0, 2) == [0, 1]
  149. assert test_config(0, 3) == [0, 1, 2]
  150. assert test_config(0, 4) == [0, 1, 2, 3]
  151. assert test_config(0, 5) == [0, 1, 2, 3, 4]
  152. assert test_config(1, 1) == [1]
  153. assert test_config(2, 3) == [2, 3, 4]
  154. assert test_config(3, 2) == [3, 4]
  155. assert test_config(4, 1) == [4]
  156. def test_sampler_chain():
  157. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  158. map_ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  159. def test_config(num_shards, shard_id):
  160. sampler = ds.DistributedSampler(num_shards, shard_id, shuffle=False, num_samples=5)
  161. child_sampler = ds.SequentialSampler()
  162. sampler.add_child(child_sampler)
  163. data1 = ds.ManifestDataset(manifest_file, sampler=sampler)
  164. res = []
  165. for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
  166. logger.info("item[image].shape[0]: {}, item[label].item(): {}"
  167. .format(item["image"].shape[0], item["label"].item()))
  168. res.append(map_[(item["image"].shape[0], item["label"].item())])
  169. return res
  170. assert test_config(2, 0) == [0, 2, 4]
  171. assert test_config(2, 1) == [1, 3, 0]
  172. assert test_config(5, 0) == [0]
  173. assert test_config(5, 1) == [1]
  174. assert test_config(5, 2) == [2]
  175. assert test_config(5, 3) == [3]
  176. assert test_config(5, 4) == [4]
  177. def test_add_sampler_invalid_input():
  178. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  179. _ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  180. data1 = ds.ManifestDataset(manifest_file)
  181. with pytest.raises(TypeError) as info:
  182. data1.use_sampler(1)
  183. assert "not an instance of a sampler" in str(info.value)
  184. with pytest.raises(TypeError) as info:
  185. data1.use_sampler("sampler")
  186. assert "not an instance of a sampler" in str(info.value)
  187. sampler = ds.SequentialSampler()
  188. with pytest.raises(ValueError) as info:
  189. data2 = ds.ManifestDataset(manifest_file, sampler=sampler, num_samples=20)
  190. assert "Conflicting arguments during sampler assignments" in str(info.value)
  191. def test_distributed_sampler_invalid_offset():
  192. with pytest.raises(ValueError) as info:
  193. sampler = ds.DistributedSampler(num_shards=4, shard_id=0, shuffle=False, num_samples=None, offset=5)
  194. assert "offset should be no more than num_shards" in str(info.value)
  195. if __name__ == '__main__':
  196. test_sequential_sampler(True)
  197. test_random_sampler(True)
  198. test_random_sampler_multi_iter(True)
  199. test_sampler_py_api()
  200. test_python_sampler()
  201. test_subset_sampler()
  202. test_sampler_chain()
  203. test_add_sampler_invalid_input()
  204. test_distributed_sampler_invalid_offset()