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

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. # Copyright 2020-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. import numpy as np
  16. import pytest
  17. import mindspore.dataset as ds
  18. from mindspore import log as logger
  19. from util import dataset_equal
  20. # test5trainimgs.json contains 5 images whose un-decoded shape is [83554, 54214, 65512, 54214, 64631]
  21. # the label of each image is [0,0,0,1,1] each image can be uniquely identified
  22. # via the following lookup table (dict){(83554, 0): 0, (54214, 0): 1, (54214, 1): 2, (65512, 0): 3, (64631, 1): 4}
  23. def test_sequential_sampler(print_res=False):
  24. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  25. map_ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  26. def test_config(num_samples, num_repeats=None):
  27. sampler = ds.SequentialSampler(num_samples=num_samples)
  28. data1 = ds.ManifestDataset(manifest_file, sampler=sampler)
  29. if num_repeats is not None:
  30. data1 = data1.repeat(num_repeats)
  31. res = []
  32. for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
  33. logger.info("item[image].shape[0]: {}, item[label].item(): {}"
  34. .format(item["image"].shape[0], item["label"].item()))
  35. res.append(map_[(item["image"].shape[0], item["label"].item())])
  36. if print_res:
  37. logger.info("image.shapes and labels: {}".format(res))
  38. return res
  39. assert test_config(num_samples=3, num_repeats=None) == [0, 1, 2]
  40. assert test_config(num_samples=None, num_repeats=2) == [0, 1, 2, 3, 4] * 2
  41. assert test_config(num_samples=4, num_repeats=2) == [0, 1, 2, 3] * 2
  42. def test_random_sampler(print_res=False):
  43. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  44. map_ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  45. def test_config(replacement, num_samples, num_repeats):
  46. sampler = ds.RandomSampler(replacement=replacement, num_samples=num_samples)
  47. data1 = ds.ManifestDataset(manifest_file, sampler=sampler)
  48. data1 = data1.repeat(num_repeats)
  49. res = []
  50. for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
  51. res.append(map_[(item["image"].shape[0], item["label"].item())])
  52. if print_res:
  53. logger.info("image.shapes and labels: {}".format(res))
  54. return res
  55. # this tests that each epoch COULD return different samples than the previous epoch
  56. assert len(set(test_config(replacement=False, num_samples=2, num_repeats=6))) > 2
  57. # the following two tests test replacement works
  58. ordered_res = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
  59. assert sorted(test_config(replacement=False, num_samples=None, num_repeats=4)) == ordered_res
  60. assert sorted(test_config(replacement=True, num_samples=None, num_repeats=4)) != ordered_res
  61. def test_random_sampler_multi_iter(print_res=False):
  62. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  63. map_ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  64. def test_config(replacement, num_samples, num_repeats, validate):
  65. sampler = ds.RandomSampler(replacement=replacement, num_samples=num_samples)
  66. data1 = ds.ManifestDataset(manifest_file, sampler=sampler)
  67. while num_repeats > 0:
  68. res = []
  69. for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
  70. res.append(map_[(item["image"].shape[0], item["label"].item())])
  71. if print_res:
  72. logger.info("image.shapes and labels: {}".format(res))
  73. if validate != sorted(res):
  74. break
  75. num_repeats -= 1
  76. assert num_repeats > 0
  77. test_config(replacement=True, num_samples=5, num_repeats=5, validate=[0, 1, 2, 3, 4, 5])
  78. def test_sampler_py_api():
  79. sampler = ds.SequentialSampler().parse()
  80. sampler1 = ds.RandomSampler().parse()
  81. sampler1.add_child(sampler)
  82. def test_python_sampler():
  83. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  84. map_ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  85. class Sp1(ds.Sampler):
  86. def __iter__(self):
  87. return iter([i for i in range(self.dataset_size)])
  88. class Sp2(ds.Sampler):
  89. def __init__(self, num_samples=None):
  90. super(Sp2, self).__init__(num_samples)
  91. # at this stage, self.dataset_size and self.num_samples are not yet known
  92. self.cnt = 0
  93. def __iter__(self): # first epoch, all 0, second epoch all 1, third all 2 etc.. ...
  94. return iter([self.cnt for i in range(self.num_samples)])
  95. def reset(self):
  96. self.cnt = (self.cnt + 1) % self.dataset_size
  97. def test_config(num_repeats, sampler):
  98. data1 = ds.ManifestDataset(manifest_file, sampler=sampler)
  99. if num_repeats is not None:
  100. data1 = data1.repeat(num_repeats)
  101. res = []
  102. for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
  103. logger.info("item[image].shape[0]: {}, item[label].item(): {}"
  104. .format(item["image"].shape[0], item["label"].item()))
  105. res.append(map_[(item["image"].shape[0], item["label"].item())])
  106. # print(res)
  107. return res
  108. def test_generator():
  109. class MySampler(ds.Sampler):
  110. def __iter__(self):
  111. for i in range(99, -1, -1):
  112. yield i
  113. data1 = ds.GeneratorDataset([(np.array(i),) for i in range(100)], ["data"], sampler=MySampler())
  114. i = 99
  115. for data in data1:
  116. assert data[0].asnumpy() == (np.array(i),)
  117. i = i - 1
  118. assert test_config(2, Sp1(5)) == [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
  119. assert test_config(6, Sp2(2)) == [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 0, 0]
  120. test_generator()
  121. def test_sequential_sampler2():
  122. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  123. map_ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  124. def test_config(start_index, num_samples):
  125. sampler = ds.SequentialSampler(start_index, num_samples)
  126. d = ds.ManifestDataset(manifest_file, sampler=sampler)
  127. res = []
  128. for item in d.create_dict_iterator(num_epochs=1, output_numpy=True):
  129. res.append(map_[(item["image"].shape[0], item["label"].item())])
  130. return res
  131. assert test_config(0, 1) == [0]
  132. assert test_config(0, 2) == [0, 1]
  133. assert test_config(0, 3) == [0, 1, 2]
  134. assert test_config(0, 4) == [0, 1, 2, 3]
  135. assert test_config(0, 5) == [0, 1, 2, 3, 4]
  136. assert test_config(1, 1) == [1]
  137. assert test_config(2, 3) == [2, 3, 4]
  138. assert test_config(3, 2) == [3, 4]
  139. assert test_config(4, 1) == [4]
  140. assert test_config(4, None) == [4]
  141. def test_subset_sampler():
  142. def test_config(indices, num_samples=None, exception_msg=None):
  143. def pipeline():
  144. sampler = ds.SubsetSampler(indices, num_samples)
  145. data = ds.NumpySlicesDataset(list(range(0, 10)), sampler=sampler)
  146. dataset_size = data.get_dataset_size()
  147. return [d[0] for d in data.create_tuple_iterator(num_epochs=1, output_numpy=True)], dataset_size
  148. if exception_msg is None:
  149. res, size = pipeline()
  150. assert indices[:num_samples] == res
  151. assert len(indices[:num_samples]) == size
  152. else:
  153. with pytest.raises(Exception) as error_info:
  154. pipeline()
  155. print(str(error_info.value))
  156. assert exception_msg in str(error_info.value)
  157. test_config([1, 2, 3])
  158. test_config(list(range(10)))
  159. test_config([0])
  160. test_config([9])
  161. test_config(list(range(0, 10, 2)))
  162. test_config(list(range(1, 10, 2)))
  163. test_config(list(range(9, 0, -1)))
  164. test_config(list(range(9, 0, -2)))
  165. test_config(list(range(8, 0, -2)))
  166. test_config([0, 9, 3, 2])
  167. test_config([0, 0, 0, 0])
  168. test_config([0])
  169. test_config([0, 9, 3, 2], num_samples=2)
  170. test_config([0, 9, 3, 2], num_samples=5)
  171. test_config([20], exception_msg="Sample ID (20) is out of bound, expected range [0, 9]")
  172. test_config([10], exception_msg="Sample ID (10) is out of bound, expected range [0, 9]")
  173. test_config([0, 9, 0, 500], exception_msg="Sample ID (500) is out of bound, expected range [0, 9]")
  174. test_config([0, 9, -6, 2], exception_msg="Sample ID (-6) is out of bound, expected range [0, 9]")
  175. # test_config([], exception_msg="Indices list is empty") # temporary until we check with MindDataset
  176. test_config([0, 9, 3, 2], num_samples=-1,
  177. exception_msg="num_samples exceeds the boundary between 0 and 9223372036854775807(INT64_MAX)")
  178. def test_sampler_chain():
  179. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  180. map_ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  181. def test_config(num_shards, shard_id):
  182. sampler = ds.DistributedSampler(num_shards, shard_id, shuffle=False, num_samples=5)
  183. child_sampler = ds.SequentialSampler()
  184. sampler.add_child(child_sampler)
  185. data1 = ds.ManifestDataset(manifest_file, sampler=sampler)
  186. res = []
  187. for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
  188. logger.info("item[image].shape[0]: {}, item[label].item(): {}"
  189. .format(item["image"].shape[0], item["label"].item()))
  190. res.append(map_[(item["image"].shape[0], item["label"].item())])
  191. return res
  192. assert test_config(2, 0) == [0, 2, 4]
  193. assert test_config(2, 1) == [1, 3, 0]
  194. assert test_config(5, 0) == [0]
  195. assert test_config(5, 1) == [1]
  196. assert test_config(5, 2) == [2]
  197. assert test_config(5, 3) == [3]
  198. assert test_config(5, 4) == [4]
  199. def test_add_sampler_invalid_input():
  200. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  201. _ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  202. data1 = ds.ManifestDataset(manifest_file)
  203. with pytest.raises(TypeError) as info:
  204. data1.use_sampler(1)
  205. assert "not an instance of a sampler" in str(info.value)
  206. with pytest.raises(TypeError) as info:
  207. data1.use_sampler("sampler")
  208. assert "not an instance of a sampler" in str(info.value)
  209. sampler = ds.SequentialSampler()
  210. with pytest.raises(RuntimeError) as info:
  211. data2 = ds.ManifestDataset(manifest_file, sampler=sampler, num_samples=20)
  212. assert "sampler and num_samples cannot be specified at the same time" in str(info.value)
  213. def test_distributed_sampler_invalid_offset():
  214. with pytest.raises(RuntimeError) as info:
  215. sampler = ds.DistributedSampler(num_shards=4, shard_id=0, shuffle=False, num_samples=None, offset=5).parse()
  216. assert "DistributedSampler: offset must be no more than num_shards(4)" in str(info.value)
  217. def test_sampler_list():
  218. data1 = ds.ImageFolderDataset("../data/dataset/testPK/data", sampler=[1, 3, 5])
  219. data21 = ds.ImageFolderDataset("../data/dataset/testPK/data", shuffle=False).take(2).skip(1)
  220. data22 = ds.ImageFolderDataset("../data/dataset/testPK/data", shuffle=False).take(4).skip(3)
  221. data23 = ds.ImageFolderDataset("../data/dataset/testPK/data", shuffle=False).take(6).skip(5)
  222. dataset_equal(data1, data21 + data22 + data23, 0)
  223. data3 = ds.ImageFolderDataset("../data/dataset/testPK/data", sampler=1)
  224. dataset_equal(data3, data21, 0)
  225. def bad_pipeline(sampler, msg):
  226. with pytest.raises(Exception) as info:
  227. data1 = ds.ImageFolderDataset("../data/dataset/testPK/data", sampler=sampler)
  228. for _ in data1:
  229. pass
  230. assert msg in str(info.value)
  231. bad_pipeline(sampler=[1.5, 7],
  232. msg="Type of indices element must be int, but got list[0]: 1.5, type: <class 'float'>")
  233. bad_pipeline(sampler=["a", "b"],
  234. msg="Type of indices element must be int, but got list[0]: a, type: <class 'str'>.")
  235. bad_pipeline(sampler="a", msg="Unsupported sampler object of type (<class 'str'>)")
  236. bad_pipeline(sampler="", msg="Unsupported sampler object of type (<class 'str'>)")
  237. bad_pipeline(sampler=np.array([1, 2]),
  238. msg="Type of indices element must be int, but got list[0]: 1, type: <class 'numpy.int64'>.")
  239. if __name__ == '__main__':
  240. test_sequential_sampler(True)
  241. test_random_sampler(True)
  242. test_random_sampler_multi_iter(True)
  243. test_sampler_py_api()
  244. test_python_sampler()
  245. test_sequential_sampler2()
  246. test_subset_sampler()
  247. test_sampler_chain()
  248. test_add_sampler_invalid_input()
  249. test_distributed_sampler_invalid_offset()
  250. test_sampler_list()