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 10 kB

5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 mindspore.dataset as ds
  17. import mindspore.dataset.text as text
  18. import mindspore.common.dtype as mstype
  19. from mindspore import log as logger
  20. # this file contains "home is behind the world head" each word is 1 line
  21. DATA_FILE = "../data/dataset/testVocab/words.txt"
  22. VOCAB_FILE = "../data/dataset/testVocab/vocab_list.txt"
  23. SIMPLE_VOCAB_FILE = "../data/dataset/testVocab/simple_vocab_list.txt"
  24. def test_lookup_callable():
  25. """
  26. Test lookup is callable
  27. """
  28. logger.info("test_lookup_callable")
  29. vocab = text.Vocab.from_list(['深', '圳', '欢', '迎', '您'])
  30. lookup = text.Lookup(vocab)
  31. word = "迎"
  32. assert lookup(word) == 3
  33. def test_from_list_tutorial():
  34. vocab = text.Vocab.from_list("home IS behind the world ahead !".split(" "), ["<pad>", "<unk>"], True)
  35. lookup = text.Lookup(vocab, "<unk>")
  36. data = ds.TextFileDataset(DATA_FILE, shuffle=False)
  37. data = data.map(operations=lookup, input_columns=["text"])
  38. ind = 0
  39. res = [2, 1, 4, 5, 6, 7]
  40. for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  41. assert d["text"] == res[ind], ind
  42. ind += 1
  43. def test_from_file_tutorial():
  44. vocab = text.Vocab.from_file(VOCAB_FILE, ",", None, ["<pad>", "<unk>"], True)
  45. lookup = text.Lookup(vocab)
  46. data = ds.TextFileDataset(DATA_FILE, shuffle=False)
  47. data = data.map(operations=lookup, input_columns=["text"])
  48. ind = 0
  49. res = [10, 11, 12, 15, 13, 14]
  50. for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  51. assert d["text"] == res[ind], ind
  52. ind += 1
  53. def test_from_dict_tutorial():
  54. vocab = text.Vocab.from_dict({"home": 3, "behind": 2, "the": 4, "world": 5, "<unk>": 6})
  55. lookup = text.Lookup(vocab, "<unk>") # any unknown token will be mapped to the id of <unk>
  56. data = ds.TextFileDataset(DATA_FILE, shuffle=False)
  57. data = data.map(operations=lookup, input_columns=["text"])
  58. res = [3, 6, 2, 4, 5, 6]
  59. ind = 0
  60. for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  61. assert d["text"] == res[ind], ind
  62. ind += 1
  63. def test_from_dict_exception():
  64. try:
  65. vocab = text.Vocab.from_dict({"home": -1, "behind": 0})
  66. if not vocab:
  67. raise ValueError("Vocab is None")
  68. except ValueError as e:
  69. assert "is not within the required interval" in str(e)
  70. def test_from_list():
  71. def gen(texts):
  72. for word in texts.split(" "):
  73. yield (np.array(word, dtype='S'),)
  74. def test_config(lookup_str, vocab_input, special_tokens, special_first, unknown_token):
  75. try:
  76. vocab = text.Vocab.from_list(vocab_input, special_tokens, special_first)
  77. data = ds.GeneratorDataset(gen(lookup_str), column_names=["text"])
  78. data = data.map(operations=text.Lookup(vocab, unknown_token), input_columns=["text"])
  79. res = []
  80. for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  81. res.append(d["text"].item())
  82. return res
  83. except (ValueError, RuntimeError, TypeError) as e:
  84. return str(e)
  85. # test basic default config, special_token=None, unknown_token=None
  86. assert test_config("w1 w2 w3", ["w1", "w2", "w3"], None, True, None) == [0, 1, 2]
  87. # test normal operations
  88. assert test_config("w1 w2 w3 s1 s2 ephemeral", ["w1", "w2", "w3"], ["s1", "s2"], True, "s2") == [2, 3, 4, 0, 1, 1]
  89. assert test_config("w1 w2 w3 s1 s2", ["w1", "w2", "w3"], ["s1", "s2"], False, "s2") == [0, 1, 2, 3, 4]
  90. assert test_config("w3 w2 w1", ["w1", "w2", "w3"], None, True, "w1") == [2, 1, 0]
  91. assert test_config("w3 w2 w1", ["w1", "w2", "w3"], None, False, "w1") == [2, 1, 0]
  92. # test unknown token lookup
  93. assert test_config("w1 un1 w3 un2", ["w1", "w2", "w3"], ["<pad>", "<unk>"], True, "<unk>") == [2, 1, 4, 1]
  94. assert test_config("w1 un1 w3 un2", ["w1", "w2", "w3"], ["<pad>", "<unk>"], False, "<unk>") == [0, 4, 2, 4]
  95. # test exceptions
  96. assert "doesn't exist in vocab." in test_config("un1", ["w1"], [], False, "unk")
  97. assert "doesn't exist in vocab and no unknown token is specified." in test_config("un1", ["w1"], [], False, None)
  98. assert "doesn't exist in vocab" in test_config("un1", ["w1"], [], False, None)
  99. assert "word_list contains duplicate" in test_config("w1", ["w1", "w1"], [], True, "w1")
  100. assert "special_tokens contains duplicate" in test_config("w1", ["w1", "w2"], ["s1", "s1"], True, "w1")
  101. assert "special_tokens and word_list contain duplicate" in test_config("w1", ["w1", "w2"], ["s1", "w1"], True, "w1")
  102. assert "is not of type" in test_config("w1", ["w1", "w2"], ["s1"], True, 123)
  103. def test_from_list_lookup_empty_string():
  104. # "" is a valid word in vocab, which can be looked up by LookupOp
  105. vocab = text.Vocab.from_list("home IS behind the world ahead !".split(" "), ["<pad>", ""], True)
  106. lookup = text.Lookup(vocab, "")
  107. data = ds.TextFileDataset(DATA_FILE, shuffle=False)
  108. data = data.map(operations=lookup, input_columns=["text"])
  109. ind = 0
  110. res = [2, 1, 4, 5, 6, 7]
  111. for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  112. assert d["text"] == res[ind], ind
  113. ind += 1
  114. # unknown_token of LookUp is None, it will convert to std::nullopt in C++,
  115. # so it has nothing to do with "" in vocab and C++ will skip looking up unknown_token
  116. vocab = text.Vocab.from_list("home IS behind the world ahead !".split(" "), ["<pad>", ""], True)
  117. lookup = text.Lookup(vocab)
  118. data = ds.TextFileDataset(DATA_FILE, shuffle=False)
  119. data = data.map(operations=lookup, input_columns=["text"])
  120. try:
  121. for _ in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  122. pass
  123. except RuntimeError as e:
  124. assert "token: \"is\" doesn't exist in vocab and no unknown token is specified" in str(e)
  125. def test_from_file():
  126. def gen(texts):
  127. for word in texts.split(" "):
  128. yield (np.array(word, dtype='S'),)
  129. def test_config(lookup_str, vocab_size, special_tokens, special_first):
  130. try:
  131. vocab = text.Vocab.from_file(SIMPLE_VOCAB_FILE, vocab_size=vocab_size, special_tokens=special_tokens,
  132. special_first=special_first)
  133. data = ds.GeneratorDataset(gen(lookup_str), column_names=["text"])
  134. data = data.map(operations=text.Lookup(vocab, "s2"), input_columns=["text"])
  135. res = []
  136. for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  137. res.append(d["text"].item())
  138. return res
  139. except ValueError as e:
  140. return str(e)
  141. # test special tokens are prepended
  142. assert test_config("w1 w2 w3 s1 s2 s3", None, ["s1", "s2", "s3"], True) == [3, 4, 5, 0, 1, 2]
  143. # test special tokens are appended
  144. assert test_config("w1 w2 w3 s1 s2 s3", None, ["s1", "s2", "s3"], False) == [0, 1, 2, 8, 9, 10]
  145. # test special tokens are prepended when not all words in file are used
  146. assert test_config("w1 w2 w3 s1 s2 s3", 3, ["s1", "s2", "s3"], False) == [0, 1, 2, 3, 4, 5]
  147. # text exception special_words contains duplicate words
  148. assert "special_tokens contains duplicate" in test_config("w1", None, ["s1", "s1"], True)
  149. # test exception when vocab_size is negative
  150. assert "Input vocab_size must be greater than 0" in test_config("w1 w2", 0, [], True)
  151. assert "Input vocab_size must be greater than 0" in test_config("w1 w2", -1, [], True)
  152. def test_lookup_cast_type():
  153. def gen(texts):
  154. for word in texts.split(" "):
  155. yield (np.array(word, dtype='S'),)
  156. def test_config(lookup_str, data_type=None):
  157. try:
  158. vocab = text.Vocab.from_list(["w1", "w2", "w3"], special_tokens=["<unk>"], special_first=True)
  159. data = ds.GeneratorDataset(gen(lookup_str), column_names=["text"])
  160. # if data_type is None, test the default value of data_type
  161. op = text.Lookup(vocab, "<unk>") if data_type is None else text.Lookup(vocab, "<unk>", data_type)
  162. data = data.map(operations=op, input_columns=["text"])
  163. res = []
  164. for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):
  165. res.append(d["text"])
  166. return res[0].dtype
  167. except (ValueError, RuntimeError, TypeError) as e:
  168. return str(e)
  169. # test result is correct
  170. assert test_config("w1", mstype.int8) == np.dtype("int8")
  171. assert test_config("w2", mstype.int32) == np.dtype("int32")
  172. assert test_config("w3", mstype.int64) == np.dtype("int64")
  173. assert test_config("unk", mstype.float32) != np.dtype("int32")
  174. assert test_config("unk") == np.dtype("int32")
  175. # test exception, data_type isn't the correct type
  176. assert "tldr is not of type [<class 'mindspore._c_expression.typing.Type'>]" in test_config("unk", "tldr")
  177. assert "Lookup does not support a string to string mapping, data_type can only be numeric." in \
  178. test_config("w1", mstype.string)
  179. if __name__ == '__main__':
  180. test_lookup_callable()
  181. test_from_dict_exception()
  182. test_from_list_tutorial()
  183. test_from_file_tutorial()
  184. test_from_dict_tutorial()
  185. test_from_list()
  186. test_from_file()
  187. test_lookup_cast_type()