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

5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 vgg16 example on cifar10########################
  17. python train.py --data_path=$DATA_HOME --device_id=$DEVICE_ID
  18. """
  19. import argparse
  20. import random
  21. import numpy as np
  22. import mindspore.nn as nn
  23. from mindspore import Tensor
  24. from mindspore.nn.optim.momentum import Momentum
  25. from mindspore.train.model import Model
  26. from mindspore import context
  27. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor
  28. from mindspore.model_zoo.vgg import vgg16
  29. import dataset
  30. from config import cifar_cfg as cfg
  31. random.seed(1)
  32. np.random.seed(1)
  33. def lr_steps(global_step, lr_max=None, total_epochs=None, steps_per_epoch=None):
  34. """Set learning rate."""
  35. lr_each_step = []
  36. total_steps = steps_per_epoch * total_epochs
  37. decay_epoch_index = [0.3 * total_steps, 0.6 * total_steps, 0.8 * total_steps]
  38. for i in range(total_steps):
  39. if i < decay_epoch_index[0]:
  40. lr_each_step.append(lr_max)
  41. elif i < decay_epoch_index[1]:
  42. lr_each_step.append(lr_max * 0.1)
  43. elif i < decay_epoch_index[2]:
  44. lr_each_step.append(lr_max * 0.01)
  45. else:
  46. lr_each_step.append(lr_max * 0.001)
  47. current_step = global_step
  48. lr_each_step = np.array(lr_each_step).astype(np.float32)
  49. learning_rate = lr_each_step[current_step:]
  50. return learning_rate
  51. if __name__ == '__main__':
  52. parser = argparse.ArgumentParser(description='Cifar10 classification')
  53. parser.add_argument('--device_target', type=str, default='Ascend', choices=['Ascend', 'GPU'],
  54. help='device where the code will be implemented. (Default: Ascend)')
  55. parser.add_argument('--data_path', type=str, default='./cifar', help='path where the dataset is saved')
  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=args_opt.device_target)
  59. context.set_context(device_id=args_opt.device_id)
  60. context.set_context(enable_mem_reuse=True, enable_hccl=False)
  61. net = vgg16(num_classes=cfg.num_classes)
  62. lr = lr_steps(0, lr_max=cfg.lr_init, total_epochs=cfg.epoch_size, steps_per_epoch=50000 // cfg.batch_size)
  63. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), Tensor(lr), cfg.momentum, weight_decay=cfg.weight_decay)
  64. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean', is_grad=False)
  65. model = Model(net, loss_fn=loss, optimizer=opt, metrics={'acc'})
  66. dataset = dataset.create_dataset(args_opt.data_path, cfg.epoch_size)
  67. batch_num = dataset.get_dataset_size()
  68. config_ck = CheckpointConfig(save_checkpoint_steps=batch_num * 5, keep_checkpoint_max=cfg.keep_checkpoint_max)
  69. ckpoint_cb = ModelCheckpoint(prefix="train_vgg_cifar10", directory="./", config=config_ck)
  70. loss_cb = LossMonitor()
  71. model.train(cfg.epoch_size, dataset, callbacks=[ckpoint_cb, loss_cb])