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.5 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. """model evaluation script"""
  16. import os
  17. import argparse
  18. import numpy as np
  19. import mindspore.nn as nn
  20. import mindspore.context as context
  21. from mindspore import Tensor
  22. from mindspore.train import Model
  23. from mindspore.nn.metrics import Accuracy
  24. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  25. from mindspore.train.callback import LossMonitor
  26. from mindspore.common import set_seed
  27. from src.config import textrcnn_cfg as cfg
  28. from src.dataset import create_dataset
  29. from src.textrcnn import textrcnn
  30. set_seed(1)
  31. if __name__ == '__main__':
  32. parser = argparse.ArgumentParser(description='textrcnn')
  33. parser.add_argument('--ckpt_path', type=str)
  34. args = parser.parse_args()
  35. context.set_context(
  36. mode=context.GRAPH_MODE,
  37. save_graphs=False,
  38. device_target="Ascend")
  39. device_id = int(os.getenv('DEVICE_ID'))
  40. context.set_context(device_id=device_id)
  41. embedding_table = np.loadtxt(os.path.join(cfg.preprocess_path, "weight.txt")).astype(np.float32)
  42. network = textrcnn(weight=Tensor(embedding_table), vocab_size=embedding_table.shape[0], \
  43. cell=cfg.cell, batch_size=cfg.batch_size)
  44. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True)
  45. opt = nn.Momentum(network.trainable_params(), cfg.lr, cfg.momentum)
  46. loss_cb = LossMonitor()
  47. print("============== Starting Testing ==============")
  48. ds_eval = create_dataset(cfg.preprocess_path, cfg.batch_size, 1, False)
  49. param_dict = load_checkpoint(args.ckpt_path)
  50. load_param_into_net(network, param_dict)
  51. network.set_train(False)
  52. model = Model(network, loss, opt, metrics={'acc': Accuracy()}, amp_level='O3')
  53. acc = model.eval(ds_eval, dataset_sink_mode=False)
  54. print("============== Accuracy:{} ==============".format(acc))