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_to_number_op.py 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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.common.dtype as mstype
  18. import mindspore.dataset as ds
  19. import mindspore.dataset.text as text
  20. np_integral_types = [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16,
  21. np.uint32, np.uint64]
  22. ms_integral_types = [mstype.int8, mstype.int16, mstype.int32, mstype.int64, mstype.uint8,
  23. mstype.uint16, mstype.uint32, mstype.uint64]
  24. np_non_integral_types = [np.float16, np.float32, np.float64]
  25. ms_non_integral_types = [mstype.float16, mstype.float32, mstype.float64]
  26. def string_dataset_generator(strings):
  27. for string in strings:
  28. yield (np.array(string, dtype='S'),)
  29. def test_to_number_eager():
  30. """
  31. Test ToNumber op is callable
  32. """
  33. input_strings = [["1", "2", "3"], ["4", "5", "6"]]
  34. op = text.ToNumber(mstype.int8)
  35. # test input_strings as one 2D tensor
  36. result1 = op(input_strings) # np array: [[1 2 3] [4 5 6]]
  37. assert np.array_equal(result1, np.array([[1, 2, 3], [4, 5, 6]], dtype='i'))
  38. # test input multiple tensors
  39. with pytest.raises(RuntimeError) as info:
  40. # test input_strings as two 1D tensor. It's error because to_number is an OneToOne op
  41. _ = op(*input_strings)
  42. assert "The op is OneToOne, can only accept one tensor as input." in str(info.value)
  43. def test_to_number_typical_case_integral():
  44. input_strings = [["-121", "14"], ["-2219", "7623"], ["-8162536", "162371864"],
  45. ["-1726483716", "98921728421"]]
  46. for ms_type, inputs in zip(ms_integral_types, input_strings):
  47. dataset = ds.GeneratorDataset(string_dataset_generator(inputs), "strings")
  48. dataset = dataset.map(operations=text.ToNumber(ms_type), input_columns=["strings"])
  49. expected_output = [int(string) for string in inputs]
  50. output = []
  51. for data in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):
  52. output.append(data["strings"])
  53. assert output == expected_output
  54. def test_to_number_typical_case_non_integral():
  55. input_strings = [["-1.1", "1.4"], ["-2219.321", "7623.453"], ["-816256.234282", "162371864.243243"]]
  56. epsilons = [0.001, 0.001, 0.0001, 0.0001, 0.0000001, 0.0000001]
  57. for ms_type, inputs in zip(ms_non_integral_types, input_strings):
  58. dataset = ds.GeneratorDataset(string_dataset_generator(inputs), "strings")
  59. dataset = dataset.map(operations=text.ToNumber(ms_type), input_columns=["strings"])
  60. expected_output = [float(string) for string in inputs]
  61. output = []
  62. for data in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):
  63. output.append(data["strings"])
  64. for expected, actual, epsilon in zip(expected_output, output, epsilons):
  65. assert abs(expected - actual) < epsilon
  66. def out_of_bounds_error_message_check(dataset, np_type, value_to_cast):
  67. type_info = np.iinfo(np_type)
  68. type_max = str(type_info.max)
  69. type_min = str(type_info.min)
  70. type_name = str(np.dtype(np_type))
  71. with pytest.raises(RuntimeError) as info:
  72. for _ in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):
  73. pass
  74. assert "string input " + value_to_cast + " will be out of bounds if cast to " + type_name in str(info.value)
  75. assert "valid range is: [" + type_min + ", " + type_max + "]" in str(info.value)
  76. def test_to_number_out_of_bounds_integral():
  77. for np_type, ms_type in zip(np_integral_types, ms_integral_types):
  78. type_info = np.iinfo(np_type)
  79. input_strings = [str(type_info.max + 10)]
  80. dataset = ds.GeneratorDataset(string_dataset_generator(input_strings), "strings")
  81. dataset = dataset.map(operations=text.ToNumber(ms_type), input_columns=["strings"])
  82. out_of_bounds_error_message_check(dataset, np_type, input_strings[0])
  83. input_strings = [str(type_info.min - 10)]
  84. dataset = ds.GeneratorDataset(string_dataset_generator(input_strings), "strings")
  85. dataset = dataset.map(operations=text.ToNumber(ms_type), input_columns=["strings"])
  86. out_of_bounds_error_message_check(dataset, np_type, input_strings[0])
  87. def test_to_number_out_of_bounds_non_integral():
  88. above_range = [str(np.finfo(np.float16).max * 10), str(np.finfo(np.float32).max * 10), "1.8e+308"]
  89. input_strings = [above_range[0]]
  90. dataset = ds.GeneratorDataset(string_dataset_generator(input_strings), "strings")
  91. dataset = dataset.map(operations=text.ToNumber(ms_non_integral_types[0]), input_columns=["strings"])
  92. with pytest.raises(RuntimeError) as info:
  93. for _ in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):
  94. pass
  95. assert "outside of valid float16 range" in str(info.value)
  96. input_strings = [above_range[1]]
  97. dataset = ds.GeneratorDataset(string_dataset_generator(input_strings), "strings")
  98. dataset = dataset.map(operations=text.ToNumber(ms_non_integral_types[1]), input_columns=["strings"])
  99. with pytest.raises(RuntimeError) as info:
  100. for _ in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):
  101. pass
  102. assert "string input " + input_strings[0] + " will be out of bounds if cast to float32" in str(info.value)
  103. input_strings = [above_range[2]]
  104. dataset = ds.GeneratorDataset(string_dataset_generator(input_strings), "strings")
  105. dataset = dataset.map(operations=text.ToNumber(ms_non_integral_types[2]), input_columns=["strings"])
  106. with pytest.raises(RuntimeError) as info:
  107. for _ in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):
  108. pass
  109. assert "string input " + input_strings[0] + " will be out of bounds if cast to float64" in str(info.value)
  110. below_range = [str(np.finfo(np.float16).min * 10), str(np.finfo(np.float32).min * 10), "-1.8e+308"]
  111. input_strings = [below_range[0]]
  112. dataset = ds.GeneratorDataset(string_dataset_generator(input_strings), "strings")
  113. dataset = dataset.map(operations=text.ToNumber(ms_non_integral_types[0]), input_columns=["strings"])
  114. with pytest.raises(RuntimeError) as info:
  115. for _ in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):
  116. pass
  117. assert "outside of valid float16 range" in str(info.value)
  118. input_strings = [below_range[1]]
  119. dataset = ds.GeneratorDataset(string_dataset_generator(input_strings), "strings")
  120. dataset = dataset.map(operations=text.ToNumber(ms_non_integral_types[1]), input_columns=["strings"])
  121. with pytest.raises(RuntimeError) as info:
  122. for _ in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):
  123. pass
  124. assert "string input " + input_strings[0] + " will be out of bounds if cast to float32" in str(info.value)
  125. input_strings = [below_range[2]]
  126. dataset = ds.GeneratorDataset(string_dataset_generator(input_strings), "strings")
  127. dataset = dataset.map(operations=text.ToNumber(ms_non_integral_types[2]), input_columns=["strings"])
  128. with pytest.raises(RuntimeError) as info:
  129. for _ in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):
  130. pass
  131. assert "string input " + input_strings[0] + " will be out of bounds if cast to float64" in str(info.value)
  132. def test_to_number_boundaries_integral():
  133. for np_type, ms_type in zip(np_integral_types, ms_integral_types):
  134. type_info = np.iinfo(np_type)
  135. input_strings = [str(type_info.max)]
  136. dataset = ds.GeneratorDataset(string_dataset_generator(input_strings), "strings")
  137. dataset = dataset.map(operations=text.ToNumber(ms_type), input_columns=["strings"])
  138. for data in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):
  139. assert data["strings"] == int(input_strings[0])
  140. input_strings = [str(type_info.min)]
  141. dataset = ds.GeneratorDataset(string_dataset_generator(input_strings), "strings")
  142. dataset = dataset.map(operations=text.ToNumber(ms_type), input_columns=["strings"])
  143. for data in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):
  144. assert data["strings"] == int(input_strings[0])
  145. input_strings = [str(0)]
  146. dataset = ds.GeneratorDataset(string_dataset_generator(input_strings), "strings")
  147. dataset = dataset.map(operations=text.ToNumber(ms_type), input_columns=["strings"])
  148. for data in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):
  149. assert data["strings"] == int(input_strings[0])
  150. def test_to_number_invalid_input():
  151. input_strings = ["a8fa9ds8fa"]
  152. dataset = ds.GeneratorDataset(string_dataset_generator(input_strings), "strings")
  153. dataset = dataset.map(operations=text.ToNumber(mstype.int32), input_columns=["strings"])
  154. with pytest.raises(RuntimeError) as info:
  155. for _ in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):
  156. pass
  157. assert "it is invalid to convert \"" + input_strings[0] + "\" to a number" in str(info.value)
  158. def test_to_number_invalid_type():
  159. with pytest.raises(TypeError) as info:
  160. dataset = ds.GeneratorDataset(string_dataset_generator(["a8fa9ds8fa"]), "strings")
  161. dataset = dataset.map(operations=text.ToNumber(mstype.bool_), input_columns=["strings"])
  162. assert "data_type: Bool is not numeric data type" in str(info.value)
  163. if __name__ == '__main__':
  164. test_to_number_eager()
  165. test_to_number_typical_case_integral()
  166. test_to_number_typical_case_non_integral()
  167. test_to_number_boundaries_integral()
  168. test_to_number_out_of_bounds_integral()
  169. test_to_number_out_of_bounds_non_integral()
  170. test_to_number_invalid_input()
  171. test_to_number_invalid_type()