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.

eval.py 2.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. """Evaluation api."""
  16. import argparse
  17. import pickle
  18. import numpy as np
  19. from mindspore.common import dtype as mstype
  20. from config import TransformerConfig
  21. from src.transformer import infer
  22. from src.utils import ngram_ppl
  23. from src.utils import Dictionary
  24. from src.utils import rouge
  25. parser = argparse.ArgumentParser(description='Evaluation MASS.')
  26. parser.add_argument("--config", type=str, required=True,
  27. help="Model config json file path.")
  28. parser.add_argument("--vocab", type=str, required=True,
  29. help="Vocabulary to use.")
  30. parser.add_argument("--output", type=str, required=True,
  31. help="Result file path.")
  32. def get_config(config):
  33. config = TransformerConfig.from_json_file(config)
  34. config.compute_type = mstype.float16
  35. config.dtype = mstype.float32
  36. return config
  37. if __name__ == '__main__':
  38. args, _ = parser.parse_known_args()
  39. vocab = Dictionary.load_from_persisted_dict(args.vocab)
  40. _config = get_config(args.config)
  41. result = infer(_config)
  42. with open(args.output, "wb") as f:
  43. pickle.dump(result, f, 1)
  44. ppl_score = 0.
  45. preds = []
  46. tgts = []
  47. _count = 0
  48. for sample in result:
  49. sentence_prob = np.array(sample['prediction_prob'], dtype=np.float32)
  50. sentence_prob = sentence_prob[:, 1:]
  51. _ppl = []
  52. for path in sentence_prob:
  53. _ppl.append(ngram_ppl(path, log_softmax=True))
  54. ppl = np.min(_ppl)
  55. preds.append(' '.join([vocab[t] for t in sample['prediction']]))
  56. tgts.append(' '.join([vocab[t] for t in sample['target']]))
  57. print(f" | source: {' '.join([vocab[t] for t in sample['source']])}")
  58. print(f" | target: {tgts[-1]}")
  59. print(f" | prediction: {preds[-1]}")
  60. print(f" | ppl: {ppl}.")
  61. if np.isinf(ppl):
  62. continue
  63. ppl_score += ppl
  64. _count += 1
  65. print(f" | PPL={ppl_score / _count}.")
  66. rouge(preds, tgts)