-
Notifications
You must be signed in to change notification settings - Fork 12
/
learning_method.py
executable file
·215 lines (179 loc) · 7.6 KB
/
learning_method.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
import numpy as np
import theano
import theano.tensor as T
from collections import OrderedDict
floatX = theano.config.floatX
device = theano.config.device
class LearningMethod:
def __init__(self, clip=None):
"""
Initialization
"""
self.clip = clip
def get_gradients(self, cost, params):
"""
Compute gradients.
"""
if self.clip is None:
return T.grad(cost, params)
else:
assert self.clip > 0
return T.grad(
theano.gradient.grad_clip(cost, -1 * self.clip, self.clip),
params
)
def get_updates(self, method, cost, params, *args, **kwargs):
"""
Compute updates.
"""
if method == 'sgd':
updates = self.sgd(cost, params, **kwargs)
elif method == 'sgdmomentum':
updates = self.sgdmomentum(cost, params, **kwargs)
elif method == 'adagrad':
updates = self.adagrad(cost, params, **kwargs)
elif method == 'adadelta':
updates = self.adadelta(cost, params, **kwargs)
elif method == 'adam':
updates = self.adam(cost, params, **kwargs)
elif method == 'rmsprop':
updates = self.rmsprop(cost, params, **kwargs)
elif method == 'dm_rmsprop':
updates = self.dm_rmsprop(cost, params, **kwargs)
else:
raise("Not implemented learning method: %s" % method)
return updates
def sgd(self, cost, params, lr=0.01):
"""
Stochatic gradient descent.
"""
lr = theano.shared(np.float32(lr).astype(floatX))
gradients = self.get_gradients(cost, params)
updates = []
for p, g in zip(params, gradients):
updates.append((p, p - lr * g))
return updates
def sgdmomentum(self, cost, params, lr=0.01, momentum=0.9):
"""
Stochatic gradient descent with momentum. Momentum has to be in [0, 1)
"""
# Check that the momentum is a correct value
assert 0 <= momentum < 1
lr = theano.shared(np.float32(lr).astype(floatX))
momentum = theano.shared(np.float32(momentum).astype(floatX))
gradients = self.get_gradients(cost, params)
velocities = [theano.shared(np.zeros_like(param.get_value(borrow=True)).astype(floatX)) for param in params]
updates = []
for param, gradient, velocity in zip(params, gradients, velocities):
new_velocity = momentum * velocity - lr * gradient
updates.append((velocity, new_velocity))
updates.append((param, param + new_velocity))
return updates
def adagrad(self, cost, params, lr=1.0, epsilon=1e-6):
"""
Adagrad. Based on http://www.ark.cs.cmu.edu/cdyer/adagrad.pdf
"""
lr = theano.shared(np.float32(lr).astype(floatX))
epsilon = theano.shared(np.float32(epsilon).astype(floatX))
gradients = self.get_gradients(cost, params)
gsums = [theano.shared(np.zeros_like(param.get_value(borrow=True)).astype(floatX)) for param in params]
updates = []
for param, gradient, gsum in zip(params, gradients, gsums):
new_gsum = gsum + gradient ** 2.
updates.append((gsum, new_gsum))
updates.append((param, param - lr * gradient / (T.sqrt(gsum + epsilon))))
return updates
def adadelta(self, cost, params, rho=0.95, epsilon=1e-6):
"""
Adadelta. Based on:
http://www.matthewzeiler.com/pubs/googleTR2012/googleTR2012.pdf
"""
rho = theano.shared(np.float32(rho).astype(floatX))
epsilon = theano.shared(np.float32(epsilon).astype(floatX))
gradients = self.get_gradients(cost, params)
accu_gradients = [
theano.shared(
np.zeros_like(param.get_value(borrow=True)).astype(floatX)
)
for param in params
]
accu_deltas = [
theano.shared(
np.zeros_like(param.get_value(borrow=True)).astype(floatX)
)
for param in params
]
updates = []
for param, gradient, accu_gradient, accu_delta in zip(params, gradients, accu_gradients, accu_deltas):
new_accu_gradient = rho * accu_gradient + (1. - rho) * gradient ** 2.
delta_x = - T.sqrt((accu_delta + epsilon) / (new_accu_gradient + epsilon)) * gradient
new_accu_delta = rho * accu_delta + (1. - rho) * delta_x ** 2.
updates.append((accu_gradient, new_accu_gradient))
updates.append((accu_delta, new_accu_delta))
updates.append((param, param + delta_x))
return updates
def adam(self, cost, params, lr=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8):
"""
Adam. Based on http://arxiv.org/pdf/1412.6980v4.pdf
"""
updates = []
gradients = self.get_gradients(cost, params)
t = theano.shared(np.float32(1.).astype(floatX))
for param, gradient in zip(params, gradients):
value = param.get_value(borrow=True)
m_prev = theano.shared(np.zeros(value.shape, dtype=value.dtype),
broadcastable=param.broadcastable)
v_prev = theano.shared(np.zeros(value.shape, dtype=value.dtype),
broadcastable=param.broadcastable)
m = beta1 * m_prev + (1. - beta1) * gradient
v = beta2 * v_prev + (1. - beta2) * gradient ** 2.
m_hat = m / (1. - beta1 ** t)
v_hat = v / (1. - beta2 ** t)
theta = param - (lr * m_hat) / (T.sqrt(v_hat) + epsilon)
updates.append((m_prev, m))
updates.append((v_prev, v))
updates.append((param, theta))
updates.append((t, t + 1.))
return updates
def rmsprop(self, cost, params, lr=0.0002, rho=0.99, epsilon=1e-6):
"""
RMSProp.
"""
gradients = self.get_gradients(cost, params)
accumulators = [
theano.shared(
np.zeros_like(param.get_value(borrow=True)).astype(floatX)
)
for param in params
]
updates = []
for param, gradient, accumulator in zip(params, gradients, accumulators):
new_accumulator = rho * accumulator + (1 - rho) * gradient ** 2
updates.append((accumulator, new_accumulator))
new_param = param - lr * gradient / T.sqrt(new_accumulator + epsilon)
updates.append((param, new_param))
return updates
def dm_rmsprop(self, cost, params, lr=0.00025, rho=0.95, epsilon=0.01):
"""
DeepMind RMSProp.
Scale learning rates by dividing with the moving average
of the root mean squared (RMS) gradients.
"""
gradients = self.get_gradients(cost, params)
updates = OrderedDict()
for param, grad in zip(params, gradients):
value = param.get_value(borrow=True)
acc_grad = theano.shared(
np.zeros(value.shape, dtype=value.dtype), broadcastable=param.broadcastable
)
acc_grad_new = rho * acc_grad + (1 - rho) * grad
acc_rms = theano.shared(
np.zeros(value.shape, dtype=value.dtype), broadcastable=param.broadcastable
)
acc_rms_new = rho * acc_rms + (1 - rho) * grad ** 2
updates[acc_grad] = acc_grad_new
updates[acc_rms] = acc_rms_new
updates[param] = (param - lr *
(grad /
T.sqrt(acc_rms_new - acc_grad_new ** 2 + epsilon)))
return updates