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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 as cfg
  22. from src.dataset import lstm_create_dataset, convert_to_mindrecord
  23. from src.lstm import SentimentNet
  24. from mindspore import Tensor, nn, Model, context
  25. from mindspore.nn import Accuracy
  26. from mindspore.train.callback import LossMonitor
  27. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  28. if __name__ == '__main__':
  29. parser = argparse.ArgumentParser(description='MindSpore LSTM Example')
  30. parser.add_argument('--preprocess', type=str, default='false', choices=['true', 'false'],
  31. help='whether to preprocess data.')
  32. parser.add_argument('--aclimdb_path', type=str, default="./aclImdb",
  33. help='path where the dataset is stored.')
  34. parser.add_argument('--glove_path', type=str, default="./glove",
  35. help='path where the GloVe is stored.')
  36. parser.add_argument('--preprocess_path', type=str, default="./preprocess",
  37. help='path where the pre-process data is stored.')
  38. parser.add_argument('--ckpt_path', type=str, default=None,
  39. help='the checkpoint file path used to evaluate model.')
  40. parser.add_argument('--device_target', type=str, default="GPU", choices=['GPU', 'CPU'],
  41. help='the target device to run, support "GPU", "CPU". Default: "GPU".')
  42. args = parser.parse_args()
  43. context.set_context(
  44. mode=context.GRAPH_MODE,
  45. save_graphs=False,
  46. device_target=args.device_target)
  47. if args.preprocess == "true":
  48. print("============== Starting Data Pre-processing ==============")
  49. convert_to_mindrecord(cfg.embed_size, args.aclimdb_path, args.preprocess_path, args.glove_path)
  50. embedding_table = np.loadtxt(os.path.join(args.preprocess_path, "weight.txt")).astype(np.float32)
  51. network = SentimentNet(vocab_size=embedding_table.shape[0],
  52. embed_size=cfg.embed_size,
  53. num_hiddens=cfg.num_hiddens,
  54. num_layers=cfg.num_layers,
  55. bidirectional=cfg.bidirectional,
  56. num_classes=cfg.num_classes,
  57. weight=Tensor(embedding_table),
  58. batch_size=cfg.batch_size)
  59. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  60. opt = nn.Momentum(network.trainable_params(), cfg.learning_rate, cfg.momentum)
  61. loss_cb = LossMonitor()
  62. model = Model(network, loss, opt, {'acc': Accuracy()})
  63. print("============== Starting Testing ==============")
  64. ds_eval = lstm_create_dataset(args.preprocess_path, cfg.batch_size, training=False)
  65. param_dict = load_checkpoint(args.ckpt_path)
  66. load_param_into_net(network, param_dict)
  67. if args.device_target == "CPU":
  68. acc = model.eval(ds_eval, dataset_sink_mode=False)
  69. else:
  70. acc = model.eval(ds_eval)
  71. print("============== {} ==============".format(acc))