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_iterator.py 6.0 kB

5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. # Copyright 2019 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.common.dtype as mstype
  18. from mindspore.common.tensor import Tensor
  19. import mindspore.dataset as ds
  20. from mindspore.dataset.engine.iterators import ITERATORS_LIST, _cleanup
  21. DATA_DIR = ["../data/dataset/testTFTestAllTypes/test.data"]
  22. SCHEMA_DIR = "../data/dataset/testTFTestAllTypes/datasetSchema.json"
  23. COLUMNS = ["col_1d", "col_2d", "col_3d", "col_binary", "col_float",
  24. "col_sint16", "col_sint32", "col_sint64"]
  25. def check(project_columns):
  26. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=COLUMNS, shuffle=False)
  27. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=project_columns, shuffle=False)
  28. for data_actual, data_expected in zip(data1.create_tuple_iterator(project_columns, num_epochs=1, output_numpy=True),
  29. data2.create_tuple_iterator(num_epochs=1, output_numpy=True)):
  30. assert len(data_actual) == len(data_expected)
  31. assert all([np.array_equal(d1, d2) for d1, d2 in zip(data_actual, data_expected)])
  32. def test_iterator_create_tuple_numpy():
  33. """
  34. Test creating tuple iterator with output NumPy
  35. """
  36. check(COLUMNS)
  37. check(COLUMNS[0:1])
  38. check(COLUMNS[0:2])
  39. check(COLUMNS[0:7])
  40. check(COLUMNS[7:8])
  41. check(COLUMNS[0:2:8])
  42. def test_iterator_create_dict_mstensor():
  43. """
  44. Test creating dict iterator with output MSTensor
  45. """
  46. def generator():
  47. for i in range(64):
  48. yield (np.array([i], dtype=np.float32),)
  49. # apply dataset operations
  50. data1 = ds.GeneratorDataset(generator, ["data"])
  51. i = 0
  52. for item in data1.create_dict_iterator(num_epochs=1):
  53. golden = np.array([i], dtype=np.float32)
  54. np.testing.assert_array_equal(item["data"].asnumpy(), golden)
  55. assert isinstance(item["data"], Tensor)
  56. assert item["data"].dtype == mstype.float32
  57. i += 1
  58. assert i == 64
  59. def test_iterator_create_tuple_mstensor():
  60. """
  61. Test creating tuple iterator with output MSTensor
  62. """
  63. def generator():
  64. for i in range(64):
  65. yield (np.array([i], dtype=np.float32),)
  66. # apply dataset operations
  67. data1 = ds.GeneratorDataset(generator, ["data"])
  68. i = 0
  69. for item in data1.create_tuple_iterator(num_epochs=1):
  70. golden = np.array([i], dtype=np.float32)
  71. np.testing.assert_array_equal(item[0].asnumpy(), golden)
  72. assert isinstance(item[0], Tensor)
  73. assert item[0].dtype == mstype.float32
  74. i += 1
  75. assert i == 64
  76. def test_iterator_weak_ref():
  77. ITERATORS_LIST.clear()
  78. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR)
  79. itr1 = data.create_tuple_iterator(num_epochs=1)
  80. itr2 = data.create_tuple_iterator(num_epochs=1)
  81. itr3 = data.create_tuple_iterator(num_epochs=1)
  82. assert len(ITERATORS_LIST) == 3
  83. assert sum(itr() is not None for itr in ITERATORS_LIST) == 3
  84. del itr1
  85. assert len(ITERATORS_LIST) == 3
  86. assert sum(itr() is not None for itr in ITERATORS_LIST) == 2
  87. del itr2
  88. assert len(ITERATORS_LIST) == 3
  89. assert sum(itr() is not None for itr in ITERATORS_LIST) == 1
  90. del itr3
  91. assert len(ITERATORS_LIST) == 3
  92. assert sum(itr() is not None for itr in ITERATORS_LIST) == 0
  93. itr1 = data.create_tuple_iterator(num_epochs=1)
  94. itr2 = data.create_tuple_iterator(num_epochs=1)
  95. itr3 = data.create_tuple_iterator(num_epochs=1)
  96. _cleanup()
  97. with pytest.raises(AttributeError) as info:
  98. itr2.__next__()
  99. assert "object has no attribute 'depipeline'" in str(info.value)
  100. del itr1
  101. assert len(ITERATORS_LIST) == 6
  102. assert sum(itr() is not None for itr in ITERATORS_LIST) == 2
  103. _cleanup()
  104. def test_iterator_exception():
  105. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR)
  106. try:
  107. _ = data.create_dict_iterator(output_numpy="123")
  108. assert False
  109. except TypeError as e:
  110. assert "Argument output_numpy with value 123 is not of type" in str(e)
  111. try:
  112. _ = data.create_dict_iterator(output_numpy=123)
  113. assert False
  114. except TypeError as e:
  115. assert "Argument output_numpy with value 123 is not of type" in str(e)
  116. try:
  117. _ = data.create_tuple_iterator(output_numpy="123")
  118. assert False
  119. except TypeError as e:
  120. assert "Argument output_numpy with value 123 is not of type" in str(e)
  121. try:
  122. _ = data.create_tuple_iterator(output_numpy=123)
  123. assert False
  124. except TypeError as e:
  125. assert "Argument output_numpy with value 123 is not of type" in str(e)
  126. class MyDict(dict):
  127. def __getattr__(self, key):
  128. return self[key]
  129. def __setattr__(self, key, value):
  130. self[key] = value
  131. def __call__(self, t):
  132. return t
  133. def test_tree_copy():
  134. """
  135. Testing copying the tree with a pyfunc that cannot be pickled
  136. """
  137. data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=COLUMNS)
  138. data1 = data.map(operations=[MyDict()])
  139. itr = data1.create_tuple_iterator(num_epochs=1)
  140. assert id(data1) != id(itr.dataset)
  141. assert id(data) != id(itr.dataset.children[0])
  142. assert id(data1.operations[0]) == id(itr.dataset.operations[0])
  143. itr.release()
  144. if __name__ == '__main__':
  145. test_iterator_create_tuple_numpy()
  146. test_iterator_weak_ref()
  147. test_iterator_exception()
  148. test_tree_copy()