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