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.

models.py 5.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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. import time
  16. import numpy as np
  17. from mindspore import Tensor
  18. from mindspore import nn
  19. from mindspore.ops import operations as P
  20. from mindspore.ops import functional as F
  21. from mindspore.common import dtype as mstype
  22. from mindspore.nn.loss.loss import _Loss
  23. from mindspore.train.callback import Callback
  24. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  25. from src.mobilenetV2 import MobileNetV2Backbone, MobileNetV2Head, mobilenet_v2
  26. class CrossEntropyWithLabelSmooth(_Loss):
  27. """
  28. CrossEntropyWith LabelSmooth.
  29. Args:
  30. smooth_factor (float): smooth factor, default=0.
  31. num_classes (int): num classes
  32. Returns:
  33. None.
  34. Examples:
  35. >>> CrossEntropyWithLabelSmooth(smooth_factor=0., num_classes=1000)
  36. """
  37. def __init__(self, smooth_factor=0., num_classes=1000):
  38. super(CrossEntropyWithLabelSmooth, self).__init__()
  39. self.onehot = P.OneHot()
  40. self.on_value = Tensor(1.0 - smooth_factor, mstype.float32)
  41. self.off_value = Tensor(1.0 * smooth_factor /
  42. (num_classes - 1), mstype.float32)
  43. self.ce = nn.SoftmaxCrossEntropyWithLogits()
  44. self.mean = P.ReduceMean(False)
  45. self.cast = P.Cast()
  46. def construct(self, logit, label):
  47. one_hot_label = self.onehot(self.cast(label, mstype.int32), F.shape(logit)[1],
  48. self.on_value, self.off_value)
  49. out_loss = self.ce(logit, one_hot_label)
  50. out_loss = self.mean(out_loss, 0)
  51. return out_loss
  52. class Monitor(Callback):
  53. """
  54. Monitor loss and time.
  55. Args:
  56. lr_init (numpy array): train lr
  57. Returns:
  58. None
  59. Examples:
  60. >>> Monitor(100,lr_init=Tensor([0.05]*100).asnumpy())
  61. """
  62. def __init__(self, lr_init=None):
  63. super(Monitor, self).__init__()
  64. self.lr_init = lr_init
  65. self.lr_init_len = len(lr_init)
  66. def epoch_begin(self, run_context):
  67. self.losses = []
  68. self.epoch_time = time.time()
  69. def epoch_end(self, run_context):
  70. cb_params = run_context.original_args()
  71. epoch_mseconds = (time.time() - self.epoch_time) * 1000
  72. per_step_mseconds = epoch_mseconds / cb_params.batch_num
  73. print("epoch time: {:5.3f}, per step time: {:5.3f}, avg loss: {:5.3f}".format(epoch_mseconds,
  74. per_step_mseconds,
  75. np.mean(self.losses)))
  76. def step_begin(self, run_context):
  77. self.step_time = time.time()
  78. def step_end(self, run_context):
  79. cb_params = run_context.original_args()
  80. step_mseconds = (time.time() - self.step_time) * 1000
  81. step_loss = cb_params.net_outputs
  82. if isinstance(step_loss, (tuple, list)) and isinstance(step_loss[0], Tensor):
  83. step_loss = step_loss[0]
  84. if isinstance(step_loss, Tensor):
  85. step_loss = np.mean(step_loss.asnumpy())
  86. self.losses.append(step_loss)
  87. cur_step_in_epoch = (cb_params.cur_step_num - 1) % cb_params.batch_num
  88. print("epoch: [{:3d}/{:3d}], step:[{:5d}/{:5d}], loss:[{:5.3f}/{:5.3f}], time:[{:5.3f}], lr:[{:5.3f}]".format(
  89. cb_params.cur_epoch_num -
  90. 1, cb_params.epoch_num, cur_step_in_epoch, cb_params.batch_num, step_loss,
  91. np.mean(self.losses), step_mseconds, self.lr_init[cb_params.cur_step_num - 1]))
  92. def load_ckpt(network, pretrain_ckpt_path, trainable=True):
  93. """
  94. incremental_learning or not
  95. """
  96. param_dict = load_checkpoint(pretrain_ckpt_path)
  97. load_param_into_net(network, param_dict)
  98. if not trainable:
  99. for param in network.get_parameters():
  100. param.requires_grad = False
  101. def define_net(args, config):
  102. backbone_net = MobileNetV2Backbone(platform=args.platform)
  103. head_net = MobileNetV2Head(input_channel=backbone_net.out_channels, num_classes=config.num_classes)
  104. net = mobilenet_v2(backbone_net, head_net)
  105. # load the ckpt file to the network for fine tune or incremental leaning
  106. if args.pretrain_ckpt:
  107. if args.train_method == "fine_tune":
  108. load_ckpt(net, args.pretrain_ckpt)
  109. elif args.train_method == "incremental_learn":
  110. load_ckpt(backbone_net, args.pretrain_ckpt, trainable=False)
  111. elif args.train_method == "train":
  112. pass
  113. else:
  114. raise ValueError("must input the usage of pretrain_ckpt when the pretrain_ckpt isn't None")
  115. return backbone_net, head_net, net