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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. python train.py --preprocess=true --aclimdb_path=your_imdb_path --glove_path=your_glove_path
  18. """
  19. import argparse
  20. import os
  21. import numpy as np
  22. from src.config import lstm_cfg as cfg
  23. from src.dataset import convert_to_mindrecord
  24. from src.dataset import lstm_create_dataset
  25. from src.lstm import SentimentNet
  26. from mindspore import Tensor, nn, Model, context
  27. from mindspore.nn import Accuracy
  28. from mindspore.train.callback import LossMonitor, CheckpointConfig, ModelCheckpoint, TimeMonitor
  29. from mindspore.train.serialization import load_param_into_net, load_checkpoint
  30. if __name__ == '__main__':
  31. parser = argparse.ArgumentParser(description='MindSpore LSTM Example')
  32. parser.add_argument('--preprocess', type=str, default='false', choices=['true', 'false'],
  33. help='whether to preprocess data.')
  34. parser.add_argument('--aclimdb_path', type=str, default="./aclImdb",
  35. help='path where the dataset is stored.')
  36. parser.add_argument('--glove_path', type=str, default="./glove",
  37. help='path where the GloVe is stored.')
  38. parser.add_argument('--preprocess_path', type=str, default="./preprocess",
  39. help='path where the pre-process data is stored.')
  40. parser.add_argument('--ckpt_path', type=str, default="./",
  41. help='the path to save the checkpoint file.')
  42. parser.add_argument('--pre_trained', type=str, default=None,
  43. help='the pretrained checkpoint file path.')
  44. parser.add_argument('--device_target', type=str, default="GPU", choices=['GPU', 'CPU'],
  45. help='the target device to run, support "GPU", "CPU". Default: "GPU".')
  46. args = parser.parse_args()
  47. context.set_context(
  48. mode=context.GRAPH_MODE,
  49. save_graphs=False,
  50. device_target=args.device_target)
  51. if args.preprocess == "true":
  52. print("============== Starting Data Pre-processing ==============")
  53. convert_to_mindrecord(cfg.embed_size, args.aclimdb_path, args.preprocess_path, args.glove_path)
  54. embedding_table = np.loadtxt(os.path.join(args.preprocess_path, "weight.txt")).astype(np.float32)
  55. network = SentimentNet(vocab_size=embedding_table.shape[0],
  56. embed_size=cfg.embed_size,
  57. num_hiddens=cfg.num_hiddens,
  58. num_layers=cfg.num_layers,
  59. bidirectional=cfg.bidirectional,
  60. num_classes=cfg.num_classes,
  61. weight=Tensor(embedding_table),
  62. batch_size=cfg.batch_size)
  63. # pre_trained
  64. if args.pre_trained:
  65. load_param_into_net(network, load_checkpoint(args.pre_trained))
  66. loss = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True)
  67. opt = nn.Momentum(network.trainable_params(), cfg.learning_rate, cfg.momentum)
  68. loss_cb = LossMonitor()
  69. model = Model(network, loss, opt, {'acc': Accuracy()})
  70. print("============== Starting Training ==============")
  71. ds_train = lstm_create_dataset(args.preprocess_path, cfg.batch_size, 1)
  72. config_ck = CheckpointConfig(save_checkpoint_steps=cfg.save_checkpoint_steps,
  73. keep_checkpoint_max=cfg.keep_checkpoint_max)
  74. ckpoint_cb = ModelCheckpoint(prefix="lstm", directory=args.ckpt_path, config=config_ck)
  75. time_cb = TimeMonitor(data_size=ds_train.get_dataset_size())
  76. if args.device_target == "CPU":
  77. model.train(cfg.num_epochs, ds_train, callbacks=[time_cb, ckpoint_cb, loss_cb], dataset_sink_mode=False)
  78. else:
  79. model.train(cfg.num_epochs, ds_train, callbacks=[time_cb, ckpoint_cb, loss_cb])
  80. print("============== Training Success ==============")