-
Notifications
You must be signed in to change notification settings - Fork 1
/
rnn_changed.py
186 lines (142 loc) · 5.08 KB
/
rnn_changed.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
import numpy as np
import collections
import pdb
class RNN3:
def __init__(self,wvecDim, middleDim, outputDim,numWords,mbSize=30,rho=1e-4):
self.wvecDim = wvecDim
self.outputDim = outputDim
self.middleDim = middleDim
self.numWords = numWords
self.mbSize = mbSize
self.defaultVec = lambda : np.zeros((wvecDim,))
self.rho = rho
def initParams(self):
np.random.seed(12341)
def costAndGrad(self,mbdata,test=False):
"""
Each datum in the minibatch is a tree.
Forward prop each tree.
Backprop each tree.
Returns
cost
Gradient w.r.t. W1, W2, Ws, b1, b2, bs
Gradient w.r.t. L in sparse form.
or if in test mode
Returns
cost, correctArray, guessArray, total
"""
cost = 0.0
correct = []
guess = []
total = 0.0
self.L, self.W1, self.b1, self.W2, self.b2, self.Ws, self.bs = self.stack
# Zero gradients
self.dW1[:] = 0
self.db1[:] = 0
self.dW2[:] = 0
self.db2[:] = 0
self.dWs[:] = 0
self.dbs[:] = 0
self.dL = collections.defaultdict(self.defaultVec)
# Forward prop each tree in minibatch
for tree in mbdata:
c,tot = self.forwardProp(tree.root,correct,guess)
cost += c
total += tot
if test:
return (1./len(mbdata))*cost,correct, guess, total
# Back prop each tree in minibatch
for tree in mbdata:
self.backProp(tree.root)
# scale cost and grad by mb size
scale = (1./self.mbSize)
for v in self.dL.itervalues():
v *=scale
# Add L2 Regularization
cost += (self.rho/2)*np.sum(self.W1**2)
cost += (self.rho/2)*np.sum(self.W2**2)
cost += (self.rho/2)*np.sum(self.Ws**2)
return scale*cost,[self.dL,scale*(self.dW1 + self.rho*self.W1),scale*self.db1,
scale*(self.dW2 + self.rho*self.W2),scale*self.db2,
scale*(self.dWs+self.rho*self.Ws),scale*self.dbs]
def forwardProp(self,node, correct=[], guess=[]):
cost = total = 0.0
return cost, total + 1
def backProp(self,node,error=None):
# Clear nodes
node.fprop = False
def updateParams(self,scale,update,log=False):
"""
Updates parameters as
p := p - scale * update.
If log is true, prints root mean square of parameter
and update.
"""
if log:
for P,dP in zip(self.stack[1:],update[1:]):
pRMS = np.sqrt(np.mean(P**2))
dpRMS = np.sqrt(np.mean((scale*dP)**2))
print "weight rms=%f -- update rms=%f"%(pRMS,dpRMS)
self.stack[1:] = [P+scale*dP for P,dP in zip(self.stack[1:],update[1:])]
# handle dictionary update sparsely
dL = update[0]
for j in dL.iterkeys():
self.L[:,j] += scale*dL[j]
def toFile(self,fid):
import cPickle as pickle
pickle.dump(self.stack,fid)
def fromFile(self,fid):
import cPickle as pickle
self.stack = pickle.load(fid)
def check_grad(self,data,epsilon=1e-6):
cost, grad = self.costAndGrad(data)
err1 = 0.0
count = 0.0
print "Checking dWs, dW1 and dW2..."
for W,dW in zip(self.stack[1:],grad[1:]):
W = W[...,None] # add dimension since bias is flat
dW = dW[...,None]
for i in xrange(W.shape[0]):
for j in xrange(W.shape[1]):
W[i,j] += epsilon
costP,_ = self.costAndGrad(data)
W[i,j] -= epsilon
numGrad = (costP - cost)/epsilon
err = np.abs(dW[i,j] - numGrad)
err1+=err
count+=1
if 0.001 > err1/count:
print "Grad Check Passed for dW"
else:
print "Grad Check Failed for dW: Sum of Error = %.9f" % (err1/count)
# check dL separately since dict
dL = grad[0]
L = self.stack[0]
err2 = 0.0
count = 0.0
print "Checking dL..."
for j in dL.iterkeys():
for i in xrange(L.shape[0]):
L[i,j] += epsilon
costP,_ = self.costAndGrad(data)
L[i,j] -= epsilon
numGrad = (costP - cost)/epsilon
err = np.abs(dL[j][i] - numGrad)
err2+=err
count+=1
if 0.001 > err2/count:
print "Grad Check Passed for dL"
else:
print "Grad Check Failed for dL: Sum of Error = %.9f" % (err2/count)
if __name__ == '__main__':
import tree as treeM
train = treeM.loadTrees()
numW = len(treeM.loadWordMap())
wvecDim = 10
middleDim = 10
outputDim = 5
rnn = RNN3(wvecDim,middleDim,outputDim,numW,mbSize=4)
rnn.initParams()
mbData = train[:4]
print "Numerical gradient check..."
rnn.check_grad(mbData)