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_datasets_gtzan.py 8.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. # Copyright 2022 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 foNtest_resr the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """
  16. Test Gtzan dataset operators.
  17. """
  18. import numpy as np
  19. import pytest
  20. import mindspore.dataset as ds
  21. from mindspore import log as logger
  22. DATA_DIR = "../data/dataset/testGTZANData"
  23. def test_gtzan_basic():
  24. """
  25. Feature: GTZANDataset
  26. Description: test basic usage of GTZAN
  27. Expectation: the dataset is as expected
  28. """
  29. logger.info("Test GTZANDataset Op")
  30. # case 1: test loading whole dataset.
  31. data1 = ds.GTZANDataset(DATA_DIR)
  32. num_iter1 = 0
  33. for _ in data1.create_dict_iterator(output_numpy=True, num_epochs=1):
  34. num_iter1 += 1
  35. assert num_iter1 == 3
  36. # case 2: test num_samples.
  37. data2 = ds.GTZANDataset(DATA_DIR, num_samples=2)
  38. num_iter2 = 0
  39. for _ in data2.create_dict_iterator(output_numpy=True, num_epochs=1):
  40. num_iter2 += 1
  41. assert num_iter2 == 2
  42. # case 3: test repeat.
  43. data3 = ds.GTZANDataset(DATA_DIR, num_samples=2)
  44. data3 = data3.repeat(5)
  45. num_iter3 = 0
  46. for _ in data3.create_dict_iterator(output_numpy=True, num_epochs=1):
  47. num_iter3 += 1
  48. assert num_iter3 == 10
  49. # case 4: test batch with drop_remainder=False.
  50. data4 = ds.GTZANDataset(DATA_DIR, num_samples=3)
  51. assert data4.get_dataset_size() == 3
  52. assert data4.get_batch_size() == 1
  53. data4 = data4.batch(batch_size=2) # drop_remainder is default to be False.
  54. assert data4.get_dataset_size() == 2
  55. assert data4.get_batch_size() == 2
  56. # case 5: test batch with drop_remainder=True.
  57. data5 = ds.GTZANDataset(DATA_DIR, num_samples=3)
  58. assert data5.get_dataset_size() == 3
  59. assert data5.get_batch_size() == 1
  60. # the rest of incomplete batch will be dropped.
  61. data5 = data5.batch(batch_size=2, drop_remainder=True)
  62. assert data5.get_dataset_size() == 1
  63. assert data5.get_batch_size() == 2
  64. def test_gtzan_distribute_sampler():
  65. """
  66. Feature: GTZANDataset
  67. Description: test GTZAN dataset with DistributedSampler
  68. Expectation: the results are as expected
  69. """
  70. logger.info("Test GTZAN with DistributedSampler")
  71. label_list1, label_list2 = [], []
  72. num_shards = 3
  73. shard_id = 0
  74. data1 = ds.GTZANDataset(DATA_DIR, usage="all", num_shards=num_shards, shard_id=shard_id)
  75. count = 0
  76. for item1 in data1.create_dict_iterator(output_numpy=True, num_epochs=1):
  77. label_list1.append(item1["label"])
  78. count = count + 1
  79. assert count == 1
  80. num_shards = 3
  81. shard_id = 0
  82. sampler = ds.DistributedSampler(num_shards, shard_id)
  83. data2 = ds.GTZANDataset(DATA_DIR, usage="all", sampler=sampler)
  84. count = 0
  85. for item2 in data2.create_dict_iterator(output_numpy=True, num_epochs=1):
  86. label_list2.append(item2["label"])
  87. count = count + 1
  88. np.testing.assert_array_equal(label_list1, label_list2)
  89. assert count == 1
  90. def test_gtzan_exception():
  91. """
  92. Feature: GTZANDataset
  93. Description: test error cases for GTZANDataset
  94. Expectation: the results are as expected
  95. """
  96. logger.info("Test error cases for GTZANDataset")
  97. error_msg_1 = "sampler and shuffle cannot be specified at the same time"
  98. with pytest.raises(RuntimeError, match=error_msg_1):
  99. ds.GTZANDataset(DATA_DIR, shuffle=False, sampler=ds.PKSampler(3))
  100. error_msg_2 = "sampler and sharding cannot be specified at the same time"
  101. with pytest.raises(RuntimeError, match=error_msg_2):
  102. ds.GTZANDataset(DATA_DIR, sampler=ds.PKSampler(3),
  103. num_shards=2, shard_id=0)
  104. error_msg_3 = "num_shards is specified and currently requires shard_id as well"
  105. with pytest.raises(RuntimeError, match=error_msg_3):
  106. ds.GTZANDataset(DATA_DIR, num_shards=10)
  107. error_msg_4 = "shard_id is specified but num_shards is not"
  108. with pytest.raises(RuntimeError, match=error_msg_4):
  109. ds.GTZANDataset(DATA_DIR, shard_id=0)
  110. error_msg_5 = "Input shard_id is not within the required interval"
  111. with pytest.raises(ValueError, match=error_msg_5):
  112. ds.GTZANDataset(DATA_DIR, num_shards=5, shard_id=-1)
  113. with pytest.raises(ValueError, match=error_msg_5):
  114. ds.GTZANDataset(DATA_DIR, num_shards=5, shard_id=5)
  115. with pytest.raises(ValueError, match=error_msg_5):
  116. ds.GTZANDataset(DATA_DIR, num_shards=2, shard_id=5)
  117. error_msg_6 = "num_parallel_workers exceeds"
  118. with pytest.raises(ValueError, match=error_msg_6):
  119. ds.GTZANDataset(DATA_DIR, shuffle=False, num_parallel_workers=0)
  120. with pytest.raises(ValueError, match=error_msg_6):
  121. ds.GTZANDataset(DATA_DIR, shuffle=False, num_parallel_workers=256)
  122. with pytest.raises(ValueError, match=error_msg_6):
  123. ds.GTZANDataset(DATA_DIR, shuffle=False, num_parallel_workers=-2)
  124. error_msg_7 = "Argument shard_id"
  125. with pytest.raises(TypeError, match=error_msg_7):
  126. ds.GTZANDataset(DATA_DIR, num_shards=2, shard_id="0")
  127. def exception_func(item):
  128. raise Exception("Error occur!")
  129. error_msg_8 = "The corresponding data files"
  130. with pytest.raises(RuntimeError, match=error_msg_8):
  131. data = ds.GTZANDataset(DATA_DIR)
  132. data = data.map(operations=exception_func, input_columns=["waveform"], num_parallel_workers=1)
  133. for _ in data.create_dict_iterator(output_numpy=True, num_epochs=1):
  134. pass
  135. def test_gtzan_sequential_sampler():
  136. """
  137. Feature: GTZANDataset
  138. Description: test GTZANDataset with SequentialSampler
  139. Expectation: the results are as expected
  140. """
  141. logger.info("Test GTZANDataset Op with SequentialSampler")
  142. num_samples = 2
  143. sampler = ds.SequentialSampler(num_samples=num_samples)
  144. data1 = ds.GTZANDataset(DATA_DIR, sampler=sampler)
  145. data2 = ds.GTZANDataset(DATA_DIR, shuffle=False, num_samples=num_samples)
  146. label_list1, label_list2 = [], []
  147. num_iter = 0
  148. for item1, item2 in zip(data1.create_dict_iterator(output_numpy=True, num_epochs=1),
  149. data2.create_dict_iterator(output_numpy=True, num_epochs=1)):
  150. label_list1.append(item1["label"])
  151. label_list2.append(item2["label"])
  152. num_iter += 1
  153. np.testing.assert_array_equal(label_list1, label_list2)
  154. assert num_iter == num_samples
  155. def test_gtzan_usage():
  156. """
  157. Feature: GTZANDataset
  158. Description: test GTZANDataset usage
  159. Expectation: the results are as expected
  160. """
  161. logger.info("Test GTZANDataset usage")
  162. def test_config(usage, gtzan_path=None):
  163. gtzan_path = DATA_DIR if gtzan_path is None else gtzan_path
  164. try:
  165. data = ds.GTZANDataset(gtzan_path, usage=usage, shuffle=False)
  166. num_rows = 0
  167. for _ in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  168. num_rows += 1
  169. except (ValueError, TypeError, RuntimeError) as e:
  170. return str(e)
  171. return num_rows
  172. assert test_config("valid") == 3
  173. assert test_config("all") == 3
  174. assert "usage is not within the valid set of ['train', 'valid', 'test', 'all']" in test_config("invalid")
  175. assert "Argument usage with value ['list'] is not of type [<class 'str'>]" in test_config(["list"])
  176. # change this directory to the folder that contains all gtzan files.
  177. all_files_path = None
  178. # the following tests on the entire datasets.
  179. if all_files_path is not None:
  180. assert test_config("train", all_files_path) == 3
  181. assert test_config("valid", all_files_path) == 3
  182. assert ds.GTZANDataset(all_files_path, usage="train").get_dataset_size() == 3
  183. assert ds.GTZANDataset(all_files_path, usage="valid").get_dataset_size() == 3
  184. if __name__ == '__main__':
  185. test_gtzan_basic()
  186. test_gtzan_distribute_sampler()
  187. test_gtzan_exception()
  188. test_gtzan_sequential_sampler()
  189. test_gtzan_usage()