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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. """model train script"""
  16. import os
  17. import shutil
  18. import numpy as np
  19. import mindspore.nn as nn
  20. import mindspore.context as context
  21. from mindspore import Tensor
  22. from mindspore.train import Model
  23. from mindspore.nn.metrics import Accuracy
  24. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor
  25. from mindspore.common import set_seed
  26. from src.config import textrcnn_cfg as cfg
  27. from src.dataset import create_dataset
  28. from src.dataset import convert_to_mindrecord
  29. from src.textrcnn import textrcnn
  30. from src.utils import get_lr
  31. set_seed(1)
  32. if __name__ == '__main__':
  33. context.set_context(
  34. mode=context.GRAPH_MODE,
  35. save_graphs=False,
  36. device_target="Ascend")
  37. device_id = int(os.getenv('DEVICE_ID'))
  38. context.set_context(device_id=device_id)
  39. if cfg.preprocess == 'true':
  40. print("============== Starting Data Pre-processing ==============")
  41. if os.path.exists(cfg.preprocess_path):
  42. shutil.rmtree(cfg.preprocess_path)
  43. os.mkdir(cfg.preprocess_path)
  44. convert_to_mindrecord(cfg.embed_size, cfg.data_path, cfg.preprocess_path, cfg.emb_path)
  45. if cfg.cell == "vanilla":
  46. print("============ Precision is lower than expected when using vanilla RNN architecture ===========")
  47. embedding_table = np.loadtxt(os.path.join(cfg.preprocess_path, "weight.txt")).astype(np.float32)
  48. network = textrcnn(weight=Tensor(embedding_table), vocab_size=embedding_table.shape[0], \
  49. cell=cfg.cell, batch_size=cfg.batch_size)
  50. ds_train = create_dataset(cfg.preprocess_path, cfg.batch_size, cfg.num_epochs, True)
  51. step_size = ds_train.get_dataset_size()
  52. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True)
  53. lr = get_lr(cfg, step_size)
  54. if cfg.opt == "adam":
  55. opt = nn.Adam(params=network.trainable_params(), learning_rate=lr)
  56. elif cfg.opt == "momentum":
  57. opt = nn.Momentum(network.trainable_params(), lr, cfg.momentum)
  58. loss_cb = LossMonitor()
  59. model = Model(network, loss, opt, {'acc': Accuracy()}, amp_level="O3")
  60. print("============== Starting Training ==============")
  61. config_ck = CheckpointConfig(save_checkpoint_steps=cfg.save_checkpoint_steps, \
  62. keep_checkpoint_max=cfg.keep_checkpoint_max)
  63. ckpoint_cb = ModelCheckpoint(prefix=cfg.cell, directory=cfg.ckpt_folder_path, config=config_ck)
  64. model.train(cfg.num_epochs, ds_train, callbacks=[ckpoint_cb, loss_cb])
  65. print("train success")