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.

lr_generator.py 1.9 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. """learning rate generator"""
  16. import math
  17. import numpy as np
  18. def get_lr(global_step, lr_init, lr_end, lr_max, warmup_epochs, total_epochs, steps_per_epoch):
  19. """
  20. generate learning rate array
  21. Args:
  22. global_step(int): total steps of the training
  23. lr_init(float): init learning rate
  24. lr_end(float): end learning rate
  25. lr_max(float): max learning rate
  26. warmup_epochs(int): number of warmup epochs
  27. total_epochs(int): total epoch of training
  28. steps_per_epoch(int): steps of one epoch
  29. Returns:
  30. np.array, learning rate array
  31. """
  32. lr_each_step = []
  33. total_steps = steps_per_epoch * total_epochs
  34. warmup_steps = steps_per_epoch * warmup_epochs
  35. for i in range(total_steps):
  36. if i < warmup_steps:
  37. lr = lr_init + (lr_max - lr_init) * i / warmup_steps
  38. else:
  39. lr = lr_end + \
  40. (lr_max - lr_end) * \
  41. (1. + math.cos(math.pi * (i - warmup_steps) / (total_steps - warmup_steps))) / 2.
  42. if lr < 0.0:
  43. lr = 0.0
  44. lr_each_step.append(lr)
  45. current_step = global_step
  46. lr_each_step = np.array(lr_each_step).astype(np.float32)
  47. learning_rate = lr_each_step[current_step:]
  48. return learning_rate