-
Notifications
You must be signed in to change notification settings - Fork 2
/
SGD.py
1583 lines (1501 loc) · 72.4 KB
/
SGD.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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
-------------------------------------------------------------------------------
If you find this code useful please cite the article:
Topology Optimization under Uncertainty using a Stochastic Gradient-based Approach
Subhayan De, Jerrad Hampton, Kurt Maute, and Alireza Doostan (2020)
Structural and Multidisciplinary Optimization, 62(5), 2255-2278.
https://doi.org/10.1007/s00158-020-02599-z
BibTeX entry:
@article{de2020topology,
title={Topology optimization under uncertainty using a stochastic gradient-based approach},
author={De, Subhayan and Hampton, Jerrad and Maute, Kurt and Doostan, Alireza},
journal={Structural and Multidisciplinary Optimization},
volume={62},
number={5},
pages={2255--2278},
year={2020},
publisher={Springer}
}
Download the SGD module from https://github.com/CU-UQ/SGD.
See the demo https://github.com/CU-UQ/SGD/blob/master/sgd_demo.py for an example of the implementation.
For a description of the algorithms, see De et al (2020) (https://doi.org/10.1007/s00158-020-02599-z) and Ruder (2016) (https://arxiv.org/abs/1609.04747).
Please report any bugs to [email protected]
Website: www.subhayande.com
-------------------------------------------------------------------------------
This is the class file that implements:
(i) Stochastic Gradient Descent,
(ii) SGD with Momentum,
(iii) NAG,
(iv) AdaGrad,
(iv) RMSprop,
(vi) Adam,
(vii) Adamax,
(viii) Adadelta,
(ix) Nadam,
(x) SAG,
(xi) minibatch SGD,
(xii) SVRG.
NOTE: Currently, the stopping conditions are maximum number of iteration and 2nd norm of gradient vector
and time-delay and exponential learnong schedules are implemented.
Copyright (C) 2019 Subhayan De
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Created on Sat Jun 30 01:04:28 2018
@author: Subhayan De
Report any bugs to [email protected]
Author's note: add kSGD, 2nd order methods
"""
import numpy as np
import time
# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█'):
"""
Call in a loop to create terminal progress bar
parameters:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\r')
# Print New Line on Complete
if iteration == total:
print()
class SGD(object):
"""
==============================================================================
| Stochastic Gradient Descent class |
==============================================================================
Initialization:
sgd = SGD(obj, grad, eta, param, iter, maxIter, objFun, gradFun,
lowerBound, upperBound, stopGrad, momentum, nesterov,
learnSched, lrParam)
NOTE: To perform just one iteration provide either grad or gradFn.
obj or objFn are optional.
==============================================================================
Attributes:
obj: objective (optional input)
grad: Gradient information
(array of dimension nParam-by-1, optional input)
eta: learning rate ( = 1.0, default)
param: the parameter vector (array of dimension nParam-by-1)
nParam: number of parameters
iter: iteration number
maxIter: maximum iteration number (optional, default = 1)
objFun: function handle to evaluate the objective
(not required for maxit = 1 )
gradFun: function handle to evaluate the gradient
(not required for maxit = 1 )
lowerBound: lower bound for the parameters (optional input)
upperBound: upper bound for the parameters (optional input)
paramHist: parameter evolution history
stopGrad: stopping criterion based on 2-norm of gradient vector
momentum: momentum parameter (default = 0)
nesterov: set to True if Nesterov momentum equation to be used
(default = False)
learnSched: learning schedule (constant, exponential or time-based,
default = constant)
lrParam: learning schedule parameter (default =0.1)
alg: algorithm used
__version__:version of the code
==============================================================================
Methods:
Public:
getParam: returns the parameter values
getObj: returns the current objective value
getGrad: returns the current gradient information
update: perform a single iteration
performIter: perform maxIter number of iterations
getParamHist: returns parameter update history
Private:
__init___: initialization
evaluateObjFn: evaluates the objective function
evaluateGradFn: evaluates the gradients
satisfyBounds: satisfies the parameter bounds
learningSchedule: learning schedule
stopCrit: check stopping criteria
==============================================================================
Reference: Bottou, Léon, Frank E. Curtis, and Jorge Nocedal.
"Optimization methods for large-scale machine learning."
SIAM Review 60.2 (2018): 223-311.
==============================================================================
written by Subhayan De (email: [email protected]), July, 2018.
==============================================================================
"""
def __init__(self,**kwargs):
allowed_kwargs = {'obj', 'grad', 'param', 'eta', 'iter', 'maxiter', 'objFun', 'gradFun', 'lowerBound', 'upperBound', 'oldGrad', 'stopGrad', 'momentum', 'nesterov','learnSched', 'lrParam'}
for k in kwargs:
if k not in allowed_kwargs:
raise TypeError('Unexpected keyword argument passed to optimizer at: ' + str(k))
self.__dict__.update(kwargs)
self.nParam = np.size(self.param)
# Checks and setting default values
# Iteration numbers
if hasattr(self,'iter') == False:
self.iter = 0 # set the iteration number
self.currentIter = self.iter
# stopping criteria
# max iteration no.
if hasattr(self,'maxiter') == False:
self.maxiter = 1 # set the default max iteration number
# minimum gradient
if hasattr(self,'stopGrad') == False:
self.stopGrad = 1e-6
# Parameter values
if hasattr(self,'param') == False:
raise ValueError('Parameter vector is missing')
# Gradient information
if hasattr(self,'grad') == False:
print('No gradient information provided at iteration: 1')
if hasattr(self,'gradFun') == False:
raise ValueError('Please provide the gradient function')
elif np.size(self.grad) != self.nParam:
raise ValueError('Gradient dimension mismatch')
if self.maxiter > 1 and hasattr(self,'gradFun') == False:
raise ValueError('Please provide the gradient function')
# Objective values
if hasattr(self,'objFun') == False and self.maxiter > 1:
raise ValueError('Please provide the objective function')
if hasattr(self,'obj') == False:
self.obj = np.array([])
if hasattr(self,'objFun'):
self.evaluateObjFn(self)
else:
self.obj = np.array([self.obj])
# Learning rate
if hasattr(self,'eta') == False:
self.eta = 1.0
print('*NOTE: No learning rate provided, assumed as 1.0')
else:
print('Learning rate = ',self.eta,'\n')
if hasattr(self,'lowerBound') == False:
self.lowerBound = -np.inf*np.ones(self.nParam)
elif np.size(self.lowerBound) == 1:
self.lowerBound = self.lowerBound*np.ones(self.nParam)
else:
raise ValueError('parameter lower bound dimension mismatch')
# Set the upper bounds
if hasattr(self,'upperBound') == False:
self.upperBound = np.inf*np.ones(self.nParam)
elif np.size(self.upperBound) == 1:
self.upperBound = self.upperBound*np.ones(self.nParam)
else:
raise ValueError('parameter upper bound dimension mismatch')
# Momentum
#self.alg = 'SGD with Momentum'
if hasattr(self,'alg') == False:
self.alg = 'SGD+momentum'
if hasattr(self,'momentum') == False:
self.alg = 'SGD'
self.momentum = 0.0;
self.paramHist = np.reshape(self.param,(2,1))
self.__version__ = '0.0.1'
self.stop = False
self.updateParam = np.zeros(self.nParam)
# Nesterov momentum
if hasattr(self, 'nesterov'):
if self.nesterov == True:
self.alg = 'SGD+Nesterov momentum'
if hasattr(self,'gradFun') == False:
raise ValueError('provide gradient function information with Nesterov')
else:
self.nesterov = False
# learning schedule
if hasattr(self,'learnSched') == False:
self.learnSched = 'constant'
elif self.learnSched != 'exponential' and self.learnSched != 'time-based':
print('no such learning schedule in this module\nSet to constant')
self.learnSched = 'constant'
elif hasattr(self,'lrParam') == False:
self.lrParam = 0.1
print('Learning schedule: ',self.learnSched)
def __version__(self):
"""
version of the code
"""
print(self.__version__)
def getParam(self):
"""
To get the next parameter values
"""
print(self.nParam,'parameters have been updated!\n')
return self.param
def getObj(self):
"""
To get the current objective (if possible)
"""
self.evaluateObjFn()
return self.obj
def getGrad(self):
"""
To get the gradients
"""
return self.grad
def getParamHist(self):
"""
To get parameter history
"""
return self.paramHist
def evaluateObjFn(self):
"""
This evalutes the objective function
objFun should be a function handle with input: param, output: objective
"""
if not self.obj.any():
print('No objective information provided to SGD')
else:
self.obj = np.append(self.obj,self.objFun(self.param))
#print('Current objective value: ', self.obj[self.currentIter],'\n')
def evaluateGradFn(self):
"""
This evalutes the gradient function for i-th data point, where i in [0, n]
gradFun should be a function handle with input: param, output: gradient
"""
self.grad = self.gradFun(self.param)
def satisfyBounds(self):
"""
This satisfies the parameter bounds (if any)
"""
# Set the lower bounds
#print(self.lowerBound)
# Satisfy the bounds
for i in range(self.nParam):
if self.param[i] > self.upperBound[i]:
self.param[i] = self.upperBound[i]
elif self.param[i] < self.lowerBound[i]:
self.param[i] = self.lowerBound[i]
def update(self):
"""
Perform one iteration of SGD
"""
# Perform one iteration of SGD
SGD.learningSchedule(self)
if self.nesterov == True:
grdnt = self.gradFun(self.param - self.momentum*self.updateParam)
self.updateParam = self.updateParam*self.momentum + self.etaCurrent*grdnt
else:
self.updateParam = self.updateParam*self.momentum + self.etaCurrent*self.grad
self.param=self.param - self.updateParam
#self.param=self.param - self.eta*self.grad
# satisfy the parameter bounds
SGD.satisfyBounds(self)
self.paramHist = np.append(self.paramHist,np.reshape(self.param,(2,1)), axis = 1)
#print('One iteration of Stochatsic Gradient Descent has been performed successfully!\n')
def performIter(self):
"""
Performs all the iterations of SGD
"""
SGD.printAlg(self)
# initialize progress bar
printProgressBar(0, self.maxiter, prefix = self.alg, suffix = 'Complete', length = 25)
self.t = time.clock()
for i in range(self.iter,self.maxiter,1):
if self.stop == True:
break
#print('iteration', i+1, 'out of', self.maxiter)
self.update()
self.currentIter = i+1
# print progress bar
SGD.printProgress(self)
# Update the objective and gradient
if self.maxiter > 1: # since objFun and gradFun are optional for 1 iteration
SGD.evaluateObjFn(self)
SGD.evaluateGradFn(self)
SGD.stopCrit(self)
def stopCrit(self):
"""
Checks stopping criteria
"""
if self.grad.ndim >1:
self.avgGrad = np.mean(self.grad,axis =1)
if np.linalg.norm(self.avgGrad)<self.stopGrad:
self.stop = True
elif np.linalg.norm(self.grad)<self.stopGrad:
self.stop = True
def learningSchedule(self):
"""
creates a learning schedule for SGD
"""
if self.learnSched == 'constant':
self.etaCurrent =self.eta # no change
elif self.learnSched == 'exponential':
self.etaCurrent = self.eta*np.exp(-self.lrParam*self.currentIter)
print(self.etaCurrent)
elif self.learnSched == 'time-based':
self.etaCurrent = self.eta/(1.0+self.lrParam*self.currentIter)
def printAlg(self):
"""
prints algorithm
"""
print('\nAlgorithm: ',self.alg,'\n')
def printProgress(self):
# Update Progress Bar
if hasattr(self,'outerIter'):
printProgressBar(self.currentIter, self.outerIter, prefix = self.alg, suffix = ('Complete: Time Elapsed = '+str(np.around(time.clock()-self.t,decimals=2))+'s'+', Objective = '+str(np.around(self.obj[self.currentIter-1],decimals=6))+' '), length = 25)
else:
printProgressBar(self.currentIter, self.maxiter, prefix = self.alg, suffix = ('Complete: Time Elapsed = '+str(np.around(time.clock()-self.t,decimals=2))+'s'+', Objective = '+str(np.around(self.obj[self.currentIter-1],decimals=6))+' '), length = 25)
class AdaGrad(SGD):
"""
==============================================================================
| Adaptive Subgradient Method (AdaGrad) class |
| derived class from Stochastic Gradient Descent |
==============================================================================
Initialization:
adg = AdaGrad(gradHist, obj, grad, eta, param,
iter, maxIter, objFun, gradFun, lowerBound, upperBound)
NOTE: gradHist: historical information of gradients
(array of dimension nparam-by-1).
This should equal to zero for 1st iteration
==============================================================================
Attributes:
obj: Initial objective value (optional input)
grad: Gradient information (array of dimension nParam-by-1)
eta: learning rate ( = 1.0, default)
param: the parameter vector (array of dimension nParam-by-1)
nParam: number of parameters
gradHist: sum of gradient history (see the algorithm)
epsilon: square-root of machine-precision
(required to avoid division by zero)
iter: iteration number (optional input)
maxIter: maximum iteration number (optional input, default = 1)
objFun: function handle to evaluate the objective
(not required for maxit = 1 )
gradFun: function handle to evaluate the gradient
(not required for maxit = 1 )
lowerBound: lower bound for the parameters (optional input)
upperBound: upper bound for the parameters (optional input)
stopGrad: stopping criterion based on 2-norm of gradient vector
(default 10^-6)
alg: algorithm used
__version__: version of the code
==============================================================================
Methods:
Public:
performIter:performs all the iterations inside a for loop
getGradHist:returns gradient history (default is zero)
Inherited:
getParam: returns the parameter values
getObj: returns the current objective value
getGrad: returns the current gradient information
getParamHist: returns parameter update history
Private: (should not be called outside this class file)
__init__: initialization
update: performs one iteration of AdaGrad
Inherited:
evaluateObjFn: evaluates the objective function
evaluateGradFn: evaluates the gradients
satisfyBounds: satisfies the parameter bounds
learningSchedule: learning schedule
stopCrit: check stopping criteria
==============================================================================
Reference: Duchi, John, Elad Hazan, and Yoram Singer.
"Adaptive subgradient methods for online learning and stochastic optimization."
Journal of Machine Learning Research 12.Jul (2011): 2121-2159.
==============================================================================
written by Subhayan De (email: [email protected]), July, 2018.
==============================================================================
"""
def __init__(self,gradHist=0.0,**kwargs):
#def __init__(self,grad,learningRate,param,nParam,gradHist):
""" Initialize the AdaGrad class object.
This can be used to perform one iteration of AdaGrad.
"""
self.alg = 'AdaGrad'
SGD.printAlg(self)
#SGD.__init__(self,grad,learningRate,param,nParam)
SGD.__init__(self,**kwargs)
self.epsilon=np.finfo(float).eps # The machine precision
if np.sum(gradHist) != 0.0:
self.gradHist=np.reshape(gradHist,(self.nParam))
else:
self.gradHist = np.zeros(self.nParam)
def update(self):
"""
Perform one iteration of AdaGrad
"""
SGD.learningSchedule(self)
self.gradHist += np.multiply(self.grad,self.grad); # Sum of gradient history
# Perform one iteration of AdaGrad
self.param=self.param - np.divide((self.etaCurrent*self.grad),(np.sqrt(self.gradHist)+self.epsilon))
# satisfy the parameter bounds
SGD.satisfyBounds(self)
self.paramHist = np.append(self.paramHist,np.reshape(self.param,(2,1)), axis = 1)
#print('One iteration of AdaGrad has been performed successfully!\n')
def performIter(self):
"""
Performs all the iterations of AdaGrad
"""
# initialize progress bar
printProgressBar(0, self.maxiter, prefix = self.alg, suffix = 'Complete', length = 25)
self.t = time.clock()
for i in range(self.iter,self.maxiter,1):
if self.stop == True:
break
#print('iteration', i+1, 'out of', self.maxiter)
self.update()
self.currentIter = i+1
# print progress bar
SGD.printProgress(self)
# Update the objective and gradient
if self.maxiter > 1: # since objFun and gradFun are optional for 1 iteration
SGD.evaluateObjFn(self)
SGD.evaluateGradFn(self)
SGD.stopCrit(self)
def getGradHist(self):
"""
Returns accumulated gradient history
"""
return self.gradHist
class RMSprop(SGD):
"""
==============================================================================
| RMSprop class |
| derived class from Stochastic Gradient Descent |
==============================================================================
Initialization:
rp = RMSprop(gradHist, updatehist, rho, obj, grad, eta, param,
iter, maxIter, objFun, gradFun, lowerBound, upperBound)
NOTE: gradHist: historical information of gradients
(array of dimension nparam-by-1)
this should equal to zero for 1st iteration
==============================================================================
Attributes:
grad: Gradient information (array of dimension nParam-by-1)
eta: learning rate = 1 by default
param: the parameter vector (array of dimension nParam-by-1)
nParam: number of parameters
gradHist: gradient history accumulator (see the algorithm)
epsilon: square-root of machine-precision
(required to avoid division by zero)
rho: exponential decay rate (0.95 may be a good choice)
iter: iteration number (optional)
maxIter: maximum iteration number (optional input, default = 1)
objFun: function handle to evaluate the objective
(not required for maxit = 1 )
gradFun: function handle to evaluate the gradient
(not required for maxit = 1 )
lowerBound: lower bound for the parameters (optional input)
upperBound: upper bound for the parameters (optional input)
stopGrad: stopping criterion based on 2-norm of gradient vector
(default 10^-6)
alg: algorithm used
__version__: version of the code
==============================================================================
Methods:
Public:
performIter:performs all the iterations inside a for loop
getGradHist:returns gradient history (default is zero)
Inherited:
getParam: returns the parameter values
getObj: returns the current objective value
getGrad: returns the current gradient information
getParamHist: returns parameter update history
Private: (should not be called outside this class file)
__init__: initialization
update: performs one iteration of Adadelta
Inherited:
evaluateObjFn: evaluates the objective function
evaluateGradFn: evaluates the gradients
satisfyBounds: satisfies the parameter bounds
learningSchedule: learning schedule
stopCrit: check stopping criteria
==============================================================================
Reference: Geoffrey Hinton
"rmsprop: Divide the gradient by a running average of its recent magnitude."
http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf.
==============================================================================
written by Subhayan De (email: [email protected]), July, 2018.
==============================================================================
"""
def __init__(self,gradHist=0.0,rho=0.9,**kwargs):
""" Initialize the Adadelta class object.
This can be used to perform one iteration of Adadelta.
"""
self.alg = 'RMSprop'
SGD.printAlg(self)
SGD.__init__(self,**kwargs)
self.epsilon=np.finfo(float).eps # The machine precision
# Initialize gradient history
if np.sum(gradHist) != 0.0:
if np.size(gradHist) != self.nParam:
raise ValueError('Gradient history dimension mismatch')
else:
self.gradHist=np.reshape(gradHist,(self.nParam))
else:
self.gradHist = np.zeros(self.nParam)
# Initialize rho
self.rho = rho
def update(self):
"""
Perform one iteration of RMSprop
"""
# update gradient history acccumulator
SGD.learningSchedule(self)
self.gradHist+=self.rho*self.gradHist+(1.0-self.rho)*np.multiply(self.grad,self.grad); # Sum of gradient history
# Perform one iteration of RMSprop
RMSg = np.sqrt(self.gradHist)+self.epsilon
updateParam = ((np.divide(self.grad,RMSg)))
self.param=self.param-self.etaCurrent*updateParam
SGD.satisfyBounds(self)
self.paramHist = np.append(self.paramHist,np.reshape(self.param,(2,1)), axis = 1)
#print('One iteration of RMSprop has been performed successfully!\n')
def performIter(self):
"""
Performs all the iterations of RMSprop
"""
# initialize progress bar
printProgressBar(0, self.maxiter, prefix = self.alg, suffix = 'Complete', length = 25)
self.t = time.clock()
for i in range(self.iter,self.maxiter,1):
if self.stop == True:
break
#print('iteration', i+1, 'out of', self.maxiter)
self.update()
self.currentIter = i+1
# print progress bar
SGD.printProgress(self)
# Update the objective and gradient
if self.maxiter > 1: # since objFun and gradFun are optional for 1 iteration
SGD.evaluateObjFn(self)
SGD.evaluateGradFn(self)
SGD.stopCrit(self)
def getGradHist(self):
"""
This returns the gradient history
"""
return self.gradHist
class Adam(SGD):
"""
==============================================================================
| Adaptive moment estimation (Adam) class |
| derived class from Stochastic Gradient Descent |
==============================================================================
Initialization:
adm = Adam(m, v, beta1, beta2, obj, grad, eta, param,
iter, maxIter, objFun, gradFun, lowerBound, upperBound)
==============================================================================
Attributes:
grad: Gradient information (array of dimension nParam-by-1)
eta: learning rate
param: the parameter vector (array of dimension nParam-by-1)
nParam: number of parameters
beta1, beta2: exponential decay rates in [0,1)
(default beta1 = 0.9, beta2 = 0.999)
m: First moment (array of dimension nParam-by-1)
v: Second raw moment (array of dimension nParam-by-1)
epsilon: square-root of machine-precision
(required to avoid division by zero)
iter: iteration number
maxIter: maximum iteration number (optional input, default = 1)
objFun: function handle to evaluate the objective
(not required for maxit = 1 )
gradFun: function handle to evaluate the gradient
(not required for maxit = 1 )
lowerBound: lower bound for the parameters (optional input)
upperBound: upper bound for the parameters (optional input)
stopGrad: stopping criterion based on 2-norm of gradient vector
(default 10^-6)
alg: algorithm used
__version__: version of the code
==============================================================================
Methods:
Public:
performIter: performs all the iterations inside a for loop
getGradHist: returns gradient history (default is zero)
getMoments: returns history of moments
Inherited:
getParam: returns the parameter values
getObj: returns the current objective value
getGrad: returns the current gradient information
getParamHist: returns parameter update history
Private: (should not be called outside this class file)
__init__: initialization
update: performs one iteration of Adam
Inherited:
evaluateObjFn: evaluates the objective function
evaluateGradFn: evaluates the gradients
satisfyBounds: satisfies the parameter bounds
learningSchedule: learning schedule
stopCrit: check stopping criteria
==============================================================================
Reference: Kingma, Diederik P., and Jimmy Ba.
"Adam: A method for stochastic optimization."
arXiv preprint arXiv:1412.6980 (2014).
==============================================================================
written by Subhayan De (email: [email protected]), July, 2018.
==============================================================================
"""
def __init__(self,m = 0.0,v = 0.0,beta1 = 0.9,beta2 = 0.99,**kwargs):
# def __init__(self,grad,learningRate,parameters,numParam,gradHist,beta1,beta2):
""" Initialize the adagrad class object.
This can be used to perform one iteration of Adam.
"""
self.alg = 'Adam'
SGD.printAlg(self)
self.beta1 = beta1 # decay rate (beta1 = 0.9 is a good suggestion)
self.beta2 = beta2 # decay rate (beta2 = 0.999 is a good suggetion)
self.epsilon=np.finfo(float).eps # The machine precision
SGD.__init__(self,**kwargs)
# Initialize first moment
if np.sum(m) != 0.0:
if np.size(m) != self.nParam:
raise ValueError('First moment dimension mismatch')
else:
self.m=np.reshape(m,(self.nParam))
else:
self.m = np.zeros(self.nParam)
# Initialize second raw moment
if np.sum(v) != 0.0:
if np.size(v) != self.nParam:
raise ValueError('Second raw moment dimension mismatch')
else:
self.v=np.reshape(v,(self.nParam))
else:
self.v = np.zeros(self.nParam)
def update(self):
""" Perform one iteration of Adam
"""
SGD.learningSchedule(self)
# Moment updates
self.m = self.beta1*self.m + (1.0-self.beta1)*self.grad # Update biased first moment estimate
self.mHat = self.m/(1.0-self.beta1**(self.currentIter+1)) # Compute bias-corrected first moment estimate
#print(self.mHat)
self.v = self.beta2*self.v + (1.0-self.beta2)*np.multiply(self.grad,self.grad) # Update biased second moment estimate
self.vHat = self.v/(1.0-self.beta2**(self.currentIter+1)) # Compute bias-corrected second moment estimate
# Parameter updates
self.param = self.param - np.divide((self.etaCurrent*self.mHat),(np.sqrt(self.vHat))+self.epsilon)
SGD.satisfyBounds(self)
self.paramHist = np.append(self.paramHist,np.reshape(self.param,(2,1)), axis = 1)
#print('One iteration of Adam has been performed successfully!\n')
def performIter(self):
"""
Performs all the iterations of Adam
"""
# initialize progress bar
printProgressBar(0, self.maxiter, prefix = self.alg, suffix = 'Complete', length = 25)
self.t = time.clock()
for i in range(self.iter,self.maxiter,1):
if self.stop == True:
break
#print('iteration', i+1, 'out of', self.maxiter)
self.update()
self.currentIter = i+1
# print progress bar
SGD.printProgress(self)
# Update the objective and gradient
if self.maxiter > 1: # since objFun and gradFun are optional for 1 iteration
SGD.evaluateObjFn(self)
SGD.evaluateGradFn(self)
SGD.stopCrit(self)
def getMoments(self):
"""
This returns the updated moments
"""
return self.m, self.v
class Adamax(SGD):
"""
==============================================================================
| Adaptive moment estimation (Adamax) class |
| derived class from Stochastic Gradient Descent |
==============================================================================
Initialization:
admx = Adamax(m, v, beta1, beta2, obj, grad, eta, param,
iter, maxIter, objFun, gradFun, lowerBound, upperBound)
==============================================================================
Attributes: (all private)
grad: Gradient information (array of dimension nParam-by-1)
eta: learning rate
param: the parameter vector (array of dimension nParam-by-1)
nParam: number of parameters
beta1, beta2: exponential decay rates in [0,1)
(default beta1 = 0.9, beta2 = 0.999)
m: First moment (array of dimension nParam-by-1)
u: infinity norm constrained second moment
(array of dimension nParam-by-1)
epsilon: square-root of machine-precision
(required to avoid division by zero)
iter: iteration number
maxIter: maximum iteration number (optional input, default = 1)
objFun: function handle to evaluate the objective
(not required for maxit = 1 )
gradFun: function handle to evaluate the gradient
(not required for maxit = 1 )
lowerBound: lower bound for the parameters (optional input)
upperBound: upper bound for the parameters (optional input)
stopGrad: stopping criterion based on 2-norm of gradient vector
(default 10^-6)
alg: algorithm used
__version__: version of the code
==============================================================================
Methods:
Public:
performIter: performs all the iterations inside a for loop
getGradHist: returns gradient history (default is zero)
getMoments: returns history of moments
Inherited:
getParam: returns the parameter values
getObj: returns the current objective value
getGrad: returns the current gradient information
getParamHist: returns parameter update history
Private: (should not be called outside this class file)
__init__: initialization
update: performs one iteration of Adam
Inherited:
evaluateObjFn: evaluates the objective function
evaluateGradFn: evaluates the gradients
satisfyBounds: satisfies the parameter bounds
learningSchedule: learning schedule
stopCrit: check stopping criteria
==============================================================================
Reference: Kingma, Diederik P., and Jimmy Ba.
"Adam: A method for stochastic optimization."
arXiv preprint arXiv:1412.6980 (2014).
==============================================================================
written by Subhayan De (email: [email protected]), July, 2018.
==============================================================================
"""
def __init__(self,m = 0.0,u = 0.0,beta1 = 0.9,beta2 = 0.99,**kwargs):
# def __init__(self,grad,learningRate,parameters,numParam,gradHist,beta1,beta2):
""" Initialize the adagrad class object.
This can be used to perform one iteration of Adamax.
"""
self.alg = 'Adamax'
SGD.printAlg(self)
self.beta1 = beta1 # decay rate (beta1 = 0.9 is a good suggestion)
self.beta2 = beta2 # decay rate (beta2 = 0.999 is a good suggetion)
self.epsilon=np.finfo(float).eps # The machine precision
SGD.__init__(self,**kwargs)
# Initialize first moment
if np.sum(m) != 0.0:
if np.size(m) != self.nParam:
raise ValueError('First moment dimension mismatch')
else:
self.m=np.reshape(m,(self.nParam))
else:
self.m = np.zeros(self.nParam)
# Initialize second raw moment
if np.sum(u) != 0.0:
if np.size(u) != self.nParam:
raise ValueError('Second raw moment dimension mismatch')
else:
self.u=np.reshape(u,(self.nParam))
else:
self.u = np.zeros(self.nParam)
def update(self):
""" Perform one iteration of Adamax
"""
SGD.learningSchedule(self)
# Moment updates
self.m = self.beta1*self.m + (1.0-self.beta1)*self.grad # Update biased first moment estimate
self.mHat = self.m/(1.0-self.beta1**(self.currentIter+1)) # Compute bias-corrected first moment estimate
self.u = np.maximum(self.beta2*self.u,np.abs(self.grad))
# self.v = self.beta2*self.v + (1.0-self.beta2)*np.multiply(self.grad,self.grad) # Update biased second moment estimate
# Parameter updates
self.param = self.param - np.divide((self.etaCurrent*self.mHat),self.u)
SGD.satisfyBounds(self)
self.paramHist = np.append(self.paramHist,np.reshape(self.param,(2,1)), axis = 1)
#print('One iteration of Adamax has been performed successfully!\n')
def performIter(self):
"""
Performs all the iterations of Adamax
"""
# initialize progress bar
printProgressBar(0, self.maxiter, prefix = self.alg, suffix = 'Complete', length = 25)
self.t = time.clock()
for i in range(self.iter,self.maxiter,1):
if self.stop == True:
break
#print('iteration', i+1, 'out of', self.maxiter)
self.update()
self.currentIter = i+1
# print progress bar
SGD.printProgress(self)
# Update the objective and gradient
if self.maxiter > 1: # since objFun and gradFun are optional for 1 iteration
SGD.evaluateObjFn(self)
SGD.evaluateGradFn(self)
SGD.stopCrit(self)
def getMoments(self):
"""
This returns the updated moments
"""
return self.m, self.v
class Adadelta(SGD):
"""
==============================================================================
| ADADELTA class |
| derived class from Stochastic Gradient Descent |
==============================================================================
Initialization:
add = Adadelta(gradHist, updatehist, rho, obj, grad, eta, param,
iter, maxIter, objFun, gradFun, lowerBound, upperBound)
NOTE: gradHist: historical information of gradients
(array of dimension nparam-by-1)
this should equal to zero for 1st iteration
==============================================================================
Attributes: (all private)
grad: Gradient information (array of dimension nParam-by-1)
eta: learning rate = 1 by default
param: the parameter vector (array of dimension nParam-by-1)
nParam: number of parameters
gradHist: gradient history accumulator (see the algorithm)
updateHist: parameter update history accumulator
epsilon: square-root of machine-precision
(required to avoid division by zero)
rho: exponential decay rate (0.95 may be a good choice)
iter: iteration number (optional)
maxIter: maximum iteration number (optional input, default = 1)
objFun: function handle to evaluate the objective
(not required for maxit = 1 )
gradFun: function handle to evaluate the gradient
(not required for maxit = 1 )
lowerBound: lower bound for the parameters (optional input)
upperBound: upper bound for the parameters (optional input)
stopGrad: stopping criterion based on 2-norm of gradient vector
(default 10^-6)
alg: algorithm used
__version__: version of the code
==============================================================================
Methods:
Public:
performIter:performs all the iterations inside a for loop
getGradHist:returns gradient history (default is zero)
Inherited:
getParam: returns the parameter values
getObj: returns the current objective value
getGrad: returns the current gradient information
getParamHist: returns parameter update history
Private: (should not be called outside this class file)
__init__: initialization
update: performs one iteration of Adadelta
Inherited:
evaluateObjFn: evaluates the objective function
evaluateGradFn: evaluates the gradients
satisfyBounds: satisfies the parameter bounds
learningSchedule: learning schedule
stopCrit: check stopping criteria
==============================================================================
Reference: Zeiler, Matthew D.
"Adadelta: an adaptive learning rate method."
arXiv preprint arXiv:1212.5701 (2012).
==============================================================================
written by Subhayan De (email: [email protected]), July, 2018.
==============================================================================
"""
def __init__(self,gradHist=0.0,updateHist=0.0,rho=0.95,**kwargs):
""" Initialize the Adadelta class object.
This can be used to perform one iteration of Adadelta.
"""
self.alg = 'Adadelta'
SGD.printAlg(self)
SGD.__init__(self,**kwargs)
self.epsilon=np.finfo(float).eps # The machine precision
# Initialize gradient history
if np.sum(gradHist) != 0.0:
if np.size(gradHist) != self.nParam:
raise ValueError('Gradient history dimension mismatch')
else:
self.gradHist=np.reshape(gradHist,(self.nParam))
else:
self.gradHist = np.zeros(self.nParam)
# Initialize parameter history
if np.sum(updateHist) != 0.0:
if np.size(updateHist) != self.nParam:
raise ValueError('Gradient history dimension mismatch')
else:
self.updateHist=np.reshape(updateHist,(self.nParam))
else:
self.updateHist = np.zeros(self.nParam)
# Initialize rho
self.rho = rho
# Set eta to 1.0
if self.eta!=1.0:
print('Learning rate = ',self.eta,'!= 1.0\nSo, the learning rate is set to 1.0\n')
self.eta = 1.0
def update(self):
"""
Perform one iteration of Adadelta
"""
self.epsilon = 1e-6
if self.currentIter<200:
self.epsilon = 0.1
else:
self.epsilon = 1e-6
SGD.learningSchedule(self)
# update gradient history acccumulator
self.gradHist+=self.rho*self.gradHist+(1.0-self.rho)*np.multiply(self.grad,self.grad); # Sum of gradient history