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

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