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

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