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_vocab.py 13 kB

5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. # Copyright 2020-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. import mindspore.dataset as ds
  18. import mindspore.dataset.text as text
  19. import mindspore.common.dtype as mstype
  20. from mindspore import log as logger
  21. # this file contains "home is behind the world head" each word is 1 line
  22. DATA_FILE = "../data/dataset/testVocab/words.txt"
  23. VOCAB_FILE = "../data/dataset/testVocab/vocab_list.txt"
  24. SIMPLE_VOCAB_FILE = "../data/dataset/testVocab/simple_vocab_list.txt"
  25. def test_get_vocab():
  26. """
  27. Feature: Python text.Vocab class
  28. Description: test vocab() method of text.Vocab
  29. Expectation: success.
  30. """
  31. logger.info("test tokens_to_ids")
  32. vocab = text.Vocab.from_list(["w1", "w2", "w3"], special_tokens=["<unk>"], special_first=True)
  33. vocab_ = vocab.vocab()
  34. assert "<unk>" in vocab_ and "w1" in vocab_ and "w2" in vocab_ and "w3" in vocab_
  35. def test_vocab_tokens_to_ids():
  36. """
  37. Feature: Python text.Vocab class
  38. Description: test tokens_to_ids() method of text.Vocab
  39. Expectation: success.
  40. """
  41. logger.info("test tokens_to_ids")
  42. vocab = text.Vocab.from_list(["w1", "w2", "w3"], special_tokens=["<unk>"], special_first=True)
  43. ids = vocab.tokens_to_ids(["w1", "w3"])
  44. assert ids == [1, 3]
  45. ids = vocab.tokens_to_ids(["w1", "w4"])
  46. assert ids == [1, -1]
  47. ids = vocab.tokens_to_ids("<unk>")
  48. assert ids == 0
  49. ids = vocab.tokens_to_ids("hello")
  50. assert ids == -1
  51. ids = vocab.tokens_to_ids(np.array(["w1", "w3"]))
  52. assert ids == [1, 3]
  53. ids = vocab.tokens_to_ids(np.array("w1"))
  54. assert ids == 1
  55. def test_vocab_ids_to_tokens():
  56. """
  57. Feature: Python text.Vocab class
  58. Description: test ids_to_tokens() method of text.Vocab
  59. Expectation: success.
  60. """
  61. logger.info("test ids_to_tokens")
  62. vocab = text.Vocab.from_list(["w1", "w2", "w3"], special_tokens=["<unk>"], special_first=True)
  63. tokens = vocab.ids_to_tokens([2, 3])
  64. assert tokens == ["w2", "w3"]
  65. tokens = vocab.ids_to_tokens([2, 7])
  66. assert tokens == ["w2", ""]
  67. tokens = vocab.ids_to_tokens(0)
  68. assert tokens == "<unk>"
  69. tokens = vocab.ids_to_tokens(7)
  70. assert tokens == ""
  71. tokens = vocab.ids_to_tokens(np.array([2, 3]))
  72. assert tokens == ["w2", "w3"]
  73. tokens = vocab.ids_to_tokens(np.array(2))
  74. assert tokens == "w2"
  75. def test_vocab_exception():
  76. """
  77. Feature: Python text.Vocab class
  78. Description: test exceptions of text.Vocab
  79. Expectation: raise RuntimeError when vocab is not initialized, raise TypeError when input is wrong.
  80. """
  81. vocab = text.Vocab()
  82. with pytest.raises(RuntimeError):
  83. vocab.ids_to_tokens(2)
  84. with pytest.raises(RuntimeError):
  85. vocab.tokens_to_ids(["w3"])
  86. vocab = text.Vocab.from_list(["w1", "w2", "w3"], special_tokens=["<unk>"], special_first=True)
  87. with pytest.raises(TypeError):
  88. vocab.ids_to_tokens("abc")
  89. with pytest.raises(TypeError):
  90. vocab.ids_to_tokens([2, 1.2, "abc"])
  91. with pytest.raises(ValueError):
  92. vocab.ids_to_tokens(-2)
  93. with pytest.raises(TypeError):
  94. vocab.tokens_to_ids([1, "w3"])
  95. with pytest.raises(TypeError):
  96. vocab.tokens_to_ids(999)
  97. def test_lookup_callable():
  98. """
  99. Test lookup is callable
  100. """
  101. logger.info("test_lookup_callable")
  102. vocab = text.Vocab.from_list(['深', '圳', '欢', '迎', '您'])
  103. lookup = text.Lookup(vocab)
  104. word = "迎"
  105. assert lookup(word) == 3
  106. def test_from_list_tutorial():
  107. vocab = text.Vocab.from_list("home IS behind the world ahead !".split(" "), ["<pad>", "<unk>"], True)
  108. lookup = text.Lookup(vocab, "<unk>")
  109. data = ds.TextFileDataset(DATA_FILE, shuffle=False)
  110. data = data.map(operations=lookup, input_columns=["text"])
  111. ind = 0
  112. res = [2, 1, 4, 5, 6, 7]
  113. for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  114. assert d["text"] == res[ind], ind
  115. ind += 1
  116. def test_from_file_tutorial():
  117. vocab = text.Vocab.from_file(VOCAB_FILE, ",", None, ["<pad>", "<unk>"], True)
  118. lookup = text.Lookup(vocab)
  119. data = ds.TextFileDataset(DATA_FILE, shuffle=False)
  120. data = data.map(operations=lookup, input_columns=["text"])
  121. ind = 0
  122. res = [10, 11, 12, 15, 13, 14]
  123. for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  124. assert d["text"] == res[ind], ind
  125. ind += 1
  126. def test_from_dict_tutorial():
  127. vocab = text.Vocab.from_dict({"home": 3, "behind": 2, "the": 4, "world": 5, "<unk>": 6})
  128. lookup = text.Lookup(vocab, "<unk>") # any unknown token will be mapped to the id of <unk>
  129. data = ds.TextFileDataset(DATA_FILE, shuffle=False)
  130. data = data.map(operations=lookup, input_columns=["text"])
  131. res = [3, 6, 2, 4, 5, 6]
  132. ind = 0
  133. for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  134. assert d["text"] == res[ind], ind
  135. ind += 1
  136. def test_from_dict_exception():
  137. try:
  138. vocab = text.Vocab.from_dict({"home": -1, "behind": 0})
  139. if not vocab:
  140. raise ValueError("Vocab is None")
  141. except ValueError as e:
  142. assert "is not within the required interval" in str(e)
  143. def test_from_list():
  144. def gen(texts):
  145. for word in texts.split(" "):
  146. yield (np.array(word, dtype='S'),)
  147. def test_config(lookup_str, vocab_input, special_tokens, special_first, unknown_token):
  148. try:
  149. vocab = text.Vocab.from_list(vocab_input, special_tokens, special_first)
  150. data = ds.GeneratorDataset(gen(lookup_str), column_names=["text"])
  151. data = data.map(operations=text.Lookup(vocab, unknown_token), input_columns=["text"])
  152. res = []
  153. for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  154. res.append(d["text"].item())
  155. return res
  156. except (ValueError, RuntimeError, TypeError) as e:
  157. return str(e)
  158. # test basic default config, special_token=None, unknown_token=None
  159. assert test_config("w1 w2 w3", ["w1", "w2", "w3"], None, True, None) == [0, 1, 2]
  160. # test normal operations
  161. assert test_config("w1 w2 w3 s1 s2 ephemeral", ["w1", "w2", "w3"], ["s1", "s2"], True, "s2") == [2, 3, 4, 0, 1, 1]
  162. assert test_config("w1 w2 w3 s1 s2", ["w1", "w2", "w3"], ["s1", "s2"], False, "s2") == [0, 1, 2, 3, 4]
  163. assert test_config("w3 w2 w1", ["w1", "w2", "w3"], None, True, "w1") == [2, 1, 0]
  164. assert test_config("w3 w2 w1", ["w1", "w2", "w3"], None, False, "w1") == [2, 1, 0]
  165. # test unknown token lookup
  166. assert test_config("w1 un1 w3 un2", ["w1", "w2", "w3"], ["<pad>", "<unk>"], True, "<unk>") == [2, 1, 4, 1]
  167. assert test_config("w1 un1 w3 un2", ["w1", "w2", "w3"], ["<pad>", "<unk>"], False, "<unk>") == [0, 4, 2, 4]
  168. # test exceptions
  169. assert "doesn't exist in vocab." in test_config("un1", ["w1"], [], False, "unk")
  170. assert "doesn't exist in vocab and no unknown token is specified." in test_config("un1", ["w1"], [], False, None)
  171. assert "doesn't exist in vocab" in test_config("un1", ["w1"], [], False, None)
  172. assert "word_list contains duplicate" in test_config("w1", ["w1", "w1"], [], True, "w1")
  173. assert "special_tokens contains duplicate" in test_config("w1", ["w1", "w2"], ["s1", "s1"], True, "w1")
  174. assert "special_tokens and word_list contain duplicate" in test_config("w1", ["w1", "w2"], ["s1", "w1"], True, "w1")
  175. assert "is not of type" in test_config("w1", ["w1", "w2"], ["s1"], True, 123)
  176. def test_from_list_lookup_empty_string():
  177. # "" is a valid word in vocab, which can be looked up by LookupOp
  178. vocab = text.Vocab.from_list("home IS behind the world ahead !".split(" "), ["<pad>", ""], True)
  179. lookup = text.Lookup(vocab, "")
  180. data = ds.TextFileDataset(DATA_FILE, shuffle=False)
  181. data = data.map(operations=lookup, input_columns=["text"])
  182. ind = 0
  183. res = [2, 1, 4, 5, 6, 7]
  184. for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  185. assert d["text"] == res[ind], ind
  186. ind += 1
  187. # unknown_token of LookUp is None, it will convert to std::nullopt in C++,
  188. # so it has nothing to do with "" in vocab and C++ will skip looking up unknown_token
  189. vocab = text.Vocab.from_list("home IS behind the world ahead !".split(" "), ["<pad>", ""], True)
  190. lookup = text.Lookup(vocab)
  191. data = ds.TextFileDataset(DATA_FILE, shuffle=False)
  192. data = data.map(operations=lookup, input_columns=["text"])
  193. try:
  194. for _ in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  195. pass
  196. except RuntimeError as e:
  197. assert "token: \"is\" doesn't exist in vocab and no unknown token is specified" in str(e)
  198. def test_from_file():
  199. def gen(texts):
  200. for word in texts.split(" "):
  201. yield (np.array(word, dtype='S'),)
  202. def test_config(lookup_str, vocab_size, special_tokens, special_first):
  203. try:
  204. vocab = text.Vocab.from_file(SIMPLE_VOCAB_FILE, vocab_size=vocab_size, special_tokens=special_tokens,
  205. special_first=special_first)
  206. data = ds.GeneratorDataset(gen(lookup_str), column_names=["text"])
  207. data = data.map(operations=text.Lookup(vocab, "s2"), input_columns=["text"])
  208. res = []
  209. for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  210. res.append(d["text"].item())
  211. return res
  212. except ValueError as e:
  213. return str(e)
  214. # test special tokens are prepended
  215. assert test_config("w1 w2 w3 s1 s2 s3", None, ["s1", "s2", "s3"], True) == [3, 4, 5, 0, 1, 2]
  216. # test special tokens are appended
  217. assert test_config("w1 w2 w3 s1 s2 s3", None, ["s1", "s2", "s3"], False) == [0, 1, 2, 8, 9, 10]
  218. # test special tokens are prepended when not all words in file are used
  219. assert test_config("w1 w2 w3 s1 s2 s3", 3, ["s1", "s2", "s3"], False) == [0, 1, 2, 3, 4, 5]
  220. # text exception special_words contains duplicate words
  221. assert "special_tokens contains duplicate" in test_config("w1", None, ["s1", "s1"], True)
  222. # test exception when vocab_size is negative
  223. assert "Input vocab_size must be greater than 0" in test_config("w1 w2", 0, [], True)
  224. assert "Input vocab_size must be greater than 0" in test_config("w1 w2", -1, [], True)
  225. def test_lookup_cast_type():
  226. def gen(texts):
  227. for word in texts.split(" "):
  228. yield (np.array(word, dtype='S'),)
  229. def test_config(lookup_str, data_type=None):
  230. try:
  231. vocab = text.Vocab.from_list(["w1", "w2", "w3"], special_tokens=["<unk>"], special_first=True)
  232. data = ds.GeneratorDataset(gen(lookup_str), column_names=["text"])
  233. # if data_type is None, test the default value of data_type
  234. op = text.Lookup(vocab, "<unk>") if data_type is None else text.Lookup(vocab, "<unk>", data_type)
  235. data = data.map(operations=op, input_columns=["text"])
  236. res = []
  237. for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  238. res.append(d["text"])
  239. return res[0].dtype
  240. except (ValueError, RuntimeError, TypeError) as e:
  241. return str(e)
  242. # test result is correct
  243. assert test_config("w1", mstype.int8) == np.dtype("int8")
  244. assert test_config("w2", mstype.int32) == np.dtype("int32")
  245. assert test_config("w3", mstype.int64) == np.dtype("int64")
  246. assert test_config("unk", mstype.float32) != np.dtype("int32")
  247. assert test_config("unk") == np.dtype("int32")
  248. # test exception, data_type isn't the correct type
  249. assert "tldr is not of type [<class 'mindspore._c_expression.typing.Type'>]" in test_config("unk", "tldr")
  250. assert "Lookup : The parameter data_type must be numeric including bool." in \
  251. test_config("w1", mstype.string)
  252. if __name__ == '__main__':
  253. test_lookup_callable()
  254. test_from_dict_exception()
  255. test_from_list_tutorial()
  256. test_from_file_tutorial()
  257. test_from_dict_tutorial()
  258. test_from_list()
  259. test_from_file()
  260. test_lookup_cast_type()