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

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. #################train lstm example on aclImdb########################
  17. """
  18. import argparse
  19. import os
  20. import numpy as np
  21. from src.config import lstm_cfg, lstm_cfg_ascend
  22. from src.dataset import lstm_create_dataset, convert_to_mindrecord
  23. from src.lr_schedule import get_lr
  24. from src.lstm import SentimentNet
  25. from mindspore import Tensor, nn, Model, context
  26. from mindspore.nn import Accuracy
  27. from mindspore.train.callback import LossMonitor
  28. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  29. if __name__ == '__main__':
  30. parser = argparse.ArgumentParser(description='MindSpore LSTM Example')
  31. parser.add_argument('--preprocess', type=str, default='false', choices=['true', 'false'],
  32. help='whether to preprocess data.')
  33. parser.add_argument('--aclimdb_path', type=str, default="./aclImdb",
  34. help='path where the dataset is stored.')
  35. parser.add_argument('--glove_path', type=str, default="./glove",
  36. help='path where the GloVe is stored.')
  37. parser.add_argument('--preprocess_path', type=str, default="./preprocess",
  38. help='path where the pre-process data is stored.')
  39. parser.add_argument('--ckpt_path', type=str, default=None,
  40. help='the checkpoint file path used to evaluate model.')
  41. parser.add_argument('--device_target', type=str, default="Ascend", choices=['GPU', 'CPU', 'Ascend'],
  42. help='the target device to run, support "GPU", "CPU". Default: "Ascend".')
  43. args = parser.parse_args()
  44. context.set_context(
  45. mode=context.GRAPH_MODE,
  46. save_graphs=False,
  47. device_target=args.device_target)
  48. if args.device_target == 'Ascend':
  49. cfg = lstm_cfg_ascend
  50. else:
  51. cfg = lstm_cfg
  52. if args.preprocess == "true":
  53. print("============== Starting Data Pre-processing ==============")
  54. convert_to_mindrecord(cfg.embed_size, args.aclimdb_path, args.preprocess_path, args.glove_path)
  55. embedding_table = np.loadtxt(os.path.join(args.preprocess_path, "weight.txt")).astype(np.float32)
  56. # DynamicRNN in this network on Ascend platform only support the condition that the shape of input_size
  57. # and hiddle_size is multiples of 16, this problem will be solved later.
  58. if args.device_target == 'Ascend':
  59. pad_num = int(np.ceil(cfg.embed_size / 16) * 16 - cfg.embed_size)
  60. if pad_num > 0:
  61. embedding_table = np.pad(embedding_table, [(0, 0), (0, pad_num)], 'constant')
  62. cfg.embed_size = int(np.ceil(cfg.embed_size / 16) * 16)
  63. network = SentimentNet(vocab_size=embedding_table.shape[0],
  64. embed_size=cfg.embed_size,
  65. num_hiddens=cfg.num_hiddens,
  66. num_layers=cfg.num_layers,
  67. bidirectional=cfg.bidirectional,
  68. num_classes=cfg.num_classes,
  69. weight=Tensor(embedding_table),
  70. batch_size=cfg.batch_size)
  71. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  72. ds_eval = lstm_create_dataset(args.preprocess_path, cfg.batch_size, training=False)
  73. if cfg.dynamic_lr:
  74. lr = Tensor(get_lr(global_step=cfg.global_step,
  75. lr_init=cfg.lr_init, lr_end=cfg.lr_end, lr_max=cfg.lr_max,
  76. warmup_epochs=cfg.warmup_epochs,
  77. total_epochs=cfg.num_epochs,
  78. steps_per_epoch=ds_eval.get_dataset_size(),
  79. lr_adjust_epoch=cfg.lr_adjust_epoch))
  80. else:
  81. lr = cfg.learning_rate
  82. opt = nn.Momentum(network.trainable_params(), lr, cfg.momentum)
  83. loss_cb = LossMonitor()
  84. model = Model(network, loss, opt, {'acc': Accuracy()})
  85. print("============== Starting Testing ==============")
  86. param_dict = load_checkpoint(args.ckpt_path)
  87. load_param_into_net(network, param_dict)
  88. if args.device_target == "CPU":
  89. acc = model.eval(ds_eval, dataset_sink_mode=False)
  90. else:
  91. acc = model.eval(ds_eval)
  92. print("============== {} ==============".format(acc))