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

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