-
Notifications
You must be signed in to change notification settings - Fork 0
/
optimizers.py
192 lines (156 loc) · 6.72 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
"""
Naive optimizers with numeric gradient
"""
import math
import numpy as np
def numeric_gradient(x, f):
x = np.asmatrix(x, np.float64)
d_x = np.zeros_like(x)
fx = f(x)
r = [None]
if np.shape(fx) != () and np.shape(fx) != np.shape(d_x):
for rank in range(len(np.shape(fx))):
if np.shape(fx)[rank] != np.shape(d_x)[rank]:
r[0] = rank
break
it = np.nditer(d_x, flags=['multi_index'])
while not it.finished:
like_x = np.copy(x)
dx = like_x[it.multi_index] * 1e-8
like_x[it.multi_index] += dx
derivative = (f(like_x) - fx) / dx
if np.shape(derivative) == ():
d_x[it.multi_index] = derivative
elif np.shape(derivative) == np.shape(d_x):
d_x[it.multi_index] = derivative[it.multi_index]
elif r[0] is not None:
for i in range(np.shape(derivative)[r[0]]):
location = list(it.multi_index)
location[r[0]] = i
d_x[it.multi_index] += derivative[tuple(location)]
it.iternext()
return d_x
class BaseOptimizer(object):
# noinspection PyMethodMayBeStatic
def optimize(self, params):
yield NotImplementedError()
class SGD(BaseOptimizer):
def __init__(self, function, learning_rate=0.01, gradient_func=numeric_gradient):
self.function = function
self.learning_rate = learning_rate
self.gradient_func = gradient_func
def optimize(self, params):
d_params = self.gradient_func(params, self.function)
for i in range(len(params)):
params[i] -= self.learning_rate * d_params[i]
class Momentum(BaseOptimizer):
def __init__(self, function, learning_rate=0.01, gradient_func=numeric_gradient, momentum_strength=0.9):
self.function = function
self.learning_rate = learning_rate
self.gradient_func = gradient_func
self.momentum_strength = momentum_strength
self.last_v = 0
def optimize(self, params):
d_params = self.gradient_func(params, self.function)
for i in range(len(params)):
v = self.momentum_strength*self.last_v + self.learning_rate*d_params[i]
params[i] -= v
self.last_v = v
class NEG(BaseOptimizer):
"""
Nestrov Accelerated Gradient
"""
def __init__(self, function, learning_rate=0.01, gradient_func=numeric_gradient, momentum_strength=0.9):
self.function = function
self.learning_rate = learning_rate
self.gradient_func = gradient_func
self.momentum_strength = momentum_strength
self.last_v = 0
def optimize(self, params):
d_params = self.gradient_func([param - self.momentum_strength*self.last_v for param in params],
self.function)
for i in range(len(params)):
v = self.momentum_strength*self.last_v + self.learning_rate*d_params[i]
params[i] -= v
self.last_v = v
class Adagrad(BaseOptimizer):
def __init__(self, function, learning_rate=0.01, gradient_func=numeric_gradient):
self.function = function
self.learning_rate = learning_rate
self.gradient_func = gradient_func
self.G = []
def optimize(self, params):
if not len(self.G) == len(params):
self.G = [0 for _ in range(len(params))]
d_params = self.gradient_func(params,
self.function)
for i in range(len(params)):
g = d_params[i]
self.G[i] += g ** 2
params[i] -= (self.learning_rate / math.sqrt(self.G[i] + 1e-8)) * g
class Adadelta(BaseOptimizer):
def __init__(self, function, decay=0.9, gradient_func=numeric_gradient):
self.function = function
self.decay = decay
self.gradient_func = gradient_func
self.decaying_g = []
self.decaying_d = []
def optimize(self, params):
if not len(self.decaying_g) == len(params):
self.decaying_g = [0 for _ in range(len(params))]
if not len(self.decaying_d) == len(params):
self.decaying_d = [0 for _ in range(len(params))]
d_params = self.gradient_func(params,
self.function)
for i in range(len(params)):
g = d_params[i]
self.decay_update(self.decaying_g, i, g)
d = -(math.sqrt(self.decaying_d[i] + 1e-8) / math.sqrt(self.decaying_g[i] + 1e-8)) * g
params[i] += d
self.decay_update(self.decaying_d, i, d)
def decay_update(self, l, i, value):
l[i] = self.decay*l[i] + (1 - self.decay) * (value ** 2)
class RMSProp(BaseOptimizer):
def __init__(self, function, learning_rate=0.001, decay=0.9, gradient_func=numeric_gradient):
self.function = function
self.learning_rate = learning_rate
self.decay = decay
self.gradient_func = gradient_func
self.decaying_g = []
def optimize(self, params):
if not len(self.decaying_g) == len(params):
self.decaying_g = [0 for _ in range(len(params))]
d_params = self.gradient_func(params,
self.function)
for i in range(len(params)):
g = d_params[i]
self.decay_update(self.decaying_g, i, g)
d = -(self.learning_rate / math.sqrt(self.decaying_g[i] + 1e-8)) * g
params[i] += d
def decay_update(self, l, i, value):
l[i] = self.decay*l[i] + (1 - self.decay) * (value ** 2)
class Adam(BaseOptimizer):
def __init__(self, function, learning_rate=0.001, decay1=0.9, decay2=0.999, gradient_func=numeric_gradient):
self.function = function
self.learning_rate = learning_rate
self.decay1 = decay1
self.decay2 = decay2
self.gradient_func = gradient_func
self.decaying_v = []
self.decaying_m = []
def optimize(self, params):
if not len(self.decaying_v) == len(params):
self.decaying_v = [0 for _ in range(len(params))]
if not len(self.decaying_m) == len(params):
self.decaying_m = [0 for _ in range(len(params))]
d_params = self.gradient_func(params,
self.function)
for i in range(len(params)):
self.decay_updates(i, d_params[i])
m_hat = self.decaying_m[i] / (1 - self.decay1)
v_hat = self.decaying_v[i] / (1 - self.decay2)
d = -(self.learning_rate / (math.sqrt(v_hat) + 1e-8)) * m_hat
params[i] += d
def decay_updates(self, i, value):
self.decaying_m[i] = self.decay1 * self.decaying_m[i] + (1 - self.decay1) * value
self.decaying_v[i] = self.decay2 * self.decaying_v[i] + (1 - self.decay2) * (value ** 2)