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_from_dataset.py 6.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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. """
  16. Testing from_dataset in mindspore.dataset
  17. """
  18. import numpy as np
  19. import mindspore.dataset as ds
  20. import mindspore.dataset.text as text
  21. def test_demo_basic_from_dataset():
  22. """ this is a tutorial on how from_dataset should be used in a normal use case"""
  23. data = ds.TextFileDataset("../data/dataset/testVocab/words.txt", shuffle=False)
  24. vocab = text.Vocab.from_dataset(data, "text", freq_range=None, top_k=None, special_tokens=["<pad>", "<unk>"],
  25. special_first=True)
  26. data = data.map(input_columns=["text"], operations=text.Lookup(vocab))
  27. res = []
  28. for d in data.create_dict_iterator():
  29. res.append(d["text"].item())
  30. assert res == [4, 5, 3, 6, 7, 2], res
  31. def test_demo_basic_from_dataset_with_tokenizer():
  32. """ this is a tutorial on how from_dataset should be used in a normal use case with tokenizer"""
  33. data = ds.TextFileDataset("../data/dataset/testTokenizerData/1.txt", shuffle=False)
  34. data = data.map(input_columns=["text"], operations=text.UnicodeCharTokenizer())
  35. vocab = text.Vocab.from_dataset(data, None, freq_range=None, top_k=None, special_tokens=["<pad>", "<unk>"],
  36. special_first=True)
  37. data = data.map(input_columns=["text"], operations=text.Lookup(vocab))
  38. res = []
  39. for d in data.create_dict_iterator():
  40. res.append(list(d["text"]))
  41. assert res == [[13, 3, 7, 14, 9, 17, 3, 2, 19, 9, 2, 11, 3, 4, 16, 4, 8, 6, 5], [21, 20, 10, 25, 23, 26],
  42. [24, 22, 10, 12, 8, 6, 7, 4, 18, 15, 5], [2, 2]]
  43. def test_from_dataset():
  44. """ test build vocab with generator dataset """
  45. def gen_corpus():
  46. # key: word, value: number of occurrences, reason for using letters is so their order is apparent
  47. corpus = {"Z": 4, "Y": 4, "X": 4, "W": 3, "U": 3, "V": 2, "T": 1}
  48. for k, v in corpus.items():
  49. yield (np.array([k] * v, dtype='S'),)
  50. def test_config(freq_range, top_k):
  51. corpus_dataset = ds.GeneratorDataset(gen_corpus, column_names=["text"])
  52. vocab = text.Vocab.from_dataset(corpus_dataset, None, freq_range, top_k, special_tokens=["<pad>", "<unk>"],
  53. special_first=True)
  54. corpus_dataset = corpus_dataset.map(input_columns="text", operations=text.Lookup(vocab))
  55. res = []
  56. for d in corpus_dataset.create_dict_iterator():
  57. res.append(list(d["text"]))
  58. return res
  59. # take words whose frequency is with in [3,4] order them alphabetically for words with the same frequency
  60. test1_res = test_config(freq_range=(3, 4), top_k=4)
  61. assert test1_res == [[4, 4, 4, 4], [3, 3, 3, 3], [2, 2, 2, 2], [1, 1, 1], [5, 5, 5], [1, 1], [1]], str(test1_res)
  62. # test words with frequency range [2,inf], only the last word will be filtered out
  63. test2_res = test_config((2, None), None)
  64. assert test2_res == [[4, 4, 4, 4], [3, 3, 3, 3], [2, 2, 2, 2], [6, 6, 6], [5, 5, 5], [7, 7], [1]], str(test2_res)
  65. # test filter only by top_k
  66. test3_res = test_config(None, 4)
  67. assert test3_res == [[4, 4, 4, 4], [3, 3, 3, 3], [2, 2, 2, 2], [1, 1, 1], [5, 5, 5], [1, 1], [1]], str(test3_res)
  68. # test filtering out the most frequent
  69. test4_res = test_config((None, 3), 100)
  70. assert test4_res == [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [3, 3, 3], [2, 2, 2], [4, 4], [5]], str(test4_res)
  71. # test top_k == 1
  72. test5_res = test_config(None, 1)
  73. assert test5_res == [[1, 1, 1, 1], [1, 1, 1, 1], [2, 2, 2, 2], [1, 1, 1], [1, 1, 1], [1, 1], [1]], str(test5_res)
  74. # test min_frequency == max_frequency
  75. test6_res = test_config((4, 4), None)
  76. assert test6_res == [[4, 4, 4, 4], [3, 3, 3, 3], [2, 2, 2, 2], [1, 1, 1], [1, 1, 1], [1, 1], [1]], str(test6_res)
  77. def test_from_dataset_special_token():
  78. """ test build vocab with generator dataset """
  79. def gen_corpus():
  80. # key: word, value: number of occurrences, reason for using letters is so their order is apparent
  81. corpus = {"D": 1, "C": 1, "B": 1, "A": 1}
  82. for k, v in corpus.items():
  83. yield (np.array([k] * v, dtype='S'),)
  84. def gen_input(texts):
  85. for word in texts.split(" "):
  86. yield (np.array(word, dtype='S'),)
  87. def test_config(texts, top_k, special_tokens, special_first):
  88. corpus_dataset = ds.GeneratorDataset(gen_corpus, column_names=["text"])
  89. vocab = text.Vocab.from_dataset(corpus_dataset, None, None, top_k, special_tokens, special_first)
  90. data = ds.GeneratorDataset(gen_input(texts), column_names=["text"])
  91. data = data.map(input_columns="text", operations=text.Lookup(vocab))
  92. res = []
  93. for d in data.create_dict_iterator():
  94. res.append(d["text"].item())
  95. return res
  96. # test special tokens are inserted before
  97. assert test_config("A B C D <pad> <unk>", 4, ["<pad>", "<unk>"], True) == [2, 3, 4, 5, 0, 1]
  98. # test special tokens are inserted after
  99. assert test_config("A B C D <pad> <unk>", 4, ["<pad>", "<unk>"], False) == [0, 1, 2, 3, 4, 5]
  100. def test_from_dataset_exceptions():
  101. """ test various exceptions during that are checked in validator """
  102. def test_config(columns, freq_range, top_k, s):
  103. try:
  104. data = ds.TextFileDataset("../data/dataset/testVocab/words.txt", shuffle=False)
  105. vocab = text.Vocab.from_dataset(data, columns, freq_range, top_k)
  106. assert isinstance(vocab.text.Vocab)
  107. except ValueError as e:
  108. assert s in str(e), str(e)
  109. test_config("text", (), 1, "freq_range needs to be either None or a tuple of 2 integers")
  110. test_config("text", (2, 3), 1.2345, "top_k needs to be a positive integer")
  111. test_config(23, (2, 3), 1.2345, "columns need to be a list of strings")
  112. test_config("text", (100, 1), 12, "frequency range [a,b] should be 0 <= a <= b")
  113. test_config("text", (2, 3), 0, "top_k needs to be a positive integer")
  114. test_config([123], (2, 3), 0, "columns need to be a list of strings")
  115. if __name__ == '__main__':
  116. test_demo_basic_from_dataset()
  117. test_from_dataset()
  118. test_from_dataset_exceptions()
  119. test_demo_basic_from_dataset_with_tokenizer()
  120. test_from_dataset_special_token()