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

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. # This 2nd case is the one that exhibits the same behavior as the case above without inheritance
  119. def test_generator_iter_sampler():
  120. class MySampler():
  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. test_generator_iter_sampler()
  133. def test_sequential_sampler2():
  134. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  135. map_ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  136. def test_config(start_index, num_samples):
  137. sampler = ds.SequentialSampler(start_index, num_samples)
  138. d = ds.ManifestDataset(manifest_file, sampler=sampler)
  139. res = []
  140. for item in d.create_dict_iterator(num_epochs=1, output_numpy=True):
  141. res.append(map_[(item["image"].shape[0], item["label"].item())])
  142. return res
  143. assert test_config(0, 1) == [0]
  144. assert test_config(0, 2) == [0, 1]
  145. assert test_config(0, 3) == [0, 1, 2]
  146. assert test_config(0, 4) == [0, 1, 2, 3]
  147. assert test_config(0, 5) == [0, 1, 2, 3, 4]
  148. assert test_config(1, 1) == [1]
  149. assert test_config(2, 3) == [2, 3, 4]
  150. assert test_config(3, 2) == [3, 4]
  151. assert test_config(4, 1) == [4]
  152. assert test_config(4, None) == [4]
  153. def test_subset_sampler():
  154. def test_config(indices, num_samples=None, exception_msg=None):
  155. def pipeline():
  156. sampler = ds.SubsetSampler(indices, num_samples)
  157. data = ds.NumpySlicesDataset(list(range(0, 10)), sampler=sampler)
  158. data2 = ds.NumpySlicesDataset(list(range(0, 10)), sampler=indices, num_samples=num_samples)
  159. dataset_size = data.get_dataset_size()
  160. dataset_size2 = data.get_dataset_size()
  161. res1 = [d[0] for d in data.create_tuple_iterator(num_epochs=1, output_numpy=True)], dataset_size
  162. res2 = [d[0] for d in data2.create_tuple_iterator(num_epochs=1, output_numpy=True)], dataset_size2
  163. return res1, res2
  164. if exception_msg is None:
  165. res, res2 = pipeline()
  166. res, size = res
  167. res2, size2 = res2
  168. if not isinstance(indices, list):
  169. indices = list(indices)
  170. assert indices[:num_samples] == res
  171. assert len(indices[:num_samples]) == size
  172. assert indices[:num_samples] == res2
  173. assert len(indices[:num_samples]) == size2
  174. else:
  175. with pytest.raises(Exception) as error_info:
  176. pipeline()
  177. print(str(error_info.value))
  178. assert exception_msg in str(error_info.value)
  179. test_config([1, 2, 3])
  180. test_config(list(range(10)))
  181. test_config([0])
  182. test_config([9])
  183. test_config(list(range(0, 10, 2)))
  184. test_config(list(range(1, 10, 2)))
  185. test_config(list(range(9, 0, -1)))
  186. test_config(list(range(9, 0, -2)))
  187. test_config(list(range(8, 0, -2)))
  188. test_config([0, 9, 3, 2])
  189. test_config([0, 0, 0, 0])
  190. test_config([0])
  191. test_config([0, 9, 3, 2], num_samples=2)
  192. test_config([0, 9, 3, 2], num_samples=5)
  193. test_config(np.array([1, 2, 3]))
  194. test_config([20], exception_msg="Sample ID (20) is out of bound, expected range [0, 9]")
  195. test_config([10], exception_msg="Sample ID (10) is out of bound, expected range [0, 9]")
  196. test_config([0, 9, 0, 500], exception_msg="Sample ID (500) is out of bound, expected range [0, 9]")
  197. test_config([0, 9, -6, 2], exception_msg="Sample ID (-6) is out of bound, expected range [0, 9]")
  198. # test_config([], exception_msg="Indices list is empty") # temporary until we check with MindDataset
  199. test_config([0, 9, 3, 2], num_samples=-1,
  200. exception_msg="num_samples exceeds the boundary between 0 and 9223372036854775807(INT64_MAX)")
  201. test_config(np.array([[1], [5]]), num_samples=10,
  202. exception_msg="SubsetSampler: Type of indices element must be int, but got list[0]: [1],"
  203. " type: <class 'numpy.ndarray'>.")
  204. def test_sampler_chain():
  205. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  206. map_ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  207. def test_config(num_shards, shard_id):
  208. sampler = ds.DistributedSampler(num_shards, shard_id, shuffle=False, num_samples=5)
  209. child_sampler = ds.SequentialSampler()
  210. sampler.add_child(child_sampler)
  211. data1 = ds.ManifestDataset(manifest_file, sampler=sampler)
  212. res = []
  213. for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
  214. logger.info("item[image].shape[0]: {}, item[label].item(): {}"
  215. .format(item["image"].shape[0], item["label"].item()))
  216. res.append(map_[(item["image"].shape[0], item["label"].item())])
  217. return res
  218. assert test_config(2, 0) == [0, 2, 4]
  219. assert test_config(2, 1) == [1, 3, 0]
  220. assert test_config(5, 0) == [0]
  221. assert test_config(5, 1) == [1]
  222. assert test_config(5, 2) == [2]
  223. assert test_config(5, 3) == [3]
  224. assert test_config(5, 4) == [4]
  225. def test_add_sampler_invalid_input():
  226. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  227. _ = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  228. data1 = ds.ManifestDataset(manifest_file)
  229. with pytest.raises(TypeError) as info:
  230. data1.use_sampler(1)
  231. assert "not an instance of a sampler" in str(info.value)
  232. with pytest.raises(TypeError) as info:
  233. data1.use_sampler("sampler")
  234. assert "not an instance of a sampler" in str(info.value)
  235. sampler = ds.SequentialSampler()
  236. with pytest.raises(RuntimeError) as info:
  237. data2 = ds.ManifestDataset(manifest_file, sampler=sampler, num_samples=20)
  238. assert "sampler and num_samples cannot be specified at the same time" in str(info.value)
  239. def test_distributed_sampler_invalid_offset():
  240. with pytest.raises(RuntimeError) as info:
  241. sampler = ds.DistributedSampler(num_shards=4, shard_id=0, shuffle=False, num_samples=None, offset=5).parse()
  242. assert "DistributedSampler: offset must be no more than num_shards(4)" in str(info.value)
  243. def test_sampler_list():
  244. data1 = ds.ImageFolderDataset("../data/dataset/testPK/data", sampler=[1, 3, 5])
  245. data21 = ds.ImageFolderDataset("../data/dataset/testPK/data", shuffle=False).take(2).skip(1)
  246. data22 = ds.ImageFolderDataset("../data/dataset/testPK/data", shuffle=False).take(4).skip(3)
  247. data23 = ds.ImageFolderDataset("../data/dataset/testPK/data", shuffle=False).take(6).skip(5)
  248. dataset_equal(data1, data21 + data22 + data23, 0)
  249. data3 = ds.ImageFolderDataset("../data/dataset/testPK/data", sampler=1)
  250. dataset_equal(data3, data21, 0)
  251. def bad_pipeline(sampler, msg):
  252. with pytest.raises(Exception) as info:
  253. data1 = ds.ImageFolderDataset("../data/dataset/testPK/data", sampler=sampler)
  254. for _ in data1:
  255. pass
  256. assert msg in str(info.value)
  257. bad_pipeline(sampler=[1.5, 7],
  258. msg="Type of indices element must be int, but got list[0]: 1.5, type: <class 'float'>")
  259. bad_pipeline(sampler=["a", "b"],
  260. msg="Type of indices element must be int, but got list[0]: a, type: <class 'str'>.")
  261. bad_pipeline(sampler="a", msg="Unsupported sampler object of type (<class 'str'>)")
  262. bad_pipeline(sampler="", msg="Unsupported sampler object of type (<class 'str'>)")
  263. bad_pipeline(sampler=np.array([[1, 2]]),
  264. msg="Type of indices element must be int, but got list[0]: [1 2], type: <class 'numpy.ndarray'>.")
  265. if __name__ == '__main__':
  266. test_sequential_sampler(True)
  267. test_random_sampler(True)
  268. test_random_sampler_multi_iter(True)
  269. test_sampler_py_api()
  270. test_python_sampler()
  271. test_sequential_sampler2()
  272. test_subset_sampler()
  273. test_sampler_chain()
  274. test_add_sampler_invalid_input()
  275. test_distributed_sampler_invalid_offset()
  276. test_sampler_list()