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_ngram_op.py 5.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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 Ngram 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_multiple_ngrams():
  22. """ test n-gram where n is a list of integers"""
  23. plates_mottos = ["WildRose Country", "Canada's Ocean Playground", "Land of Living Skies"]
  24. n_gram_mottos = []
  25. n_gram_mottos.append(
  26. ['WildRose', 'Country', '_ WildRose', 'WildRose Country', 'Country _', '_ _ WildRose', '_ WildRose Country',
  27. 'WildRose Country _', 'Country _ _'])
  28. n_gram_mottos.append(
  29. ["Canada's", 'Ocean', 'Playground', "_ Canada's", "Canada's Ocean", 'Ocean Playground', 'Playground _',
  30. "_ _ Canada's", "_ Canada's Ocean", "Canada's Ocean Playground", 'Ocean Playground _', 'Playground _ _'])
  31. n_gram_mottos.append(
  32. ['Land', 'of', 'Living', 'Skies', '_ Land', 'Land of', 'of Living', 'Living Skies', 'Skies _', '_ _ Land',
  33. '_ Land of', 'Land of Living', 'of Living Skies', 'Living Skies _', 'Skies _ _'])
  34. def gen(texts):
  35. for line in texts:
  36. yield (np.array(line.split(" "), dtype='S'),)
  37. dataset = ds.GeneratorDataset(gen(plates_mottos), column_names=["text"])
  38. dataset = dataset.map(input_columns=["text"], operations=text.Ngram([1, 2, 3], ("_", 2), ("_", 2), " "))
  39. i = 0
  40. for data in dataset.create_dict_iterator():
  41. assert [d.decode("utf8") for d in data["text"]] == n_gram_mottos[i]
  42. i += 1
  43. def test_simple_ngram():
  44. """ test simple gram with only one n value"""
  45. plates_mottos = ["Friendly Manitoba", "Yours to Discover", "Land of Living Skies",
  46. "Birthplace of the Confederation"]
  47. n_gram_mottos = [[""]]
  48. n_gram_mottos.append(["Yours to Discover"])
  49. n_gram_mottos.append(['Land of Living', 'of Living Skies'])
  50. n_gram_mottos.append(['Birthplace of the', 'of the Confederation'])
  51. def gen(texts):
  52. for line in texts:
  53. yield (np.array(line.split(" "), dtype='S'),)
  54. dataset = ds.GeneratorDataset(gen(plates_mottos), column_names=["text"])
  55. dataset = dataset.map(input_columns=["text"], operations=text.Ngram(3, separator=" "))
  56. i = 0
  57. for data in dataset.create_dict_iterator():
  58. assert [d.decode("utf8") for d in data["text"]] == n_gram_mottos[i], i
  59. i += 1
  60. def test_corner_cases():
  61. """ testing various corner cases and exceptions"""
  62. def test_config(input_line, n, l_pad=("", 0), r_pad=("", 0), sep=" "):
  63. def gen(texts):
  64. yield (np.array(texts.split(" "), dtype='S'),)
  65. try:
  66. dataset = ds.GeneratorDataset(gen(input_line), column_names=["text"])
  67. dataset = dataset.map(input_columns=["text"], operations=text.Ngram(n, l_pad, r_pad, separator=sep))
  68. for data in dataset.create_dict_iterator():
  69. return [d.decode("utf8") for d in data["text"]]
  70. except (ValueError, TypeError) as e:
  71. return str(e)
  72. # test tensor length smaller than n
  73. assert test_config("Lone Star", [2, 3, 4, 5]) == ["Lone Star", "", "", ""]
  74. # test empty separator
  75. assert test_config("Beautiful British Columbia", 2, sep="") == ['BeautifulBritish', 'BritishColumbia']
  76. # test separator with longer length
  77. assert test_config("Beautiful British Columbia", 3, sep="^-^") == ['Beautiful^-^British^-^Columbia']
  78. # test left pad != right pad
  79. assert test_config("Lone Star", 4, ("The", 1), ("State", 1)) == ['The Lone Star State']
  80. # test invalid n
  81. assert "gram[1] with value [1] is not of type (<class 'int'>,)" in test_config("Yours to Discover", [1, [1]])
  82. assert "n needs to be a non-empty list" in test_config("Yours to Discover", [])
  83. # test invalid pad
  84. assert "padding width need to be positive numbers" in test_config("Yours to Discover", [1], ("str", -1))
  85. assert "pad needs to be a tuple of (str, int)" in test_config("Yours to Discover", [1], ("str", "rts"))
  86. # test 0 as in valid input
  87. assert "gram_0 must be greater than 0" in test_config("Yours to Discover", 0)
  88. assert "gram_0 must be greater than 0" in test_config("Yours to Discover", [0])
  89. assert "gram_1 must be greater than 0" in test_config("Yours to Discover", [1, 0])
  90. if __name__ == '__main__':
  91. test_multiple_ngrams()
  92. test_simple_ngram()
  93. test_corner_cases()