|
| 1 | +from tensorflow.keras.callbacks import * |
| 2 | +from tensorflow.keras import backend as K |
| 3 | +import numpy as np |
| 4 | + |
| 5 | +class CyclicLR(Callback): |
| 6 | + """This callback implements a cyclical learning rate policy (CLR). |
| 7 | + The method cycles the learning rate between two boundaries with |
| 8 | + some constant frequency, as detailed in this paper (https://arxiv.org/abs/1506.01186). |
| 9 | + The amplitude of the cycle can be scaled on a per-iteration or |
| 10 | + per-cycle basis. |
| 11 | + This class has three built-in policies, as put forth in the paper. |
| 12 | + "triangular": |
| 13 | + A basic triangular cycle w/ no amplitude scaling. |
| 14 | + "triangular2": |
| 15 | + A basic triangular cycle that scales initial amplitude by half each cycle. |
| 16 | + "exp_range": |
| 17 | + A cycle that scales initial amplitude by gamma**(cycle iterations) at each |
| 18 | + cycle iteration. |
| 19 | + For more detail, please see paper. |
| 20 | + |
| 21 | + # Example |
| 22 | + ```python |
| 23 | + clr = CyclicLR(base_lr=0.001, max_lr=0.006, |
| 24 | + step_size=2000., mode='triangular') |
| 25 | + model.fit(X_train, Y_train, callbacks=[clr]) |
| 26 | + ``` |
| 27 | + |
| 28 | + Class also supports custom scaling functions: |
| 29 | + ```python |
| 30 | + clr_fn = lambda x: 0.5*(1+np.sin(x*np.pi/2.)) |
| 31 | + clr = CyclicLR(base_lr=0.001, max_lr=0.006, |
| 32 | + step_size=2000., scale_fn=clr_fn, |
| 33 | + scale_mode='cycle') |
| 34 | + model.fit(X_train, Y_train, callbacks=[clr]) |
| 35 | + ``` |
| 36 | + # Arguments |
| 37 | + base_lr: initial learning rate which is the |
| 38 | + lower boundary in the cycle. |
| 39 | + max_lr: upper boundary in the cycle. Functionally, |
| 40 | + it defines the cycle amplitude (max_lr - base_lr). |
| 41 | + The lr at any cycle is the sum of base_lr |
| 42 | + and some scaling of the amplitude; therefore |
| 43 | + max_lr may not actually be reached depending on |
| 44 | + scaling function. |
| 45 | + step_size: number of training iterations per |
| 46 | + half cycle. Authors suggest setting step_size |
| 47 | + 2-8 x training iterations in epoch. |
| 48 | + mode: one of {triangular, triangular2, exp_range}. |
| 49 | + Default 'triangular'. |
| 50 | + Values correspond to policies detailed above. |
| 51 | + If scale_fn is not None, this argument is ignored. |
| 52 | + gamma: constant in 'exp_range' scaling function: |
| 53 | + gamma**(cycle iterations) |
| 54 | + scale_fn: Custom scaling policy defined by a single |
| 55 | + argument lambda function, where |
| 56 | + 0 <= scale_fn(x) <= 1 for all x >= 0. |
| 57 | + mode paramater is ignored |
| 58 | + scale_mode: {'cycle', 'iterations'}. |
| 59 | + Defines whether scale_fn is evaluated on |
| 60 | + cycle number or cycle iterations (training |
| 61 | + iterations since start of cycle). Default is 'cycle'. |
| 62 | + """ |
| 63 | + |
| 64 | + def __init__(self, base_lr=0.001, max_lr=0.006, step_size=2000., mode='triangular', |
| 65 | + gamma=1., scale_fn=None, scale_mode='cycle'): |
| 66 | + super(CyclicLR, self).__init__() |
| 67 | + |
| 68 | + self.base_lr = base_lr |
| 69 | + self.max_lr = max_lr |
| 70 | + self.step_size = step_size |
| 71 | + self.mode = mode |
| 72 | + self.gamma = gamma |
| 73 | + if scale_fn == None: |
| 74 | + if self.mode == 'triangular': |
| 75 | + self.scale_fn = lambda x: 1. |
| 76 | + self.scale_mode = 'cycle' |
| 77 | + elif self.mode == 'triangular2': |
| 78 | + self.scale_fn = lambda x: 1/(2.**(x-1)) |
| 79 | + self.scale_mode = 'cycle' |
| 80 | + elif self.mode == 'exp_range': |
| 81 | + self.scale_fn = lambda x: gamma**(x) |
| 82 | + self.scale_mode = 'iterations' |
| 83 | + else: |
| 84 | + self.scale_fn = scale_fn |
| 85 | + self.scale_mode = scale_mode |
| 86 | + self.clr_iterations = 0. |
| 87 | + self.trn_iterations = 0. |
| 88 | + self.history = {} |
| 89 | + |
| 90 | + self._reset() |
| 91 | + |
| 92 | + def _reset(self, new_base_lr=None, new_max_lr=None, |
| 93 | + new_step_size=None): |
| 94 | + """Resets cycle iterations. |
| 95 | + Optional boundary/step size adjustment. |
| 96 | + """ |
| 97 | + if new_base_lr != None: |
| 98 | + self.base_lr = new_base_lr |
| 99 | + if new_max_lr != None: |
| 100 | + self.max_lr = new_max_lr |
| 101 | + if new_step_size != None: |
| 102 | + self.step_size = new_step_size |
| 103 | + self.clr_iterations = 0. |
| 104 | + |
| 105 | + def clr(self): |
| 106 | + cycle = np.floor(1+self.clr_iterations/(2*self.step_size)) |
| 107 | + x = np.abs(self.clr_iterations/self.step_size - 2*cycle + 1) |
| 108 | + if self.scale_mode == 'cycle': |
| 109 | + return self.base_lr + (self.max_lr-self.base_lr)*np.maximum(0, (1-x))*self.scale_fn(cycle) |
| 110 | + else: |
| 111 | + return self.base_lr + (self.max_lr-self.base_lr)*np.maximum(0, (1-x))*self.scale_fn(self.clr_iterations) |
| 112 | + |
| 113 | + def on_train_begin(self, logs={}): |
| 114 | + logs = logs or {} |
| 115 | + |
| 116 | + if self.clr_iterations == 0: |
| 117 | + K.set_value(self.model.optimizer.lr, self.base_lr) |
| 118 | + else: |
| 119 | + K.set_value(self.model.optimizer.lr, self.clr()) |
| 120 | + |
| 121 | + def on_batch_end(self, epoch, logs=None): |
| 122 | + |
| 123 | + logs = logs or {} |
| 124 | + self.trn_iterations += 1 |
| 125 | + self.clr_iterations += 1 |
| 126 | + |
| 127 | + self.history.setdefault('lr', []).append(K.get_value(self.model.optimizer.lr)) |
| 128 | + self.history.setdefault('iterations', []).append(self.trn_iterations) |
| 129 | + |
| 130 | + for k, v in logs.items(): |
| 131 | + self.history.setdefault(k, []).append(v) |
| 132 | + |
| 133 | + K.set_value(self.model.optimizer.lr, self.clr()) |
0 commit comments