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

5 years ago
5 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 lenet example ########################
  17. train lenet and get network model files(.ckpt) :
  18. python train.py --data_path /YourDataPath
  19. """
  20. import os
  21. import ast
  22. import argparse
  23. from src.config import mnist_cfg as cfg
  24. from src.dataset import create_dataset
  25. from src.lenet import LeNet5
  26. import mindspore.nn as nn
  27. from mindspore import context
  28. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor, TimeMonitor
  29. from mindspore.train import Model
  30. from mindspore.nn.metrics import Accuracy
  31. from mindspore.common import set_seed
  32. set_seed(1)
  33. if __name__ == "__main__":
  34. parser = argparse.ArgumentParser(description='MindSpore Lenet Example')
  35. parser.add_argument('--device_target', type=str, default="Ascend", choices=['Ascend', 'GPU', 'CPU'],
  36. help='device where the code will be implemented (default: Ascend)')
  37. parser.add_argument('--data_path', type=str, default="./Data",
  38. help='path where the dataset is saved')
  39. parser.add_argument('--ckpt_path', type=str, default="./ckpt", help='if is test, must provide\
  40. path where the trained ckpt file')
  41. parser.add_argument('--dataset_sink_mode', type=ast.literal_eval, default=True,
  42. help='dataset_sink_mode is False or True')
  43. args = parser.parse_args()
  44. context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target)
  45. ds_train = create_dataset(os.path.join(args.data_path, "train"),
  46. cfg.batch_size)
  47. if ds_train.get_dataset_size() == 0:
  48. raise ValueError("Please check dataset size > 0 and batch_size <= dataset size")
  49. network = LeNet5(cfg.num_classes)
  50. net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  51. net_opt = nn.Momentum(network.trainable_params(), cfg.lr, cfg.momentum)
  52. time_cb = TimeMonitor(data_size=ds_train.get_dataset_size())
  53. config_ck = CheckpointConfig(save_checkpoint_steps=cfg.save_checkpoint_steps,
  54. keep_checkpoint_max=cfg.keep_checkpoint_max)
  55. ckpoint_cb = ModelCheckpoint(prefix="checkpoint_lenet", directory=args.ckpt_path, config=config_ck)
  56. if args.device_target != "Ascend":
  57. model = Model(network, net_loss, net_opt, metrics={"Accuracy": Accuracy()})
  58. else:
  59. model = Model(network, net_loss, net_opt, metrics={"Accuracy": Accuracy()}, amp_level="O2")
  60. print("============== Starting Training ==============")
  61. model.train(cfg['epoch_size'], ds_train, callbacks=[time_cb, ckpoint_cb, LossMonitor()],
  62. dataset_sink_mode=args.dataset_sink_mode)