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

4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # Copyright 2021 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. """Transformer evaluation script."""
  16. import os
  17. import argparse
  18. import mindspore.common.dtype as mstype
  19. from mindspore.common.tensor import Tensor
  20. from mindspore.train.model import Model
  21. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  22. from mindspore import context
  23. from src.dataset import create_gru_dataset
  24. from src.seq2seq import Seq2Seq
  25. from src.gru_for_infer import GRUInferCell
  26. from src.config import config
  27. def run_gru_eval():
  28. """
  29. Transformer evaluation.
  30. """
  31. parser = argparse.ArgumentParser(description='GRU eval')
  32. parser.add_argument("--device_target", type=str, default="Ascend",
  33. help="device where the code will be implemented, default is Ascend")
  34. parser.add_argument('--device_id', type=int, default=0, help='device id of GPU or Ascend, default is 0')
  35. parser.add_argument('--device_num', type=int, default=1, help='Use device nums, default is 1')
  36. parser.add_argument('--ckpt_file', type=str, default="", help='ckpt file path')
  37. parser.add_argument("--dataset_path", type=str, default="",
  38. help="Dataset path, default: f`sns.")
  39. args = parser.parse_args()
  40. context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target, reserve_class_name_in_scope=False, \
  41. device_id=args.device_id, save_graphs=False)
  42. mindrecord_file = args.dataset_path
  43. if not os.path.exists(mindrecord_file):
  44. print("dataset file {} not exists, please check!".format(mindrecord_file))
  45. raise ValueError(mindrecord_file)
  46. dataset = create_gru_dataset(epoch_count=config.num_epochs, batch_size=config.eval_batch_size, \
  47. dataset_path=mindrecord_file, rank_size=args.device_num, rank_id=0, do_shuffle=False, is_training=False)
  48. dataset_size = dataset.get_dataset_size()
  49. print("dataset size is {}".format(dataset_size))
  50. network = Seq2Seq(config, is_training=False)
  51. network = GRUInferCell(network)
  52. network.set_train(False)
  53. if args.ckpt_file != "":
  54. parameter_dict = load_checkpoint(args.ckpt_file)
  55. load_param_into_net(network, parameter_dict)
  56. model = Model(network)
  57. predictions = []
  58. source_sents = []
  59. target_sents = []
  60. eval_text_len = 0
  61. for batch in dataset.create_dict_iterator(output_numpy=True, num_epochs=1):
  62. source_sents.append(batch["source_ids"])
  63. target_sents.append(batch["target_ids"])
  64. source_ids = Tensor(batch["source_ids"], mstype.int32)
  65. target_ids = Tensor(batch["target_ids"], mstype.int32)
  66. predicted_ids = model.predict(source_ids, target_ids)
  67. print("predicts is ", predicted_ids.asnumpy())
  68. print("target_ids is ", target_ids)
  69. predictions.append(predicted_ids.asnumpy())
  70. eval_text_len = eval_text_len + 1
  71. f_output = open(config.output_file, 'w')
  72. f_target = open(config.target_file, "w")
  73. for batch_out, true_sentence in zip(predictions, target_sents):
  74. for i in range(config.eval_batch_size):
  75. target_ids = [str(x) for x in true_sentence[i].tolist()]
  76. f_target.write(" ".join(target_ids) + "\n")
  77. token_ids = [str(x) for x in batch_out[i].tolist()]
  78. f_output.write(" ".join(token_ids) + "\n")
  79. f_output.close()
  80. f_target.close()
  81. if __name__ == "__main__":
  82. run_gru_eval()