-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDependencyParser.py
More file actions
570 lines (425 loc) · 19.1 KB
/
DependencyParser.py
File metadata and controls
570 lines (425 loc) · 19.1 KB
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
import collections
import tensorflow as tf
import numpy as np
import pickle
import math
from progressbar import ProgressBar
from DependencyTree import DependencyTree
from ParsingSystem import ParsingSystem
from Configuration import Configuration
import Config
import Util
"""
This script defines a transition-based dependency parser which makes
use of a classifier powered by a neural network. The neural network
accepts distributed representation inputs: dense, continuous
representations of words, their part of speech tags, and the labels
which connect words in a partial dependency parse.
This is an implementation of the method described in
Danqi Chen and Christopher Manning. A Fast and Accurate Dependency Parser Using Neural Networks. In EMNLP 2014.
Author: Danqi Chen, Jon Gauthier
Modified by: Heeyoung Kwon (2017)
Modified by: Jun S. Kang (2018 Mar)
"""
class DependencyParserModel(object):
def __init__(self, graph, embedding_array, Config):
self.build_graph(graph, embedding_array, Config)
def build_graph(self, graph, embedding_array, Config):
"""
:param graph:
:param embedding_array:
:param Config:
:return:
"""
with graph.as_default():
self.embeddings = tf.Variable(embedding_array, dtype=tf.float32)
"""
===================================================================
Define the computational graph with necessary variables.
1) You may need placeholders of:
- Many parameters are defined at Config: batch_size, n_Tokens, etc
- # of transitions can be get by calling parsing_system.numTransitions()
self.train_inputs =
self.train_labels =
self.test_inputs =
...
2) Call forward_pass and get predictions
...
self.prediction = self.forward_pass(embed, weights_input, biases_input, weights_output)
3) Implement the loss function described in the paper
- lambda is defined at Config.lam
...
self.loss =
===================================================================
"""
# Placeholders from Config
maxIteration = Config.max_iter
batchSize = Config.batch_size
hiddenSize = Config.hidden_size
embeddingSize = Config.embedding_size
learningRate = Config.learning_rate
displayStep = Config.display_step
validationStep = Config.validation_step
numTokens = Config.n_Tokens
lambdaParam = Config.lam
numTransitions = parsing_system.numTransitions()
flat_dimension = numTokens * embeddingSize
self.train_inputs = tf.placeholder(tf.int32, [None, numTokens])
self.train_labels = tf.placeholder(tf.int32, [None, numTransitions])
self.test_inputs = tf.placeholder(tf.int32, [numTokens, ])
mean = 0.0
stddev = math.sqrt(1.0/parsing_system.numTransitions())
weights_input = tf.Variable(tf.random_normal([hiddenSize, numTokens * embeddingSize], mean=mean, stddev=stddev))
weights_output = tf.Variable(tf.random_normal([parsing_system.numTransitions(), hiddenSize], mean=mean, stddev=stddev))
biases_input = tf.Variable(tf.zeros([hiddenSize, 1]))
self.b2 = tf.Variable(tf.zeros([parsing_system.numTransitions(), 1]))
train_embed = tf.nn.embedding_lookup(self.embeddings, self.train_inputs)
train_embed = tf.reshape(train_embed, [-1, numTokens * embeddingSize])
self.prediction = self.forward_pass(train_embed, weights_input, biases_input, weights_output)
self.prediction = tf.transpose(self.prediction)
self.loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.prediction, labels=tf.argmax(tf.transpose(self.train_labels)))
l2_loss = tf.multiply(lambdaParam, tf.nn.l2_loss(weights_input))
self.loss = tf.add(self.loss, l2_loss)
self.loss = tf.reduce_mean(self.loss)
optimizer = tf.train.GradientDescentOptimizer(learningRate)
# Disable gradient clipping
#self.app = optimizer.minimize(self.loss)
# Enable gradient clipping
grads = optimizer.compute_gradients(self.loss)
clipped_grads = [(tf.clip_by_norm(grad, 5), var) for grad, var in grads]
self.app = optimizer.apply_gradients(clipped_grads)
# For test data, we only need to get its prediction
test_embed = tf.nn.embedding_lookup(self.embeddings, self.test_inputs)
test_embed = tf.reshape(test_embed, [1, -1])
self.test_pred = self.forward_pass(test_embed, weights_input, biases_input, weights_output)
self.test_pred = tf.transpose(self.test_pred)
# intializer
self.init = tf.global_variables_initializer()
def train(self, sess, num_steps):
"""
:param sess:
:param num_steps:
:return:
"""
self.init.run()
print("Initailized")
average_loss = 0
for step in range(num_steps):
start = (step * Config.batch_size) % len(trainFeats)
end = ((step + 1) * Config.batch_size) % len(trainFeats)
if end < start:
start -= end
end = len(trainFeats)
batch_inputs, batch_labels = trainFeats[start:end], trainLabels[start:end]
feed_dict = {self.train_inputs: batch_inputs, self.train_labels: batch_labels}
_, loss_val = sess.run([self.app, self.loss], feed_dict=feed_dict)
average_loss += loss_val
if step % Config.display_step == 0:
if step > 0:
average_loss /= Config.display_step
print("Average loss at step ", step, ": ", average_loss)
average_loss = 0
if step % Config.validation_step == 0 and step != 0:
print("\nTesting on dev set at step ", step)
predTrees = []
for sent in devSents:
numTrans = parsing_system.numTransitions()
c = parsing_system.initialConfiguration(sent)
while not parsing_system.isTerminal(c):
feat = getFeatures(c)
pred = sess.run(self.test_pred, feed_dict={self.test_inputs: feat})
optScore = -float('inf')
optTrans = ""
for j in range(numTrans):
if pred[0, j] > optScore and parsing_system.canApply(c, parsing_system.transitions[j]):
optScore = pred[0, j]
optTrans = parsing_system.transitions[j]
c = parsing_system.apply(c, optTrans)
predTrees.append(c.tree)
result = parsing_system.evaluate(devSents, predTrees, devTrees)
print(result)
print("Train Finished.")
def evaluate(self, sess, testSents):
"""
:param sess:
:return:
"""
print("Starting to predict on test set")
predTrees = []
for sent in testSents:
numTrans = parsing_system.numTransitions()
c = parsing_system.initialConfiguration(sent)
while not parsing_system.isTerminal(c):
# feat = getFeatureArray(c)
feat = getFeatures(c)
pred = sess.run(self.test_pred, feed_dict={self.test_inputs: feat})
optScore = -float('inf')
optTrans = ""
for j in range(numTrans):
if pred[0, j] > optScore and parsing_system.canApply(c, parsing_system.transitions[j]):
optScore = pred[0, j]
optTrans = parsing_system.transitions[j]
c = parsing_system.apply(c, optTrans)
predTrees.append(c.tree)
print("Saved the test results.")
Util.writeConll('result_test.conll', testSents, predTrees)
def forward_pass(self, embed, weights_input, biases_input, weights_output):
"""
:param embed:
:param weights:
:param biases:
:return:
"""
"""
=======================================================
Implement the forwrad pass described in
"A Fast and Accurate Dependency Parser using Neural Networks"(2014)
=======================================================
"""
# Cube non-linearity
h = tf.pow(tf.add(tf.matmul(weights_input, tf.transpose(embed)), biases_input), 3)
#pred = tf.matmul(weights_output, h)
pred = tf.add(tf.matmul(weights_output, h), self.b2)
# Sigmoid non-linearity
#h = tf.nn.sigmoid(tf.add(tf.matmul(weights_input, tf.transpose(embed)), biases_input))
#pred = tf.matmul(weights_output, h)
#pred = tf.add(tf.matmul(weights_output, h), self.b2)
# Tanh non-linearity
#h = tf.nn.tanh(tf.add(tf.matmul(weights_input, tf.transpose(embed)), biases_input))
#pred = tf.matmul(weights_output, h)
#pred = tf.add(tf.matmul(weights_output, h), self.b2)
# Relu non-linearity
#h = tf.nn.relu(tf.add(tf.matmul(weights_input, tf.transpose(embed)), biases_input))
#pred = tf.add(tf.matmul(weights_output, h), self.b2)
#pred = tf.matmul(weights_output, h)
# Two layer network(cube,cube)
"""
#layer - 1
z1 = tf.add(tf.matmul(weights_input, tf.transpose(embed)), biases_input)
h1 = tf.pow(z1, 3)
mean = 0.1
stddev = math.sqrt(1.0 / parsing_system.numTransitions())
weights_input_2 = tf.Variable(tf.random_normal([Config.hidden_size, Config.hidden_size], mean=mean, stddev=stddev))
biases_input_2 = tf.Variable(tf.zeros([Config.hidden_size, 1]))
#layer - 2
z2 = tf.add(tf.matmul(weights_input_2, h1), biases_input_2)
h2 = tf.pow(z2, 3)
#output layer
pred = tf.matmul(weights_output, h2)
"""
# Three layer network (cube->relu->tanh)
"""
#layer - 1
z1 = tf.add(tf.matmul(weights_input, tf.transpose(embed)), biases_input)
h1 = tf.pow(z1, 3)
mean = 0.1
stddev = math.sqrt(1.0 / parsing_system.numTransitions())
weights_input_2 = tf.Variable(tf.random_normal([Config.hidden_size, Config.hidden_size], mean=mean, stddev=stddev))
biases_input_2 = tf.Variable(tf.zeros([Config.hidden_size, 1]))
#layer - 2
z2 = tf.add(tf.matmul(weights_input_2, h1), biases_input_2)
h2 = tf.nn.relu(z2)
weights_input_3 = tf.Variable(tf.random_normal([Config.hidden_size, Config.hidden_size], mean=mean, stddev=stddev))
biases_input_3 = tf.Variable(tf.zeros([Config.hidden_size, 1]))
#layer - 3
z3 = tf.add(tf.matmul(weights_input_3, h2), biases_input_3)
h3 = tf.nn.tanh(z3)
#output layer
pred = tf.matmul(weights_output, h3)
"""
# Three layer network (cube->cube->cube)
"""
z1 = tf.add(tf.matmul(weights_input, tf.transpose(embed)), biases_input)
h1 = tf.pow(z1, 3)
mean = 0.1
stddev = math.sqrt(1.0 / parsing_system.numTransitions())
weights_input_2 = tf.Variable(tf.random_normal([Config.hidden_size, Config.hidden_size], mean=mean, stddev=stddev))
biases_input_2 = tf.Variable(tf.zeros([Config.hidden_size, 1]))
#layer - 2
z2 = tf.add(tf.matmul(weights_input_2, h1), biases_input_2)
h2 = tf.pow(z2, 3)
weights_input_3 = tf.Variable(tf.random_normal([Config.hidden_size, Config.hidden_size], mean=mean, stddev=stddev))
biases_input_3 = tf.Variable(tf.zeros([Config.hidden_size, 1]))
#layer - 3
z3 = tf.add(tf.matmul(weights_input_3, h2), biases_input_3)
h3 = tf.pow(z3, 3)
#output layer
pred = tf.matmul(weights_output, h3)
"""
return pred
def genDictionaries(sents, trees):
word = []
label = []
pos = []
for s in sents:
for token in s:
word.append(token['word'])
pos.append(token['POS'])
rootLabel = None
for tree in trees:
for k in range(1, tree.n + 1):
if tree.getHead(k) == 0:
rootLabel = tree.getLabel(k)
else:
label.append(tree.getLabel(k))
if rootLabel in label:
label.remove(rootLabel)
index = 0
wordCount = [Config.UNKNOWN, Config.NULL, Config.ROOT]
wordCount.extend(collections.Counter(word))
for word in wordCount:
wordDict[word] = index
index += 1
posCount = [Config.UNKNOWN, Config.NULL, Config.ROOT]
posCount.extend(collections.Counter(pos))
for pos in posCount:
posDict[pos] = index
index += 1
labelCount = [Config.NULL, rootLabel]
labelCount.extend(collections.Counter(label))
for label in labelCount:
labelDict[label] = index
index += 1
return wordDict, posDict, labelDict
def getWordID(s):
if s in wordDict:
return wordDict[s]
else:
return wordDict[Config.UNKNOWN]
def getPosID(s):
if s in posDict:
return posDict[s]
else:
return posDict[Config.UNKNOWN]
def getLabelID(s):
if s in labelDict:
return labelDict[s]
else:
return labelDict[Config.UNKNOWN]
def getFeatures(c):
"""
=================================================================
Implement feature extraction described in
"A Fast and Accurate Dependency Parser using Neural Networks"(2014)
=================================================================
"""
fWord = []
fPos = []
fLabel = []
feature = []
# Retrieve top three words and POS from the stack
for j in range(2, -1, -1):
index = c.getStack(j)
fWord.append(getWordID(c.getWord(index)))
fPos.append(getPosID(c.getPOS(index)))
# Retrieve top three words and POS from the buffer
for j in range(0, 3, 1):
index = c.getBuffer(j)
fWord.append(getWordID(c.getWord(index)))
fPos.append(getPosID(c.getPOS(index)))
for j in range(0, 2, 1):
# Retrieve the word/pos/label of the first and second leftmost / rightmost children of the top two words on the stack
k = c.getStack(j)
index = c.getLeftChild(k, 1)
fWord.append(getWordID(c.getWord(index)))
fPos.append(getPosID(c.getPOS(index)))
fLabel.append(getLabelID(c.getLabel(index)))
index = c.getRightChild(k, 1)
fWord.append(getWordID(c.getWord(index)))
fPos.append(getPosID(c.getPOS(index)))
fLabel.append(getLabelID(c.getLabel(index)))
index = c.getLeftChild(k, 2)
fWord.append(getWordID(c.getWord(index)))
fPos.append(getPosID(c.getPOS(index)))
fLabel.append(getLabelID(c.getLabel(index)))
index = c.getRightChild(k, 2)
fWord.append(getWordID(c.getWord(index)))
fPos.append(getPosID(c.getPOS(index)))
fLabel.append(getLabelID(c.getLabel(index)))
# Retrieve the word/pos/label of the left of the leftmost / right of the right children of the top two words on the stack
index = c.getLeftChild(c.getLeftChild(k, 1), 1)
fWord.append(getWordID(c.getWord(index)))
fPos.append(getPosID(c.getPOS(index)))
fLabel.append(getLabelID(c.getLabel(index)))
index = c.getRightChild(c.getRightChild(k, 1), 1)
fWord.append(getWordID(c.getWord(index)))
fPos.append(getPosID(c.getPOS(index)))
fLabel.append(getLabelID(c.getLabel(index)))
feature.extend(fWord)
feature.extend(fPos)
feature.extend(fLabel)
return feature
def genTrainExamples(sents, trees):
numTrans = parsing_system.numTransitions()
features = []
labels = []
pbar = ProgressBar()
for i in pbar(range(len(sents))):
if trees[i].isProjective():
c = parsing_system.initialConfiguration(sents[i])
while not parsing_system.isTerminal(c):
oracle = parsing_system.getOracle(c, trees[i])
feat = getFeatures(c)
label = []
for j in range(numTrans):
t = parsing_system.transitions[j]
if t == oracle:
label.append(1.)
elif parsing_system.canApply(c, t):
label.append(0.)
else:
label.append(-1.)
if 1.0 not in label:
print(i, label)
features.append(feat)
labels.append(label)
c = parsing_system.apply(c, oracle)
return features, labels
def load_embeddings(filename, wordDict, posDict, labelDict):
with open(filename, 'rb') as file:
dictionary, word_embeds = pickle.load(file, encoding='latin1')
#dictionary, word_embeds = pickle.load(open(filename, 'r'))
embedding_array = np.zeros((len(wordDict) + len(posDict) + len(labelDict), Config.embedding_size))
knownWords = list(wordDict.keys())
foundEmbed = 0
for i in range(len(embedding_array)):
index = -1
if i < len(knownWords):
w = knownWords[i]
if w in dictionary:
index = dictionary[w]
elif w.lower() in dictionary:
index = dictionary[w.lower()]
if index >= 0:
foundEmbed += 1
embedding_array[i] = word_embeds[index]
else:
embedding_array[i] = np.random.rand(Config.embedding_size) * 0.02 - 0.01
print("Found embeddings: ", foundEmbed, "/", len(knownWords))
return embedding_array
if __name__ == '__main__':
wordDict = {}
posDict = {}
labelDict = {}
parsing_system = None
trainSents, trainTrees = Util.loadConll('train.conll')
devSents, devTrees = Util.loadConll('dev.conll')
testSents, _ = Util.loadConll('test.conll')
genDictionaries(trainSents, trainTrees)
embedding_filename = 'word2vec.model'
embedding_array = load_embeddings(embedding_filename, wordDict, posDict, labelDict)
labelInfo = []
for idx in np.argsort(list(labelDict.values())):
labelInfo.append(list(labelDict.keys())[idx])
parsing_system = ParsingSystem(labelInfo[1:])
print(parsing_system.rootLabel)
print("Generating Traning Examples")
trainFeats, trainLabels = genTrainExamples(trainSents, trainTrees)
print("Done.")
# Build the graph model
graph = tf.Graph()
model = DependencyParserModel(graph, embedding_array, Config)
num_steps = Config.max_iter
with tf.Session(graph=graph) as sess:
model.train(sess, num_steps)
model.evaluate(sess, testSents)