-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprototypeAOCP.py
More file actions
358 lines (260 loc) · 14.9 KB
/
prototypeAOCP.py
File metadata and controls
358 lines (260 loc) · 14.9 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
from keras.callbacks import *
class CyclicLR(Callback):
def __init__(self,
batches_per_epoch,
epoch_per_cycle = 2,
smoothing_factor = 5,
lr_min = -10.0,
lr_max = 0.0,
lr_depth = 10,
lr_decay=0.95,
momentum_depth = 1.25,
clipnorm_multiple = 5.0,
decay_hyper_params = True,
default_searching_clip = True,
default_searching_momentum = True,
default_searching_decay = True
):
super(CyclicLR, self).__init__()
self.batches_per_epoch = batches_per_epoch
self.epoch_per_cycle = epoch_per_cycle
self.smoothing_factor = smoothing_factor
self.lr_min = lr_min
self.lr_max = lr_max
self.lr_depth = lr_depth
self.lr_decay = lr_decay
self.momentum_depth = momentum_depth
self.clipnorm_multiple = clipnorm_multiple
self.decay_hyper_params = decay_hyper_params
self.default_searching_clip = default_searching_clip
self.default_searching_momentum = default_searching_momentum
self.default_searching_decay = default_searching_decay
def _reset(self):
self.base_lr = 0.0
self.max_lr = 1.0
self.base_clipnorm = 1.0
self.base_momentum = 1.0
self.min_momentum = 0.50
self.base_decay = 0.0
self.rate_schedule = []
self.clipnorm_schedule = []
self.momentum_schedule = []
self.decay_schedule = []
self.ascending = False
self.loss_history = []
self.epoch_loss_history = []
self.lr_history = []
self.clipnorm_history = []
self.momentum_history = []
self.decay_history = []
# redo finding the optimum values
self.find_all()
def find_all(self):
# set to begin searching values
self.searching = True
# All optomizers have LR and ClipNorm as values
self.searching_lr = True
self.searching_clip = self.default_searching_clip
# check if it has a momentum
if hasattr(self.model.optimizer, 'momentum'):
self.searching_momentum = self.default_searching_momentum
else:
self.searching_momentum = False
# check if it has a decay
if hasattr(self.model.optimizer, 'decay'):
self.searching_decay = self.default_searching_decay
else:
self.searching_decay = False
self.find_lr()
def find_lr(self):
# create an x value for each batch
xes = np.linspace(self.lr_min, self.lr_max, self.batches_per_epoch)
# increases the learning rate exponentially as we search for the best value
self.rate_schedule = []
for i in range(self.batches_per_epoch):
self.rate_schedule.append( math.exp( xes[i] ) )
# set defaults for searching
K.set_value(self.model.optimizer.lr, np.float32(self.rate_schedule[0]))
self.model.optimizer.clipnorm = np.float32(1.0)
if hasattr(self.model.optimizer, 'momentum'):
K.set_value(self.model.optimizer.momentum, np.float32(0.50))
if hasattr(self.model.optimizer, 'decay'):
K.set_value(self.model.optimizer.decay, np.float32(0.0))
def find_clipnorm(self):
# create an x value for each batch
xes = np.linspace(0.0, 1.0, self.batches_per_epoch)
# increase the clipnorm at a rate of x^e between 0.5 and 1.5
self.clipnorm_schedule = []
for i in range(self.batches_per_epoch):
self.clipnorm_schedule.append( self.clipnorm_multiple * ( xes[i] ** math.e ) )
# set defaults for searching
K.set_value(self.model.optimizer.lr, np.float32(self.max_lr)) # use the largest LR
self.model.optimizer.clipnorm = np.float32(self.clipnorm_schedule[0])
if hasattr(self.model.optimizer, 'momentum'):
K.set_value(self.model.optimizer.momentum, np.float32(0.50))
if hasattr(self.model.optimizer, 'decay'):
K.set_value(self.model.optimizer.decay, np.float32(0.0))
def find_momentum(self):
# create an x value for each batch
xes = np.linspace(0.0, 1.0, self.batches_per_epoch)
# increase the momentum at a rate of x^e between 0.0 and 1.0
self.momentum_schedule = []
for i in range(self.batches_per_epoch):
self.momentum_schedule.append( xes ) # ( xes[i] ** math.e ) )
# set defaults for searching
K.set_value(self.model.optimizer.lr, np.float32(self.base_lr)) # use the min LR
self.model.optimizer.clipnorm = np.float32(self.base_clipnorm)
if hasattr(self.model.optimizer, 'momentum'):
K.set_value(self.model.optimizer.momentum, np.float32(self.momentum_schedule[0]))
if hasattr(self.model.optimizer, 'decay'):
K.set_value(self.model.optimizer.decay, np.float32(0.0))
def find_decay(self):
# create an x value for each batch
xes = np.linspace(0.0, 1.0, self.batches_per_epoch)
# increase the momentum at a rate of x^e between 0.0 and 1.0
self.decay_schedule = []
for i in range(self.batches_per_epoch):
self.decay_schedule.append( ( xes[i] ** math.e ) )
# set defaults for searching
K.set_value(self.model.optimizer.lr, np.float32(self.base_lr)) # use the min LR
self.model.optimizer.clipnorm = np.float32(self.base_clipnorm)
if hasattr(self.model.optimizer, 'momentum'):
K.set_value(self.model.optimizer.momentum, np.float32(self.base_momentum))
if hasattr(self.model.optimizer, 'decay'):
K.set_value(self.model.optimizer.decay, np.float32(self.decay_schedule[0]))
def on_train_begin(self, logs={}):
logs = logs or {}
self.iteration = 0
self._reset()
def on_epoch_end( self , epoch, logs = {}):
logs = logs or {}
loss = np.float32(logs.get('loss'))
self.iteration = 0
# if we are in the first few epochs where we're searching for the best values
if self.searching:
if(self.searching_lr):
# we've finished searching LR, compile the results and move on
self.searching_lr = False
# smooth the data, each batch can have a lot of noise, get the lowest loss once smoothed and use that value
smoothed = scipy.signal.medfilt(self.epoch_loss_history, self.smoothing_factor)
index_of_best = np.argmin(smoothed)
best_lr = self.rate_schedule[index_of_best] / 2.0 # since LR lags, just assume it should be lower
# search is done, set our top and bottom values
self.base_lr = best_lr / self.lr_depth
self.max_lr = best_lr
# set the LR for the test
K.set_value(self.model.optimizer.lr, np.float32(self.base_lr))
elif(self.searching_clip):
# we've finished searching clipnorm, compile the results and move on
self.searching_clip = False
# smooth the data, each batch can have a lot of noise, get the lowest loss once smoothed and use that value
smoothed = scipy.signal.medfilt(self.epoch_loss_history, self.smoothing_factor)
index_of_best = np.argmin(smoothed)
self.base_clipnorm = self.clipnorm_schedule[index_of_best]
self.model.optimizer.clipnorm = np.float32(self.base_clipnorm)
elif(self.searching_momentum):
# we've finished searching momentum, compile the results and move on
self.searching_momentum = False
# smooth the data, each batch can have a lot of noise, get the lowest loss once smoothed and use that value
smoothed = scipy.signal.medfilt(self.epoch_loss_history, self.smoothing_factor)
index_of_best = np.argmin(smoothed)
self.base_momentum = self.momentum_schedule[index_of_best]
self.min_momentum = self.base_momentum / 1.2
if hasattr(self.model.optimizer, 'momentum'):
K.set_value(self.model.optimizer.momentum, np.float32(self.base_momentum))
elif(self.searching_decay):
# we've finished searching decay, compile the results and move on
self.searching_decay = False
# smooth the data, each batch can have a lot of noise, get the lowest loss once smoothed and use that value
smoothed = scipy.signal.medfilt(self.epoch_loss_history, self.smoothing_factor)
index_of_best = np.argmin(smoothed)
self.base_decay = self.decay_schedule[index_of_best]
if hasattr(self.model.optimizer, 'decay'):
K.set_value(self.model.optimizer.decay, np.float32(self.base_decay))
# now once we finished updating for one, we need to see what's left to optomize
if(self.searching_clip):
# now find the clipnorm
self.find_clipnorm()
elif(self.searching_momentum):
# now find the momentum
self.find_momentum()
elif(self.searching_decay):
# now find the momentum
self.find_decay()
else:
# we found all the values, print them out and stop searching
self.searching = False
print( "Found the following values: ")
print( "base_lr: ", self.base_lr )
print( "max_lr: ", self.max_lr )
print( "base_clipnorm: ", self.base_clipnorm )
if hasattr(self.model.optimizer, 'momentum'):
print( "base_momentum: ", self.base_momentum )
print( "min_momentum: ", self.min_momentum )
if hasattr(self.model.optimizer, 'decay'):
print( "base_decay: ", self.base_decay )
if not self.searching:
# Flip the value of acending/decending every epoch
self.ascending = not self.ascending
# cyles are Learning Rate Acending and Learning Rate Decending
if self.ascending:
old_clipnorm = self.base_clipnorm
old_decay = self.base_decay
# use hyper Param decay if enabled
if(self.decay_hyper_params):
self.base_lr *= self.lr_decay
#self.base_clipnorm *= self.lr_decay
self.base_momentum = ((self.base_momentum - self.min_momentum) * self.lr_decay) + self.min_momentum
#self.base_decay *= self.lr_decay
# set the parameter schedules
self.rate_schedule = np.linspace(self.base_lr, self.max_lr, self.batches_per_epoch)
self.clipnorm_schedule = np.linspace(old_clipnorm, self.base_clipnorm, self.batches_per_epoch)
self.momentum_schedule = np.linspace(self.base_momentum, self.min_momentum, self.batches_per_epoch)
self.decay_schedule = np.linspace(old_decay, self.base_decay, self.batches_per_epoch)
else:
old_clipnorm = self.base_clipnorm
old_decay = self.base_decay
# use hyper Param decay if enabled
if(self.decay_hyper_params):
self.max_lr = ((self.max_lr - self.base_lr) * self.lr_decay) + self.base_lr
#self.base_clipnorm *= self.lr_decay
self.min_momentum *= self.lr_decay
#self.base_decay *= self.lr_decay
# set the parameter schedules
self.rate_schedule = np.linspace(self.max_lr, self.base_lr, self.batches_per_epoch)
self.clipnorm_schedule = np.linspace(old_clipnorm, self.base_clipnorm, self.batches_per_epoch)
self.momentum_schedule = np.linspace(self.min_momentum, self.base_momentum, self.batches_per_epoch)
self.decay_schedule = np.linspace(old_decay, self.base_decay, self.batches_per_epoch)
# clear the loss history for this epoch
self.epoch_loss_history = []
def on_batch_end(self, epoch, logs=None):
logs = logs or {}
loss = np.float32(logs.get('loss'))
# keep metrics for the history, is is mostly for debugging
self.loss_history.append(loss)
self.epoch_loss_history.append(loss)
self.lr_history.append(K.get_value(self.model.optimizer.lr))
self.clipnorm_history.append(self.model.optimizer.clipnorm)#K.get_value(self.model.optimizer.clipnorm))
if hasattr(self.model.optimizer, 'momentum'):
self.momentum_history.append(K.get_value(self.model.optimizer.momentum))
self.decay_history.append(K.get_value(self.model.optimizer.decay))
# set the values for this point in the cycle
if self.searching:
# if we are seraching then we keep all the parameters except one constant
if(self.searching_lr):
K.set_value(self.model.optimizer.lr, np.float32(self.rate_schedule[self.iteration]))
elif(self.searching_clip):
self.model.optimizer.clipnorm = np.float32(self.clipnorm_schedule[self.iteration])
elif(self.searching_momentum and hasattr(self.model.optimizer, 'momentum')):
K.set_value(self.model.optimizer.momentum, np.float32(self.momentum_schedule[self.iteration]))
elif(self.searching_decay and hasattr(self.model.optimizer, 'decay')):
K.set_value(self.model.optimizer.decay, np.float32(self.decay_schedule[self.iteration]))
else:
# if we are running, then we adjust all parameters acording to their scales
K.set_value(self.model.optimizer.lr, np.float32(self.rate_schedule[self.iteration]))
self.model.optimizer.clipnorm = np.float32(self.clipnorm_schedule[self.iteration])
if hasattr(self.model.optimizer, 'momentum'):
K.set_value(self.model.optimizer.momentum, np.float32(self.momentum_schedule[self.iteration]))
if hasattr(self.model.optimizer, 'decay'):
K.set_value(self.model.optimizer.decay, np.float32(self.decay_schedule[self.iteration]))
self.iteration += 1