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.

train.py 4.4 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 convert_to_mindrecord
  23. from src.dataset import lstm_create_dataset
  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, CheckpointConfig, ModelCheckpoint, TimeMonitor
  28. from mindspore.train.serialization import load_param_into_net, load_checkpoint
  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="./",
  40. help='the path to save the checkpoint file.')
  41. parser.add_argument('--pre_trained', type=str, default=None,
  42. help='the pretrained checkpoint file path.')
  43. parser.add_argument('--device_target', type=str, default="GPU", choices=['GPU', 'CPU'],
  44. help='the target device to run, support "GPU", "CPU". Default: "GPU".')
  45. args = parser.parse_args()
  46. context.set_context(
  47. mode=context.GRAPH_MODE,
  48. save_graphs=False,
  49. device_target=args.device_target)
  50. if args.preprocess == "true":
  51. print("============== Starting Data Pre-processing ==============")
  52. convert_to_mindrecord(cfg.embed_size, args.aclimdb_path, args.preprocess_path, args.glove_path)
  53. embedding_table = np.loadtxt(os.path.join(args.preprocess_path, "weight.txt")).astype(np.float32)
  54. network = SentimentNet(vocab_size=embedding_table.shape[0],
  55. embed_size=cfg.embed_size,
  56. num_hiddens=cfg.num_hiddens,
  57. num_layers=cfg.num_layers,
  58. bidirectional=cfg.bidirectional,
  59. num_classes=cfg.num_classes,
  60. weight=Tensor(embedding_table),
  61. batch_size=cfg.batch_size)
  62. # pre_trained
  63. if args.pre_trained:
  64. load_param_into_net(network, load_checkpoint(args.pre_trained))
  65. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  66. opt = nn.Momentum(network.trainable_params(), cfg.learning_rate, cfg.momentum)
  67. loss_cb = LossMonitor()
  68. model = Model(network, loss, opt, {'acc': Accuracy()})
  69. print("============== Starting Training ==============")
  70. ds_train = lstm_create_dataset(args.preprocess_path, cfg.batch_size, 1)
  71. config_ck = CheckpointConfig(save_checkpoint_steps=cfg.save_checkpoint_steps,
  72. keep_checkpoint_max=cfg.keep_checkpoint_max)
  73. ckpoint_cb = ModelCheckpoint(prefix="lstm", directory=args.ckpt_path, config=config_ck)
  74. time_cb = TimeMonitor(data_size=ds_train.get_dataset_size())
  75. if args.device_target == "CPU":
  76. model.train(cfg.num_epochs, ds_train, callbacks=[time_cb, ckpoint_cb, loss_cb], dataset_sink_mode=False)
  77. else:
  78. model.train(cfg.num_epochs, ds_train, callbacks=[time_cb, ckpoint_cb, loss_cb])
  79. print("============== Training Success ==============")