-
Notifications
You must be signed in to change notification settings - Fork 4
/
LSTM_RNN.py
198 lines (166 loc) · 7.64 KB
/
LSTM_RNN.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
import utils
import numpy as np
class LSTM_RNN:
def __init__(self, lr, in_dim, h_him, out_dim):
# Hyperparamaters
self.lr = lr # Learning rate
self.in_dim = in_dim # Dimension of input layer
self.h_dim = h_him # Dimension of hidden layer
self.out_dim = out_dim # Dimension of output layer
# "Variables", i.e. the parameters to learn (inspired by Tensorflow)
self.vars = {
# Weights between input and hidden state
'in_h': init_lstm_weights(h_him, in_dim, False),
# Weights between hidden state at consecutive timesteps
'h_h': init_lstm_weights(h_him, h_him, False),
# Weights between hidden and output state
'h_out': np.random.random((out_dim, h_him)) * 0.01,
# Output layer bias
'bias': np.zeros(out_dim)
}
# Holds the state of the neural network at each point in time
self.state = {
'in': {}, # Input layer
# Internal state of the LSTM cell
'c': {}, # Value of the cell
'i': {}, # Input gate
'f': {}, # Forget gate
'o': {}, # Output gate
'g': {}, # Transformation gate (before cell values are updated)
'h': {}, # Hidden layer
'out': {} # Output layer
}
# Forward Propagation
def forward_pass(self, inputs, targets, first_prev_h, first_prev_c):
loss = 0
# For each input in the set
for t in xrange(len(inputs)):
# Encode input layer
self.state['in'][t] = one_hot_vec(self.in_dim, inputs[t])
# Get previous states if available
prev_h = self.state['h'][t - 1] if t > 0 else first_prev_h
prev_c = self.state['h'][t - 1] if t > 0 else first_prev_c
# Update LSTM cell gates and value
self.state['i'][t] = sigmoid(
np.dot(self.vars['in_h']['i'], self.state['in'][t]) +
np.dot(self.vars['h_h']['i'], prev_h),
False)
self.state['f'][t] = sigmoid(
np.dot(self.vars['in_h']['f'], self.state['in'][t]) +
np.dot(self.vars['h_h']['f'], prev_h),
False)
self.state['o'][t] = sigmoid(
np.dot(self.vars['in_h']['o'], self.state['in'][t]) +
np.dot(self.vars['h_h']['o'], prev_h),
False)
self.state['g'][t] = tanh(
np.dot(self.vars['in_h']['g'], self.state['in'][t]) +
np.dot(self.vars['h_h']['g'], prev_h),
False)
self.state['c'][t] = np.multiply(prev_c, self.state['f'][t].T) +\
np.multiply(self.state['g'][t], state['i'][t].T)
# Propagating from the cell to the hidden layer
self.state['h'][t] = np.multiply(
tanh(self.state['c'][t], False),
self.state['o'][t])
# Softmax loss
loss += -np.log(state['out'][t][targets[t], 0])
# Return the loss
return loss
# Backward Bropagation
def backward_pass(self, inputs, targets, first_prev_h, first_prev_c):
# Initialising gradients
D_vars = {
'in_h': init_dict_like(self.vars['in_h']),
'h_h': init_dict_like(self.vars['h_h']),
'h_out': np.zeros_like(self.vars['h_out']),
'bias': np.zeros(self.out_dim)
}
# Initialising Adagrad memory variables
M_vars = {
'in_h': init_dict_like(self.vars['in_h']),
'h_h': init_dict_like(self.vars['h_h']),
'h_out': np.zeros_like(self.vars['h_out']),
'bias': np.zeros(self.out_dim)
}
# Backward propagation
for t in reversed(xrange(len(inputs))):
# Softmax loss
D_out = np.copy(self.state['out'][t])
D_out[targets[t]] -= 1
# Hidden to output
D_vars['h_out'] += np.dot(D_out, self.state['h'][t].T)
D_vars['bias'] += D_out
# Backpropagate through the LSTM cell
D_o = np.multiply(
self.state['h'][t],
tanh(self.state['c'][t], False))
D_c[t] += np.multiply(
self.state['h'][t],
np.multiply(
self.state['o'][t],
tanh(self.state['c'][t], True)))
D_i = np.multiply(D_c[t], self.state['g'][t])
D_g = np.multiply(D_c[t], self.state['i'][t])
prev_c = self.state['c'][t - 1] if t > 0 else first_prev_c
D_f = np.multiply(D_c[t], prev_c)
D_c[t - 1] = np.multiply(D_c[t], self.state['f'][t])
prev_h = self.state['h'][t - 1] if t > 0 else first_prev_h
D_prime = {}
D_prime['g'] = np.multiply(
D_g,
(np.dot(self.vars['in_h']['g'], self.state['in'][t]) +
np.dot(self.vars['h_h']['g'], prev_h)))
D_prime['i'] = np.multiply(
D_i,
np.multiply(self.state['i'][t], 1 - self.state['i'][t]))
D_prime['f'] = np.multiply(
D_f,
np.multiply(self.state['f'][t], 1 - self.state['f'][t]))
D_prime['o'] = np.multiply(
D_o, np.multiply(self.state['o'][t], 1 - self.state['o'][t]))
for k, d in D_prime.iteritems():
# Multiply the first set of gradients by the input
D_vars['in_h'][k] = np.dot(d, self.state['in'][t].T)
# Multiply the second set by the previous hidden state
D_vars['h_h'][k] = np.dot(d, prev_h.T)
# Adagrad parameter update
for p, D_p, M_p in zip(
[self.vars['in_h']['i'], self.vars['in_h']['f'],
self.vars['in_h']['o'], self.vars['in_h']['g'],
self.vars['h_h']['i'], self.vars['h_h']['f'],
self.vars['h_h']['o'], self.vars['h_h']['g'],
self.vars['h_out'], self.vars['bias']],
[D_vars['in_h']['i'], D_vars['in_h']['f'], D_vars['in_h']['o'],
D_vars['in_h']['g'],
D_vars['h_h']['i'], D_vars['h_h']['f'], D_vars['h_h']['o'],
D_vars['h_h']['g'], D_vars['h_out'],
D_vars['bias']],
[M_vars['in_h']['i'], M_vars['in_h']['f'], M_vars['in_h']['o'],
M_vars['in_h']['g'],
M_vars['h_h']['i'], M_vars['h_h']['f'], M_vars['h_h']['o'],
M_vars['h_h']['g'], M_vars['h_out'],
M_vars['bias']]):
M_p += D_p * D_p
p += -(self.lr) * D_p / np.sqrt(M_p + 1e-8) # Avoiding x / 0
# Return latest hidden state
return self.state['h'][len(inputs) - 1]
# The training function
def train(self, iterations, inputs, targets, slice_len):
n = 0 # Iteration count
p = 0 # Pointer to the position in the data
while n <= iterations:
# Resetting pointers and states if we reach the end of our data
if (p + slice_len + 1 >= len(inputs)) or n == 0:
p = 0
h = np.zeros((self.h_dim, 1))
c = np.zeros((self.h_dim, 1))
# Slicing the inputs we want for this pass
inputs_slice = inputs[p:p + slice_len]
targets_slice = targets[p:p + slice_len]
# Forward Propogation
loss = self.forward_pass(inputs_slice, targets_slice, h, c)
# Backwards Propogation
h = self.backward_pass(inputs_slice, targets_slice, h, c)
p += slice_len
n += 1