-
Notifications
You must be signed in to change notification settings - Fork 0
/
annealing_lr.py
49 lines (35 loc) · 1.31 KB
/
annealing_lr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import abc
from math import exp
"""Classes for annealing learning rate schedules."""
class AnnealingSchedule(object):
def __init__(self, initial_lr, decay_rate, decay_step):
self.initial_lr = initial_lr
self.lr = initial_lr
self.k = decay_rate
self.decay_step = decay_step
self.global_step = 0
def __mul__(self, z):
self.global_step += 1
if (self.global_step % self.decay_step) == 0: self._anneal_lr()
return self.lr * z
def __rmul__(self, z):
return self.__mul__(z)
@abc.abstractmethod
def _anneal_lr(self):
"""Define your annealing schedule here."""
return
class InvScaling(AnnealingSchedule):
def __init__(self, initial_lr, decay_rate, decay_step=10):
super(InvScaling, self).__init__(initial_lr, decay_rate, decay_step)
def _anneal_lr(self):
self.lr = self.initial_lr / (1 + self.k * self.global_step)
class ExponentialDecay(AnnealingSchedule):
def __init__(self, initial_lr, decay_rate, decay_step=10):
super(ExponentialDecay, self).__init__(initial_lr, decay_rate, decay_step)
def _anneal_lr(self):
self.lr = self.initial_lr * exp(-self.k * self.global_step)
class StepDecay(AnnealingSchedule):
def __init__(self, initial_lr, decay_rate, decay_step=10):
super(StepDecay, self).__init__(initial_lr, decay_rate, decay_step)
def _anneal_lr(self):
self.lr = self.lr - self.decay_rate