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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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 mindspore.dataset as ds
  16. from mindspore import log as logger
  17. import numpy as np
  18. # test5trainimgs.json contains 5 images whose un-decoded shape is [83554, 54214, 65512, 54214, 64631]
  19. # the label of each image is [0,0,0,1,1] each image can be uniquely identified
  20. # via the following lookup table (dict){(83554, 0): 0, (54214, 0): 1, (54214, 1): 2, (65512, 0): 3, (64631, 1): 4}
  21. def test_sequential_sampler(print_res=False):
  22. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  23. map = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  24. def test_config(num_samples, num_repeats=None):
  25. sampler = ds.SequentialSampler()
  26. data1 = ds.ManifestDataset(manifest_file, num_samples=num_samples, sampler=sampler)
  27. if num_repeats is not None:
  28. data1 = data1.repeat(num_repeats)
  29. res = []
  30. for item in data1.create_dict_iterator():
  31. logger.info("item[image].shape[0]: {}, item[label].item(): {}"
  32. .format(item["image"].shape[0], item["label"].item()))
  33. res.append(map[(item["image"].shape[0], item["label"].item())])
  34. if print_res:
  35. logger.info("image.shapes and labels: {}".format(res))
  36. return res
  37. assert test_config(num_samples=3, num_repeats=None) == [0, 1, 2]
  38. assert test_config(num_samples=None, num_repeats=2) == [0, 1, 2, 3, 4] * 2
  39. assert test_config(num_samples=4, num_repeats=2) == [0, 1, 2, 3] * 2
  40. def test_random_sampler(print_res=False):
  41. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  42. map = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  43. def test_config(replacement, num_samples, num_repeats):
  44. sampler = ds.RandomSampler(replacement=replacement, num_samples=num_samples)
  45. data1 = ds.ManifestDataset(manifest_file, sampler=sampler)
  46. data1 = data1.repeat(num_repeats)
  47. res = []
  48. for item in data1.create_dict_iterator():
  49. res.append(map[(item["image"].shape[0], item["label"].item())])
  50. if print_res:
  51. logger.info("image.shapes and labels: {}".format(res))
  52. return res
  53. # this tests that each epoch COULD return different samples than the previous epoch
  54. assert len(set(test_config(replacement=False, num_samples=2, num_repeats=6))) > 2
  55. # the following two tests test replacement works
  56. ordered_res = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
  57. assert sorted(test_config(replacement=False, num_samples=None, num_repeats=4)) == ordered_res
  58. assert sorted(test_config(replacement=True, num_samples=None, num_repeats=4)) != ordered_res
  59. def test_random_sampler_multi_iter(print_res=False):
  60. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  61. map = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  62. def test_config(replacement, num_samples, num_repeats, validate):
  63. sampler = ds.RandomSampler(replacement=replacement, num_samples=num_samples)
  64. data1 = ds.ManifestDataset(manifest_file, sampler=sampler)
  65. while num_repeats > 0:
  66. res = []
  67. for item in data1.create_dict_iterator():
  68. res.append(map[(item["image"].shape[0], item["label"].item())])
  69. if print_res:
  70. logger.info("image.shapes and labels: {}".format(res))
  71. if validate != sorted(res):
  72. break
  73. num_repeats -= 1
  74. assert num_repeats > 0
  75. test_config(replacement=True, num_samples=5, num_repeats=5, validate=[0, 1, 2, 3, 4, 5])
  76. def test_sampler_py_api():
  77. sampler = ds.SequentialSampler().create()
  78. sampler.set_num_rows(128)
  79. sampler.set_num_samples(64)
  80. sampler.initialize()
  81. sampler.get_indices()
  82. sampler = ds.RandomSampler().create()
  83. sampler.set_num_rows(128)
  84. sampler.set_num_samples(64)
  85. sampler.initialize()
  86. sampler.get_indices()
  87. sampler = ds.DistributedSampler(8, 4).create()
  88. sampler.set_num_rows(128)
  89. sampler.set_num_samples(64)
  90. sampler.initialize()
  91. sampler.get_indices()
  92. def test_python_sampler():
  93. manifest_file = "../data/dataset/testManifestData/test5trainimgs.json"
  94. map = {(172876, 0): 0, (54214, 0): 1, (54214, 1): 2, (173673, 0): 3, (64631, 1): 4}
  95. class Sp1(ds.Sampler):
  96. def __iter__(self):
  97. return iter([i for i in range(self.dataset_size)])
  98. class Sp2(ds.Sampler):
  99. def __init__(self):
  100. super(Sp2, self).__init__()
  101. # at this stage, self.dataset_size and self.num_samples are not yet known
  102. self.cnt = 0
  103. def __iter__(self): # first epoch, all 0, second epoch all 1, third all 2 etc.. ...
  104. return iter([self.cnt for i in range(self.num_samples)])
  105. def reset(self):
  106. self.cnt = (self.cnt + 1) % self.dataset_size
  107. def test_config(num_samples, num_repeats, sampler):
  108. data1 = ds.ManifestDataset(manifest_file, num_samples=num_samples, sampler=sampler)
  109. if num_repeats is not None:
  110. data1 = data1.repeat(num_repeats)
  111. res = []
  112. for item in data1.create_dict_iterator():
  113. logger.info("item[image].shape[0]: {}, item[label].item(): {}"
  114. .format(item["image"].shape[0], item["label"].item()))
  115. res.append(map[(item["image"].shape[0], item["label"].item())])
  116. # print(res)
  117. return res
  118. def test_generator():
  119. class MySampler(ds.Sampler):
  120. def __iter__(self):
  121. for i in range(99, -1, -1):
  122. yield i
  123. data1 = ds.GeneratorDataset([(np.array(i),) for i in range(100)], ["data"], sampler = MySampler())
  124. i = 99
  125. for data in data1:
  126. assert data[0] == (np.array(i),)
  127. i = i - 1
  128. assert test_config(5, 2, Sp1()) == [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
  129. assert test_config(2, 6, Sp2()) == [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 0, 0]
  130. test_generator()
  131. sp1 = Sp1().create()
  132. sp1.set_num_rows(5)
  133. sp1.set_num_samples(5)
  134. sp1.initialize()
  135. assert list(sp1.get_indices()) == [0, 1, 2, 3, 4]
  136. if __name__ == '__main__':
  137. test_sequential_sampler(True)
  138. test_random_sampler(True)
  139. test_random_sampler_multi_iter(True)
  140. test_sampler_py_api()
  141. test_python_sampler()