forked from ddbourgin/numpy-ml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptimizers.py
482 lines (405 loc) · 17.1 KB
/
optimizers.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
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
from copy import deepcopy
from abc import ABC, abstractmethod
import numpy as np
from numpy.linalg import norm
class OptimizerBase(ABC):
def __init__(self, lr, scheduler=None):
"""
An abstract base class for all Optimizer objects.
This should never be used directly.
"""
from ..initializers import SchedulerInitializer
self.cache = {}
self.cur_step = 0
self.hyperparameters = {}
self.lr_scheduler = SchedulerInitializer(scheduler, lr=lr)()
def __call__(self, param, param_grad, param_name, cur_loss=None):
return self.update(param, param_grad, param_name, cur_loss)
def step(self):
"""Increment the optimizer step counter by 1"""
self.cur_step += 1
def reset_step(self):
"""Reset the step counter to zero"""
self.cur_step = 0
def copy(self):
"""Return a copy of the optimizer object"""
return deepcopy(self)
def set_params(self, hparam_dict=None, cache_dict=None):
"""Set the parameters of the optimizer object from a dictionary"""
from ..initializers import SchedulerInitializer
if hparam_dict is not None:
for k, v in hparam_dict.items():
if k in self.hyperparameters:
self.hyperparameters[k] = v
if k == "lr_scheduler":
self.lr_scheduler = SchedulerInitializer(v, lr=None)()
if cache_dict is not None:
for k, v in cache_dict.items():
if k in self.cache:
self.cache[k] = v
@abstractmethod
def update(self, param, param_grad, param_name, cur_loss=None):
raise NotImplementedError
class SGD(OptimizerBase):
def __init__(
self, lr=0.01, momentum=0.0, clip_norm=None, lr_scheduler=None, **kwargs
):
"""
A stochastic gradient descent optimizer.
Notes
-----
For model parameters :math:`\\theta`, averaged parameter gradients
:math:`\\nabla_{\\theta} \mathcal{L}`, and learning rate :math:`\eta`,
the SGD update at timestep `t` is
.. math::
\\text{update}^{(t)}
&= \\text{momentum} \cdot \\text{update}^{(t-1)} + \eta^{(t)} \\nabla_{\\theta} \mathcal{L}\\\\
\\theta^{(t+1)}
&\leftarrow \\theta^{(t)} - \\text{update}^{(t)}
Parameters
----------
lr : float
Learning rate for SGD. If scheduler is not None, this is used as
the starting learning rate. Default is 0.01.
momentum : float in range [0, 1]
The fraction of the previous update to add to the current update.
If 0, no momentum is applied. Default is 0.
clip_norm : float
If not None, all param gradients are scaled to have maximum l2 norm of
`clip_norm` before computing update. Default is None.
lr_scheduler : str, :doc:`Scheduler <numpy_ml.neural_nets.schedulers>` object, or None
The learning rate scheduler. If None, use a constant learning
rate equal to `lr`. Default is None.
"""
super().__init__(lr, lr_scheduler)
self.hyperparameters = {
"id": "SGD",
"lr": lr,
"momentum": momentum,
"clip_norm": clip_norm,
"lr_scheduler": str(self.lr_scheduler),
}
def __str__(self):
H = self.hyperparameters
lr, mm, cn, sc = H["lr"], H["momentum"], H["clip_norm"], H["lr_scheduler"]
return "SGD(lr={}, momentum={}, clip_norm={}, lr_scheduler={})".format(
lr, mm, cn, sc
)
def update(self, param, param_grad, param_name, cur_loss=None):
"""
Compute the SGD update for a given parameter
Parameters
----------
param : :py:class:`ndarray <numpy.ndarray>` of shape (n, m)
The value of the parameter to be updated.
param_grad : :py:class:`ndarray <numpy.ndarray>` of shape (n, m)
The gradient of the loss function with respect to `param_name`.
param_name : str
The name of the parameter.
cur_loss : float
The training or validation loss for the current minibatch. Used for
learning rate scheduling e.g., by
:class:`~numpy_ml.neural_nets.schedulers.KingScheduler`.
Default is None.
Returns
-------
updated_params : :py:class:`ndarray <numpy.ndarray>` of shape (n, m)
The value of `param` after applying the momentum update.
"""
C = self.cache
H = self.hyperparameters
momentum, clip_norm = H["momentum"], H["clip_norm"]
lr = self.lr_scheduler(self.cur_step, cur_loss)
if param_name not in C:
C[param_name] = np.zeros_like(param_grad)
# scale gradient to avoid explosion
t = np.inf if clip_norm is None else clip_norm
if norm(param_grad) > t:
param_grad = param_grad * t / norm(param_grad)
update = momentum * C[param_name] + lr * param_grad
self.cache[param_name] = update
return param - update
#######################################################################
# Adaptive Gradient Methods #
#######################################################################
class AdaGrad(OptimizerBase):
def __init__(self, lr=0.01, eps=1e-7, clip_norm=None, lr_scheduler=None, **kwargs):
"""
An AdaGrad optimizer.
Notes
-----
Weights that receive large gradients will have their effective learning
rate reduced, while weights that receive small or infrequent updates
will have their effective learning rate increased.
Equations::
cache[t] = cache[t-1] + grad[t] ** 2
update[t] = lr * grad[t] / (np.sqrt(cache[t]) + eps)
param[t+1] = param[t] - update[t]
Note that the ``**`` and `/` operations are elementwise
"A downside of Adagrad ... is that the monotonic learning rate usually
proves too aggressive and stops learning too early." [1]
References
----------
.. [1] Karpathy, A. "CS231n: Convolutional neural networks for visual
recognition" https://cs231n.github.io/neural-networks-3/
Parameters
----------
lr : float
Global learning rate
eps : float
Smoothing term to avoid divide-by-zero errors in the update calc.
Default is 1e-7.
clip_norm : float or None
If not None, all param gradients are scaled to have maximum `L2` norm of
`clip_norm` before computing update. Default is None.
lr_scheduler : str or :doc:`Scheduler <numpy_ml.neural_nets.schedulers>` object or None
The learning rate scheduler. If None, use a constant learning
rate equal to `lr`. Default is None.
"""
super().__init__(lr, lr_scheduler)
self.cache = {}
self.hyperparameters = {
"id": "AdaGrad",
"lr": lr,
"eps": eps,
"clip_norm": clip_norm,
"lr_scheduler": str(self.lr_scheduler),
}
def __str__(self):
H = self.hyperparameters
lr, eps, cn, sc = H["lr"], H["eps"], H["clip_norm"], H["lr_scheduler"]
return "AdaGrad(lr={}, eps={}, clip_norm={}, lr_scheduler={})".format(
lr, eps, cn, sc
)
def update(self, param, param_grad, param_name, cur_loss=None):
"""
Compute the AdaGrad update for a given parameter.
Notes
-----
Adjusts the learning rate of each weight based on the magnitudes of its
gradients (big gradient -> small lr, small gradient -> big lr).
Parameters
----------
param : :py:class:`ndarray <numpy.ndarray>` of shape (n, m)
The value of the parameter to be updated
param_grad : :py:class:`ndarray <numpy.ndarray>` of shape (n, m)
The gradient of the loss function with respect to `param_name`
param_name : str
The name of the parameter
cur_loss : float or None
The training or validation loss for the current minibatch. Used for
learning rate scheduling e.g., by
:class:`~numpy_ml.neural_nets.schedulers.KingScheduler`.
Default is None.
Returns
-------
updated_params : :py:class:`ndarray <numpy.ndarray>` of shape (n, m)
The value of `param` after applying the AdaGrad update
"""
C = self.cache
H = self.hyperparameters
eps, clip_norm = H["eps"], H["clip_norm"]
lr = self.lr_scheduler(self.cur_step, cur_loss)
if param_name not in C:
C[param_name] = np.zeros_like(param_grad)
# scale gradient to avoid explosion
t = np.inf if clip_norm is None else clip_norm
if norm(param_grad) > t:
param_grad = param_grad * t / norm(param_grad)
C[param_name] += param_grad ** 2
update = lr * param_grad / (np.sqrt(C[param_name]) + eps)
self.cache = C
return param - update
class RMSProp(OptimizerBase):
def __init__(
self, lr=0.001, decay=0.9, eps=1e-7, clip_norm=None, lr_scheduler=None, **kwargs
):
"""
RMSProp optimizer.
Notes
-----
RMSProp was proposed as a refinement of :class:`AdaGrad` to reduce its
aggressive, monotonically decreasing learning rate.
RMSProp uses a *decaying average* of the previous squared gradients
(second moment) rather than just the immediately preceding squared
gradient for its `previous_update` value.
Equations::
cache[t] = decay * cache[t-1] + (1 - decay) * grad[t] ** 2
update[t] = lr * grad[t] / (np.sqrt(cache[t]) + eps)
param[t+1] = param[t] - update[t]
Note that the ``**`` and ``/`` operations are elementwise.
Parameters
----------
lr : float
Learning rate for update. Default is 0.001.
decay : float in [0, 1]
Rate of decay for the moving average. Typical values are [0.9,
0.99, 0.999]. Default is 0.9.
eps : float
Constant term to avoid divide-by-zero errors during the update calc. Default is 1e-7.
clip_norm : float or None
If not None, all param gradients are scaled to have maximum l2 norm of
`clip_norm` before computing update. Default is None.
lr_scheduler : str or :doc:`Scheduler <numpy_ml.neural_nets.schedulers>` object or None
The learning rate scheduler. If None, use a constant learning
rate equal to `lr`. Default is None.
"""
super().__init__(lr, lr_scheduler)
self.cache = {}
self.hyperparameters = {
"id": "RMSProp",
"lr": lr,
"eps": eps,
"decay": decay,
"clip_norm": clip_norm,
"lr_scheduler": str(self.lr_scheduler),
}
def __str__(self):
H = self.hyperparameters
sc = H["lr_scheduler"]
lr, eps, dc, cn = H["lr"], H["eps"], H["decay"], H["clip_norm"]
return "RMSProp(lr={}, eps={}, decay={}, clip_norm={}, lr_scheduler={})".format(
lr, eps, dc, cn, sc
)
def update(self, param, param_grad, param_name, cur_loss=None):
"""
Compute the RMSProp update for a given parameter.
Parameters
----------
param : :py:class:`ndarray <numpy.ndarray>` of shape (n, m)
The value of the parameter to be updated
param_grad : :py:class:`ndarray <numpy.ndarray>` of shape (n, m)
The gradient of the loss function with respect to `param_name`
param_name : str
The name of the parameter
cur_loss : float or None
The training or validation loss for the current minibatch. Used for
learning rate scheduling e.g., by
:class:`~numpy_ml.neural_nets.schedulers.KingScheduler`.
Default is None.
Returns
-------
updated_params : :py:class:`ndarray <numpy.ndarray>` of shape (n, m)
The value of `param` after applying the RMSProp update.
"""
C = self.cache
H = self.hyperparameters
eps, decay, clip_norm = H["eps"], H["decay"], H["clip_norm"]
lr = self.lr_scheduler(self.cur_step, cur_loss)
if param_name not in C:
C[param_name] = np.zeros_like(param_grad)
# scale gradient to avoid explosion
t = np.inf if clip_norm is None else clip_norm
if norm(param_grad) > t:
param_grad = param_grad * t / norm(param_grad)
C[param_name] = decay * C[param_name] + (1 - decay) * param_grad ** 2
update = lr * param_grad / (np.sqrt(C[param_name]) + eps)
self.cache = C
return param - update
class Adam(OptimizerBase):
def __init__(
self,
lr=0.001,
decay1=0.9,
decay2=0.999,
eps=1e-7,
clip_norm=None,
lr_scheduler=None,
**kwargs
):
"""
Adam (adaptive moment estimation) optimization algorithm.
Notes
-----
Designed to combine the advantages of :class:`AdaGrad`, which works
well with sparse gradients, and :class:`RMSProp`, which works well in
online and non-stationary settings.
Parameters
----------
lr : float
Learning rate for update. This parameter is ignored if using
:class:`~numpy_ml.neural_nets.schedulers.NoamScheduler`.
Default is 0.001.
decay1 : float
The rate of decay to use for in running estimate of the first
moment (mean) of the gradient. Default is 0.9.
decay2 : float
The rate of decay to use for in running estimate of the second
moment (variance) of the gradient. Default is 0.999.
eps : float
Constant term to avoid divide-by-zero errors during the update
calc. Default is 1e-7.
clip_norm : float
If not None, all param gradients are scaled to have maximum l2 norm of
`clip_norm` before computing update. Default is None.
lr_scheduler : str, or :doc:`Scheduler <numpy_ml.neural_nets.schedulers>` object, or None
The learning rate scheduler. If None, use a constant learning rate
equal to `lr`. Default is None.
"""
super().__init__(lr, lr_scheduler)
self.cache = {}
self.hyperparameters = {
"id": "Adam",
"lr": lr,
"eps": eps,
"decay1": decay1,
"decay2": decay2,
"clip_norm": clip_norm,
"lr_scheduler": str(self.lr_scheduler),
}
def __str__(self):
H = self.hyperparameters
lr, d1, d2 = H["lr"], H["decay1"], H["decay2"]
eps, cn, sc = H["eps"], H["clip_norm"], H["lr_scheduler"]
return "Adam(lr={}, decay1={}, decay2={}, eps={}, clip_norm={}, lr_scheduler={})".format(
lr, d1, d2, eps, cn, sc
)
def update(self, param, param_grad, param_name, cur_loss=None):
"""
Compute the Adam update for a given parameter.
Parameters
----------
param : :py:class:`ndarray <numpy.ndarray>` of shape (n, m)
The value of the parameter to be updated.
param_grad : :py:class:`ndarray <numpy.ndarray>` of shape (n, m)
The gradient of the loss function with respect to `param_name`.
param_name : str
The name of the parameter.
cur_loss : float
The training or validation loss for the current minibatch. Used for
learning rate scheduling e.g., by
:class:`~numpy_ml.neural_nets.schedulers.KingScheduler`. Default is
None.
Returns
-------
updated_params : :py:class:`ndarray <numpy.ndarray>` of shape (n, m)
The value of `param` after applying the Adam update.
"""
C = self.cache
H = self.hyperparameters
d1, d2 = H["decay1"], H["decay2"]
eps, clip_norm = H["eps"], H["clip_norm"]
lr = self.lr_scheduler(self.cur_step, cur_loss)
if param_name not in C:
C[param_name] = {
"t": 0,
"mean": np.zeros_like(param_grad),
"var": np.zeros_like(param_grad),
}
# scale gradient to avoid explosion
t = np.inf if clip_norm is None else clip_norm
if norm(param_grad) > t:
param_grad = param_grad * t / norm(param_grad)
t = C[param_name]["t"] + 1
var = C[param_name]["var"]
mean = C[param_name]["mean"]
# update cache
C[param_name]["t"] = t
C[param_name]["var"] = d2 * var + (1 - d2) * param_grad ** 2
C[param_name]["mean"] = d1 * mean + (1 - d1) * param_grad
self.cache = C
# calc unbiased moment estimates and Adam update
v_hat = C[param_name]["var"] / (1 - d2 ** t)
m_hat = C[param_name]["mean"] / (1 - d1 ** t)
update = lr * m_hat / (np.sqrt(v_hat) + eps)
return param - update