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

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 textcnn example on movie review########################
  17. python train.py
  18. """
  19. import argparse
  20. import math
  21. import mindspore.nn as nn
  22. from mindspore.nn.metrics import Accuracy
  23. from mindspore import context
  24. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor, TimeMonitor
  25. from mindspore.train.model import Model
  26. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  27. from src.config import cfg_mr, cfg_subj, cfg_sst2
  28. from src.textcnn import TextCNN
  29. from src.textcnn import SoftmaxCrossEntropyExpand
  30. from src.dataset import MovieReview, SST2, Subjectivity
  31. parser = argparse.ArgumentParser(description='TextCNN')
  32. parser.add_argument('--device_target', type=str, default="Ascend", choices=['Ascend', 'GPU', 'CPU'],
  33. help='device where the code will be implemented (default: Ascend)')
  34. parser.add_argument('--device_id', type=int, default=5, help='device id of GPU or Ascend.')
  35. parser.add_argument('--dataset', type=str, default="MR", choices=['MR', 'SUBJ', 'SST2'])
  36. args_opt = parser.parse_args()
  37. if __name__ == '__main__':
  38. rank = 0
  39. # set context
  40. context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.device_target)
  41. context.set_context(device_id=args_opt.device_id)
  42. if args_opt.dataset == 'MR':
  43. cfg = cfg_mr
  44. instance = MovieReview(root_dir=cfg.data_path, maxlen=cfg.word_len, split=0.9)
  45. elif args_opt.dataset == 'SUBJ':
  46. cfg = cfg_subj
  47. instance = Subjectivity(root_dir=cfg.data_path, maxlen=cfg.word_len, split=0.9)
  48. elif args_opt.dataset == 'SST2':
  49. cfg = cfg_sst2
  50. instance = SST2(root_dir=cfg.data_path, maxlen=cfg.word_len, split=0.9)
  51. dataset = instance.create_train_dataset(batch_size=cfg.batch_size, epoch_size=cfg.epoch_size)
  52. batch_num = dataset.get_dataset_size()
  53. base_lr = cfg.base_lr
  54. learning_rate = []
  55. warm_up = [base_lr / math.floor(cfg.epoch_size / 5) * (i + 1) for _ in range(batch_num) for i in
  56. range(math.floor(cfg.epoch_size / 5))]
  57. shrink = [base_lr / (16 * (i + 1)) for _ in range(batch_num) for i in range(math.floor(cfg.epoch_size * 3 / 5))]
  58. normal_run = [base_lr for _ in range(batch_num) for i in
  59. range(cfg.epoch_size - math.floor(cfg.epoch_size / 5) - math.floor(cfg.epoch_size * 2 / 5))]
  60. learning_rate = learning_rate + warm_up + normal_run + shrink
  61. net = TextCNN(vocab_len=instance.get_dict_len(), word_len=cfg.word_len,
  62. num_classes=cfg.num_classes, vec_length=cfg.vec_length)
  63. # Continue training if set pre_trained to be True
  64. if cfg.pre_trained:
  65. param_dict = load_checkpoint(cfg.checkpoint_path)
  66. load_param_into_net(net, param_dict)
  67. opt = nn.Adam(filter(lambda x: x.requires_grad, net.get_parameters()), learning_rate=learning_rate, weight_decay=cfg.weight_decay)
  68. loss = SoftmaxCrossEntropyExpand(sparse=True)
  69. model = Model(net, loss_fn=loss, optimizer=opt, metrics={'acc': Accuracy()})
  70. config_ck = CheckpointConfig(save_checkpoint_steps=int(cfg.epoch_size*batch_num/2),
  71. keep_checkpoint_max=cfg.keep_checkpoint_max)
  72. time_cb = TimeMonitor(data_size=batch_num)
  73. ckpt_save_dir = "./ckpt_" + str(rank) + "/"
  74. ckpoint_cb = ModelCheckpoint(prefix="train_textcnn", directory=ckpt_save_dir, config=config_ck)
  75. loss_cb = LossMonitor()
  76. model.train(cfg.epoch_size, dataset, callbacks=[time_cb, ckpoint_cb, loss_cb])
  77. print("train success")