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_dataset_numpy_slices.py 7.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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 numpy as np
  16. import pytest
  17. import mindspore.dataset as de
  18. from mindspore import log as logger
  19. import mindspore.dataset.transforms.vision.c_transforms as vision
  20. import pandas as pd
  21. def test_numpy_slices_list_1():
  22. logger.info("Test Slicing a 1D list.")
  23. np_data = [1, 2, 3]
  24. ds = de.NumpySlicesDataset(np_data, shuffle=False)
  25. for i, data in enumerate(ds):
  26. assert data[0] == np_data[i]
  27. def test_numpy_slices_list_2():
  28. logger.info("Test Slicing a 2D list into 1D list.")
  29. np_data = [[1, 2], [3, 4]]
  30. ds = de.NumpySlicesDataset(np_data, column_names=["col1"], shuffle=False)
  31. for i, data in enumerate(ds):
  32. assert np.equal(data[0], np_data[i]).all()
  33. def test_numpy_slices_list_3():
  34. logger.info("Test Slicing list in the first dimension.")
  35. np_data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
  36. ds = de.NumpySlicesDataset(np_data, column_names=["col1"], shuffle=False)
  37. for i, data in enumerate(ds):
  38. assert np.equal(data[0], np_data[i]).all()
  39. def test_numpy_slices_list_append():
  40. logger.info("Test reading data of image list.")
  41. DATA_DIR = ["../data/dataset/test_tf_file_3_images/train-0000-of-0001.data"]
  42. resize_height, resize_width = 2, 2
  43. data1 = de.TFRecordDataset(DATA_DIR)
  44. resize_op = vision.Resize((resize_height, resize_width))
  45. data1 = data1.map(input_columns=["image"], operations=[vision.Decode(True), resize_op])
  46. res = []
  47. for data in data1.create_dict_iterator():
  48. res.append(data["image"])
  49. ds = de.NumpySlicesDataset(res, column_names=["col1"], shuffle=False)
  50. for i, data in enumerate(ds):
  51. assert np.equal(data, res[i]).all()
  52. def test_numpy_slices_dict_1():
  53. logger.info("Test Dictionary structure data.")
  54. np_data = {"a": [1, 2], "b": [3, 4]}
  55. ds = de.NumpySlicesDataset(np_data, shuffle=False)
  56. res = [[1, 3], [2, 4]]
  57. for i, data in enumerate(ds):
  58. assert data[0] == res[i][0]
  59. assert data[1] == res[i][1]
  60. def test_numpy_slices_tuple_1():
  61. logger.info("Test slicing a list of tuple.")
  62. np_data = [([1, 2], [3, 4]), ([11, 12], [13, 14]), ([21, 22], [23, 24])]
  63. ds = de.NumpySlicesDataset(np_data, shuffle=False)
  64. for i, data in enumerate(ds):
  65. assert np.equal(data, np_data[i]).all()
  66. assert sum([1 for _ in ds]) == 3
  67. def test_numpy_slices_tuple_2():
  68. logger.info("Test slicing a tuple of list.")
  69. np_data = ([1, 2], [3, 4], [5, 6])
  70. expected = [[1, 3, 5], [2, 4, 6]]
  71. ds = de.NumpySlicesDataset(np_data, shuffle=False)
  72. for i, data in enumerate(ds):
  73. assert np.equal(data, expected[i]).all()
  74. assert sum([1 for _ in ds]) == 2
  75. def test_numpy_slices_tuple_3():
  76. logger.info("Test reading different dimension of tuple data.")
  77. features, labels = np.random.sample((5, 2)), np.random.sample((5, 1))
  78. data = (features, labels)
  79. ds = de.NumpySlicesDataset(data, column_names=["col1", "col2"], shuffle=False)
  80. for i, data in enumerate(ds):
  81. assert np.equal(data[0], features[i]).all()
  82. assert data[1] == labels[i]
  83. def test_numpy_slices_csv_value():
  84. logger.info("Test loading value of csv file.")
  85. csv_file = "../data/dataset/testNumpySlicesDataset/heart.csv"
  86. df = pd.read_csv(csv_file)
  87. target = df.pop("target")
  88. df.pop("state")
  89. np_data = (df.values, target.values)
  90. ds = de.NumpySlicesDataset(np_data, column_names=["col1", "col2"], shuffle=False)
  91. for i, data in enumerate(ds):
  92. assert np.equal(np_data[0][i], data[0]).all()
  93. assert np.equal(np_data[1][i], data[1]).all()
  94. def test_numpy_slices_csv_dict():
  95. logger.info("Test loading csv file as dict.")
  96. csv_file = "../data/dataset/testNumpySlicesDataset/heart.csv"
  97. df = pd.read_csv(csv_file)
  98. df.pop("state")
  99. res = df.values
  100. ds = de.NumpySlicesDataset(dict(df), shuffle=False)
  101. for i, data in enumerate(ds):
  102. assert np.equal(data, res[i]).all()
  103. def test_numpy_slices_num_samplers():
  104. logger.info("Test num_samplers.")
  105. np_data = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14], [15, 16]]
  106. ds = de.NumpySlicesDataset(np_data, shuffle=False, num_samples=2)
  107. for i, data in enumerate(ds):
  108. assert np.equal(data[0], np_data[i]).all()
  109. assert sum([1 for _ in ds]) == 2
  110. def test_numpy_slices_distributed_sampler():
  111. logger.info("Test distributed sampler.")
  112. np_data = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14], [15, 16]]
  113. ds = de.NumpySlicesDataset(np_data, shuffle=False, shard_id=0, num_shards=4)
  114. for i, data in enumerate(ds):
  115. assert np.equal(data[0], np_data[i * 4]).all()
  116. assert sum([1 for _ in ds]) == 2
  117. def test_numpy_slices_sequential_sampler():
  118. logger.info("Test numpy_slices_dataset with SequentialSampler and repeat.")
  119. np_data = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14], [15, 16]]
  120. ds = de.NumpySlicesDataset(np_data, sampler=de.SequentialSampler()).repeat(2)
  121. for i, data in enumerate(ds):
  122. assert np.equal(data[0], np_data[i % 8]).all()
  123. def test_numpy_slices_invalid_column_names_type():
  124. logger.info("Test incorrect column_names input")
  125. np_data = [1, 2, 3]
  126. with pytest.raises(TypeError) as err:
  127. de.NumpySlicesDataset(np_data, column_names=[1], shuffle=False)
  128. assert "Argument column_names[0] with value 1 is not of type (<class 'str'>,)." in str(err.value)
  129. def test_numpy_slices_invalid_column_names_string():
  130. logger.info("Test incorrect column_names input")
  131. np_data = [1, 2, 3]
  132. with pytest.raises(ValueError) as err:
  133. de.NumpySlicesDataset(np_data, column_names=[""], shuffle=False)
  134. assert "column_names[0] should not be empty" in str(err.value)
  135. def test_numpy_slices_invalid_empty_column_names():
  136. logger.info("Test incorrect column_names input")
  137. np_data = [1, 2, 3]
  138. with pytest.raises(ValueError) as err:
  139. de.NumpySlicesDataset(np_data, column_names=[], shuffle=False)
  140. assert "column_names should not be empty" in str(err.value)
  141. if __name__ == "__main__":
  142. test_numpy_slices_list_1()
  143. test_numpy_slices_list_2()
  144. test_numpy_slices_list_3()
  145. test_numpy_slices_list_append()
  146. test_numpy_slices_dict_1()
  147. test_numpy_slices_tuple_1()
  148. test_numpy_slices_tuple_2()
  149. test_numpy_slices_tuple_3()
  150. test_numpy_slices_csv_value()
  151. test_numpy_slices_csv_dict()
  152. test_numpy_slices_num_samplers()
  153. test_numpy_slices_distributed_sampler()
  154. test_numpy_slices_sequential_sampler()
  155. test_numpy_slices_invalid_column_names_type()
  156. test_numpy_slices_invalid_column_names_string()
  157. test_numpy_slices_invalid_empty_column_names()