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_fast_text.py 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. # Copyright 2021 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. from mindspore import log
  18. import mindspore.dataset as ds
  19. import mindspore.dataset.text as text
  20. import mindspore.dataset.text.transforms as T
  21. DATASET_ROOT_PATH = "../data/dataset/test_fast_text/"
  22. def test_fast_text_all_build_from_file_params():
  23. """
  24. Feature: FastText
  25. Description: test with all parameters which include `path` and `max_vector` in function BuildFromFile
  26. Expectation: output is equal to the expected value
  27. """
  28. vectors = text.FastText.from_file(DATASET_ROOT_PATH + "fast_text.vec", max_vectors=100)
  29. to_vectors = text.ToVectors(vectors)
  30. data = ds.TextFileDataset(DATASET_ROOT_PATH + "words.txt", shuffle=False)
  31. data = data.map(operations=to_vectors, input_columns=["text"])
  32. ind = 0
  33. res = [[0.418, 0.24968, -0.41242, 0.1217, 0.34527, -0.04445718411],
  34. [0, 0, 0, 0, 0, 0],
  35. [0.15164, 0.30177, -0.16763, 0.17684, 0.31719, 0.33973],
  36. [0.70853, 0.57088, -0.4716, 0.18048, 0.54449, 0.72603],
  37. [0.68047, -0.039263, 0.30186, -0.17792, 0.42962, 0.032246],
  38. [0.26818, 0.14346, -0.27877, 0.016257, 0.11384, 0.69923],
  39. [0, 0, 0, 0, 0, 0]]
  40. print(data)
  41. for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  42. res_array = np.array(res[ind], dtype=np.float32)
  43. assert np.array_equal(res_array, d["text"]), ind
  44. ind += 1
  45. def test_fast_text_all_build_from_file_params_eager():
  46. """
  47. Feature: FastText
  48. Description: test with all parameters which include `path` and `max_vector` in function BuildFromFile in eager mode
  49. Expectation: output is equal to the expected value
  50. """
  51. vectors = text.FastText.from_file(DATASET_ROOT_PATH + "fast_text.vec", max_vectors=4)
  52. to_vectors = T.ToVectors(vectors)
  53. result1 = to_vectors("ok")
  54. result2 = to_vectors("!")
  55. result3 = to_vectors("this")
  56. result4 = to_vectors("is")
  57. result5 = to_vectors("my")
  58. result6 = to_vectors("home")
  59. result7 = to_vectors("none")
  60. res = [[0.418, 0.24968, -0.41242, 0.1217, 0.34527, -0.04445718411],
  61. [0.013441, 0.23682, -0.16899, 0.40951, 0.63812, 0.47709],
  62. [0.15164, 0.30177, -0.16763, 0.17684, 0.31719, 0.33973],
  63. [0.70853, 0.57088, -0.4716, 0.18048, 0.54449, 0.72603],
  64. [0, 0, 0, 0, 0, 0],
  65. [0, 0, 0, 0, 0, 0],
  66. [0, 0, 0, 0, 0, 0]]
  67. res_array = np.array(res, dtype=np.float32)
  68. assert np.array_equal(result1, res_array[0])
  69. assert np.array_equal(result2, res_array[1])
  70. assert np.array_equal(result3, res_array[2])
  71. assert np.array_equal(result4, res_array[3])
  72. assert np.array_equal(result5, res_array[4])
  73. assert np.array_equal(result6, res_array[5])
  74. assert np.array_equal(result7, res_array[6])
  75. def test_fast_text_all_to_vectors_params_eager():
  76. """
  77. Feature: FastText
  78. Description: test with all parameters which include `unk_init` and `lower_case_backup` in function ToVectors
  79. in eager mode
  80. Expectation: output is equal to the expected value
  81. """
  82. vectors = text.FastText.from_file(DATASET_ROOT_PATH + "fast_text.vec", max_vectors=4)
  83. my_unk = [-1, -1, -1, -1, -1, -1]
  84. to_vectors = T.ToVectors(vectors, unk_init=my_unk, lower_case_backup=True)
  85. result1 = to_vectors("Ok")
  86. result2 = to_vectors("!")
  87. result3 = to_vectors("This")
  88. result4 = to_vectors("is")
  89. result5 = to_vectors("my")
  90. result6 = to_vectors("home")
  91. result7 = to_vectors("none")
  92. res = [[0.418, 0.24968, -0.41242, 0.1217, 0.34527, -0.04445718411],
  93. [0.013441, 0.23682, -0.16899, 0.40951, 0.63812, 0.47709],
  94. [0.15164, 0.30177, -0.16763, 0.17684, 0.31719, 0.33973],
  95. [0.70853, 0.57088, -0.4716, 0.18048, 0.54449, 0.72603],
  96. [-1, -1, -1, -1, -1, -1],
  97. [-1, -1, -1, -1, -1, -1],
  98. [-1, -1, -1, -1, -1, -1]]
  99. res_array = np.array(res, dtype=np.float32)
  100. assert np.array_equal(result1, res_array[0])
  101. assert np.array_equal(result2, res_array[1])
  102. assert np.array_equal(result3, res_array[2])
  103. assert np.array_equal(result4, res_array[3])
  104. assert np.array_equal(result5, res_array[4])
  105. assert np.array_equal(result6, res_array[5])
  106. assert np.array_equal(result7, res_array[6])
  107. def test_fast_text_build_from_file():
  108. """
  109. Feature: FastText
  110. Description: test with only default parameter
  111. Expectation: output is equal to the expected value
  112. """
  113. vectors = text.FastText.from_file(DATASET_ROOT_PATH + "fast_text.vec")
  114. to_vectors = text.ToVectors(vectors)
  115. data = ds.TextFileDataset(DATASET_ROOT_PATH + "words.txt", shuffle=False)
  116. data = data.map(operations=to_vectors, input_columns=["text"])
  117. ind = 0
  118. res = [[0.418, 0.24968, -0.41242, 0.1217, 0.34527, -0.04445718411],
  119. [0, 0, 0, 0, 0, 0],
  120. [0.15164, 0.30177, -0.16763, 0.17684, 0.31719, 0.33973],
  121. [0.70853, 0.57088, -0.4716, 0.18048, 0.54449, 0.72603],
  122. [0.68047, -0.039263, 0.30186, -0.17792, 0.42962, 0.032246],
  123. [0.26818, 0.14346, -0.27877, 0.016257, 0.11384, 0.69923],
  124. [0, 0, 0, 0, 0, 0]]
  125. print(data)
  126. for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  127. res_array = np.array(res[ind], dtype=np.float32)
  128. assert np.array_equal(res_array, d["text"]), ind
  129. ind += 1
  130. def test_fast_text_build_from_file_eager():
  131. """
  132. Feature: FastText
  133. Description: test with only default parameter in eager mode
  134. Expectation: output is equal to the expected value
  135. """
  136. vectors = text.FastText.from_file(DATASET_ROOT_PATH + "fast_text.vec")
  137. to_vectors = T.ToVectors(vectors)
  138. result1 = to_vectors("ok")
  139. result2 = to_vectors("!")
  140. result3 = to_vectors("this")
  141. result4 = to_vectors("is")
  142. result5 = to_vectors("my")
  143. result6 = to_vectors("home")
  144. result7 = to_vectors("none")
  145. res = [[0.418, 0.24968, -0.41242, 0.1217, 0.34527, -0.04445718411],
  146. [0.013441, 0.23682, -0.16899, 0.40951, 0.63812, 0.47709],
  147. [0.15164, 0.30177, -0.16763, 0.17684, 0.31719, 0.33973],
  148. [0.70853, 0.57088, -0.4716, 0.18048, 0.54449, 0.72603],
  149. [0.68047, -0.039263, 0.30186, -0.17792, 0.42962, 0.032246],
  150. [0.26818, 0.14346, -0.27877, 0.016257, 0.11384, 0.69923],
  151. [0, 0, 0, 0, 0, 0]]
  152. res_array = np.array(res, dtype=np.float32)
  153. assert np.array_equal(result1, res_array[0])
  154. assert np.array_equal(result2, res_array[1])
  155. assert np.array_equal(result3, res_array[2])
  156. assert np.array_equal(result4, res_array[3])
  157. assert np.array_equal(result5, res_array[4])
  158. assert np.array_equal(result6, res_array[5])
  159. assert np.array_equal(result7, res_array[6])
  160. def test_fast_text_invalid_input():
  161. """
  162. Feature: FastText
  163. Description: test the validate function with invalid parameters
  164. Expectation: output is equal to the expected error
  165. """
  166. def test_invalid_input(test_name, file_path, error, error_msg, max_vectors=None, unk_init=None,
  167. lower_case_backup=False, token="ok"):
  168. log.info("Test Vectors with wrong input: {0}".format(test_name))
  169. with pytest.raises(error) as error_info:
  170. vectors = text.FastText.from_file(file_path, max_vectors=max_vectors)
  171. to_vectors = T.ToVectors(vectors, unk_init=unk_init, lower_case_backup=lower_case_backup)
  172. to_vectors(token)
  173. assert error_msg in str(error_info.value)
  174. test_invalid_input("Not all vectors have the same number of dimensions",
  175. DATASET_ROOT_PATH + "fast_text_dim_different.vec", error=RuntimeError,
  176. error_msg="all vectors must have the same number of dimensions, " \
  177. "but got dim 5 while expecting 6")
  178. test_invalid_input("the file is empty.", DATASET_ROOT_PATH + "fast_text_empty.vec",
  179. error=RuntimeError, error_msg="invalid file, file is empty.")
  180. test_invalid_input("the count of `unknown_init`'s element is different with word vector.",
  181. DATASET_ROOT_PATH + "fast_text.vec",
  182. error=RuntimeError,
  183. error_msg="unk_init must be the same length as vectors, but got unk_init",
  184. unk_init=[-1, -1])
  185. test_invalid_input("The file not exist", DATASET_ROOT_PATH + "not_exist.vec", RuntimeError,
  186. error_msg="FastText: invalid file")
  187. test_invalid_input("The token is 1-dimensional", DATASET_ROOT_PATH + "fast_text_with_wrong_info.vec",
  188. error=RuntimeError, error_msg="token with 1-dimensional vector.")
  189. test_invalid_input("max_vectors parameter must be greater than 0", DATASET_ROOT_PATH + "fast_text.vec",
  190. error=ValueError, error_msg="Input max_vectors is not within the required interval",
  191. max_vectors=-1)
  192. test_invalid_input("invalid max_vectors parameter type as a float", DATASET_ROOT_PATH + "fast_text.vec",
  193. error=TypeError, error_msg="Argument max_vectors with value 1.0 is not of type [<class 'int'>],"
  194. " but got <class 'float'>.", max_vectors=1.0)
  195. test_invalid_input("invalid max_vectors parameter type as a string", DATASET_ROOT_PATH + "fast_text.vec",
  196. error=TypeError, error_msg="Argument max_vectors with value 1 is not of type [<class 'int'>],"
  197. " but got <class 'str'>.", max_vectors="1")
  198. test_invalid_input("invalid token parameter type as a float", DATASET_ROOT_PATH + "fast_text.vec",
  199. error=RuntimeError, error_msg="input tensor type should be string.", token=1.0)
  200. test_invalid_input("invalid lower_case_backup parameter type as a string", DATASET_ROOT_PATH + "fast_text.vec",
  201. error=TypeError, error_msg="Argument lower_case_backup with value True is " \
  202. "not of type [<class 'bool'>],"
  203. " but got <class 'str'>.", lower_case_backup="True")
  204. test_invalid_input("invalid lower_case_backup parameter type as a string", DATASET_ROOT_PATH + "fast_text.vec",
  205. error=TypeError, error_msg="Argument lower_case_backup with value True is " \
  206. "not of type [<class 'bool'>],"
  207. " but got <class 'str'>.", lower_case_backup="True")
  208. test_invalid_input("the suffix of pre-training set must be `*.vec`", DATASET_ROOT_PATH + "fast_text.txt",
  209. error=RuntimeError, error_msg="FastText: invalid file, can not find file '*.vec'")
  210. if __name__ == '__main__':
  211. test_fast_text_all_build_from_file_params()
  212. test_fast_text_all_build_from_file_params_eager()
  213. test_fast_text_all_to_vectors_params_eager()
  214. test_fast_text_build_from_file()
  215. test_fast_text_build_from_file_eager()
  216. test_fast_text_invalid_input()