-
Notifications
You must be signed in to change notification settings - Fork 1
/
train.py
266 lines (201 loc) · 8.65 KB
/
train.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
import cPickle
import numpy as np
from model import LSTM, Weights
import sys
from IPython import embed
from numba import cuda
def train_encoder(lstm, x, y, epochs):
outputs = []
for i in range(epochs):
for x_i in x:
outputs.append(lstm.predict(x_i))
BTTEncoder(outputs, y, lstm)
def train(lstm, x, y, epochs, network_type):
outputs = list()
for i in range(epochs):
print '\nEpoch %d' % i
if network_type == 'encoder':
for x_i in x:
outputs.append(lstm.predict(x_i))
BTTEncoder(outputs, x, y, lstm)
elif network_type == 'decoder':
for y_i, x_i in zip(y, x):
outputs.append(lstm.predict(y_i[:-1], x_i[-1].h))
print 'Before BTT Decoder'
y_input = [x[:-1] for x in y]
y_output = [x[1:] for x in y]
BTTDecoder(outputs, y_input, y_output, lstm)
outputs = list()
def BTTEncoder(outputs, x, y, lstm):
diff = Weights(lstm.input_nodes,lstm.hidden_nodes,lstm.output_nodes, 0)
total_cost = 0
for output, yi, xi in zip(outputs, y, x):
total_cost += cost(yi, output[-1].v)
de_dsoftmax = error_gradient(output[-1].v, yi)
dsoftmax_dh = dsoftmax_dx(output[-1].h)
de_dh = de_dsoftmax*dsoftmax_dh
de_ds = np.zeros_like(de_dh)
diff.whv += de_dh
diff.bv += de_dsoftmax
for i in range(len(xi) - 1, -1, -1):
state = output[i+1]
# lstm cell gradients
dh_ds = state.o
dh_do = state.s
# s to gates gradients
ds_dg = state.i
ds_di = state.g
ds_df = output[i].s
# gate to activation gradients
dg_dtanh = 1. - state.g**2
di_dsigmoid = state.i*(1-state.i)
df_dsigmoid = state.f*(1-state.f)
do_dsigmoid = state.o*(1-state.o)
dtanh_dwgx = xi[i]
dtanh_dwgh = output[i].h
dtanh_dbg = 1
dsigmoid_dwix = xi[i]
dsigmoid_dwih = output[i].h
dsigmoid_dbi = 1
dsigmoid_dwfx = xi[i]
dsigmoid_dwfh = output[i].h
dsigmoid_dbf = 1
dsigmoid_dwox = xi[i]
dsigmoid_dwoh = output[i].h
dsigmoid_dbo = 1
# g gradients
diff.wgx += np.dot(dtanh_dwgx, ((de_dh * dh_ds + de_ds) * ds_dg * dg_dtanh).T)
diff.wgh += ((de_dh * dh_ds + de_ds) * ds_dg * dg_dtanh * dtanh_dwgh).T
diff.bg += (de_dh * dh_ds + de_ds) * ds_dg * dg_dtanh * dtanh_dbg
# i gradients
diff.wix += np.dot(dsigmoid_dwix, ((de_dh * dh_ds + de_ds) * ds_di * di_dsigmoid).T)
diff.wih += ((de_dh * dh_ds + de_ds) * ds_di * di_dsigmoid * dsigmoid_dwih).T
diff.bi += (de_dh * dh_ds + de_ds) * ds_di * di_dsigmoid * dsigmoid_dbi
# f gradients
diff.wfx += np.dot(dsigmoid_dwfx, (de_dh*dh_ds*ds_df*df_dsigmoid).T)
diff.wfh += (de_dh*dh_ds*ds_df*df_dsigmoid*dsigmoid_dwfh).T
diff.bf += de_dh*dh_ds*ds_df*df_dsigmoid*dsigmoid_dbf
# o gradients
diff.wox += np.dot(dsigmoid_dwox, (de_dh * dh_do * do_dsigmoid).T)
diff.woh += (de_dh * dh_do * do_dsigmoid * dsigmoid_dwoh).T
diff.bo += de_dh * dh_do * do_dsigmoid * dsigmoid_dbo
de_ds = (de_dh * dh_ds + de_ds) * state.f
de_dh = (diff.wgh + diff.wih + diff.wfh + diff.woh).T
update_weights(lstm, diff, 0.8)
print total_cost
def update_weights(lstm, diff, learning_rate):
lstm.weights.wgx -= diff.wgx * learning_rate
lstm.weights.wgh -= diff.wgh * learning_rate
lstm.weights.bg -= diff.bg * learning_rate
lstm.weights.wix -= diff.wix * learning_rate
lstm.weights.wih -= diff.wih * learning_rate
lstm.weights.bi -= diff.bi * learning_rate
lstm.weights.wfx -= diff.wfx * learning_rate
lstm.weights.wfh -= diff.wfh * learning_rate
lstm.weights.bf -= diff.bf * learning_rate
lstm.weights.wox -= diff.wox * learning_rate
lstm.weights.woh -= diff.woh * learning_rate
lstm.weights.bo -= diff.bo * learning_rate
lstm.weights.whv -= diff.whv * learning_rate
lstm.weights.bv -= diff.bv * learning_rate
def BTTDecoder(outputs, x, y, lstm):
diff = Weights(lstm.input_nodes, lstm.hidden_nodes, lstm.output_nodes, 0)
count = 0
for output, yi, xi in zip(outputs, y, x):
de_dh = np.zeros((diff.hidden_nodes, diff.output_nodes), dtype='float64')
de_ds = np.zeros_like(de_dh, dtype='float64')
for i in range(len(xi) - 1, -1, -1):
print 'output shape', len(output), len(yi)
state = output[i + 1]
de_dsoftmax = error_gradient(output[i+1].v, yi[i])
dsoftmax_dh = dsoftmax_dx(output[i+1].h)
print de_dsoftmax.shape, dsoftmax_dh.shape
de_dh += np.dot(dsoftmax_dh.astype('float64'), de_dsoftmax.T.astype('float64'))
diff.whv += de_dh
diff.bv += de_dsoftmax
# lstm cell gradients
dh_ds = state.o
dh_do = state.s
# s to gates gradients
ds_dg = state.i
ds_di = state.g
ds_df = output[i].s
# gate to activation gradients
dg_dtanh = 1. - state.g ** 2
di_dsigmoid = state.i * (1 - state.i)
df_dsigmoid = state.f * (1 - state.f)
do_dsigmoid = state.o * (1 - state.o)
dtanh_dwgx = xi[i]
dtanh_dwgh = output[i].h
dtanh_dbg = 1
dsigmoid_dwix = xi[i]
dsigmoid_dwih = output[i].h
dsigmoid_dbi = 1
dsigmoid_dwfx = xi[i]
dsigmoid_dwfh = output[i].h
dsigmoid_dbf = 1
dsigmoid_dwox = xi[i]
dsigmoid_dwoh = output[i].h
dsigmoid_dbo = 1
# g gradients
diff.wgx += np.dot(dtanh_dwgx, ((de_dh * dh_ds + de_ds) * ds_dg * dg_dtanh).T)
diff.wgh += ((de_dh * dh_ds + de_ds) * ds_dg * dg_dtanh * dtanh_dwgh).T
diff.bg += (de_dh * dh_ds + de_ds) * ds_dg * dg_dtanh * dtanh_dbg
# i gradients
diff.wix += np.dot(dsigmoid_dwix, ((de_dh * dh_ds + de_ds) * ds_di * di_dsigmoid).T)
diff.wih += ((de_dh * dh_ds + de_ds) * ds_di * di_dsigmoid * dsigmoid_dwih).T
diff.bi += (de_dh * dh_ds + de_ds) * ds_di * di_dsigmoid * dsigmoid_dbi
# f gradients
diff.wfx += np.dot(dsigmoid_dwfx, (de_dh*dh_ds*ds_df*df_dsigmoid).T)
diff.wfh += (de_dh*dh_ds*ds_df*df_dsigmoid*dsigmoid_dwfh).T
diff.bf += de_dh*dh_ds*ds_df*df_dsigmoid*dsigmoid_dbf
# o gradients
diff.wox += np.dot(dsigmoid_dwox, (de_dh * dh_do * do_dsigmoid).T)
diff.woh += (de_dh * dh_do * do_dsigmoid * dsigmoid_dwoh).T
diff.bo += de_dh * dh_do * do_dsigmoid * dsigmoid_dbo
de_ds = (de_dh * dh_ds + de_ds) * state.f
de_dh = (diff.wgh + diff.wih + diff.wfh + diff.woh).T
update_weights(lstm, diff, 0.8)
def error_gradient(output, y):
return -(y - output)
def cost(y, output):
c = 0
for i in range(y.shape[0]):
c += 0.5 * (y[i] - output[i]) ** 2 / len(y)
return c
def dsoftmax_dx(x):
ex = np.exp(x - np.max(x))
dex = (ex*ex.sum() + ex*ex) / (ex.sum() ** 2)
return dex
def main():
print 'Loading Data'
x = cPickle.load(open('english_matrices.pkl', 'rb'))
y = cPickle.load(open('chinese_matrices.pkl', 'rb'))
print 'Done'
# x = np.random.random((10, 10, 50, 1))
# y = np.random.random((10, 10, 50, 1))
encoder_lstm = LSTM(50, 100, 50)
encoder_lstm.load_weights('encoder.pkl')
outputs = []
for i in range(10000):
outputs.append(encoder_lstm.predict(x[i]))
# for _ in range(10):
# for i in range(20):
# idx_start = i*500
# idx_end = min((i+1)*500, len(x))
# sys.stdout.write('\n\nTraining Data %d - %d' % (idx_start, idx_end))
# train(encoder_lstm, x[idx_start:idx_end], y[idx_start:idx_end][0], 50, 'encoder')
# encoder_lstm.save_weights('encoder.pkl')
# outputs = encoder_lstm.predict(x[:10000])
# encoder_lstm.save_weights('encoder.pkl')
embed()
decoder_lstm = LSTM(50, 100, 50)
for _ in range(4):
for i in range(20):
idx_start = i * 500
idx_end = min((i + 1) * 500, len(x))
sys.stdout.write('\n\nTraining Data %d - %d' % (idx_start, idx_end))
train(decoder_lstm, outputs[idx_start:idx_end], y[idx_start:idx_end], 50, 'decoder')
decoder_lstm.save_weights('decoder.pkl')
if __name__ == '__main__':
main()