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

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