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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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 googlent example on cifar10########################
  17. python train.py
  18. """
  19. import argparse
  20. import os
  21. import random
  22. import numpy as np
  23. import mindspore.nn as nn
  24. from mindspore import Tensor
  25. from mindspore import context
  26. from mindspore.communication.management import init
  27. from mindspore.nn.optim.momentum import Momentum
  28. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor, TimeMonitor
  29. from mindspore.train.model import Model, ParallelMode
  30. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  31. from src.config import cifar_cfg as cfg
  32. from src.dataset import create_dataset
  33. from src.googlenet import GoogleNet
  34. random.seed(1)
  35. np.random.seed(1)
  36. def lr_steps(global_step, lr_max=None, total_epochs=None, steps_per_epoch=None):
  37. """Set learning rate."""
  38. lr_each_step = []
  39. total_steps = steps_per_epoch * total_epochs
  40. decay_epoch_index = [0.3 * total_steps, 0.6 * total_steps, 0.8 * total_steps]
  41. for i in range(total_steps):
  42. if i < decay_epoch_index[0]:
  43. lr_each_step.append(lr_max)
  44. elif i < decay_epoch_index[1]:
  45. lr_each_step.append(lr_max * 0.1)
  46. elif i < decay_epoch_index[2]:
  47. lr_each_step.append(lr_max * 0.01)
  48. else:
  49. lr_each_step.append(lr_max * 0.001)
  50. current_step = global_step
  51. lr_each_step = np.array(lr_each_step).astype(np.float32)
  52. learning_rate = lr_each_step[current_step:]
  53. return learning_rate
  54. if __name__ == '__main__':
  55. parser = argparse.ArgumentParser(description='Cifar10 classification')
  56. parser.add_argument('--device_id', type=int, default=None, help='device id of GPU or Ascend. (Default: None)')
  57. args_opt = parser.parse_args()
  58. context.set_context(mode=context.GRAPH_MODE, device_target=cfg.device_target)
  59. if args_opt.device_id is not None:
  60. context.set_context(device_id=args_opt.device_id)
  61. else:
  62. context.set_context(device_id=cfg.device_id)
  63. device_num = int(os.environ.get("DEVICE_NUM", 1))
  64. if device_num > 1:
  65. context.reset_auto_parallel_context()
  66. context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode.DATA_PARALLEL,
  67. mirror_mean=True)
  68. init()
  69. dataset = create_dataset(cfg.data_path, 1)
  70. batch_num = dataset.get_dataset_size()
  71. net = GoogleNet(num_classes=cfg.num_classes)
  72. # Continue training if set pre_trained to be True
  73. if cfg.pre_trained:
  74. param_dict = load_checkpoint(cfg.checkpoint_path)
  75. load_param_into_net(net, param_dict)
  76. lr = lr_steps(0, lr_max=cfg.lr_init, total_epochs=cfg.epoch_size, steps_per_epoch=batch_num)
  77. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), Tensor(lr), cfg.momentum,
  78. weight_decay=cfg.weight_decay)
  79. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean', is_grad=False)
  80. model = Model(net, loss_fn=loss, optimizer=opt, metrics={'acc'},
  81. amp_level="O2", keep_batchnorm_fp32=False, loss_scale_manager=None)
  82. config_ck = CheckpointConfig(save_checkpoint_steps=batch_num * 5, keep_checkpoint_max=cfg.keep_checkpoint_max)
  83. time_cb = TimeMonitor(data_size=batch_num)
  84. ckpoint_cb = ModelCheckpoint(prefix="train_googlenet_cifar10", directory="./", config=config_ck)
  85. loss_cb = LossMonitor()
  86. model.train(cfg.epoch_size, dataset, callbacks=[time_cb, ckpoint_cb, loss_cb])
  87. print("train success")