forked from hiroki13/neural-pos-tagger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nn_word_batch.py
346 lines (269 loc) · 11.5 KB
/
nn_word_batch.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
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
import sys
import time
import math
import random
import io_utils
import numpy as np
import theano
import theano.tensor as T
from nn_utils import sample_weights, relu
from optimizers import sgd, ada_grad
theano.config.floatX = 'float32'
class Model(object):
def __init__(self, x, y, n_words, batch_size, lr, init_emb, vocab_size, emb_dim, hidden_dim, output_dim, window, opt):
assert window % 2 == 1, 'Window size must be odd'
""" input """
self.x = x # 1D: n_words * batch_size, 2D: window; elem=word id
self.x_v = x.flatten() # 1D: n_words * batch_size * window; elem=word id
self.y = y
self.batch_size = batch_size
self.n_words = n_words
self.lr = lr
""" params """
if init_emb is not None:
self.emb = theano.shared(init_emb)
else:
self.emb = theano.shared(sample_weights(vocab_size, emb_dim))
self.W_in = theano.shared(sample_weights(emb_dim * window, hidden_dim))
self.W_out = theano.shared(sample_weights(hidden_dim, output_dim))
self.b_in = theano.shared(sample_weights(hidden_dim))
self.b_y = theano.shared(sample_weights(output_dim))
self.params = [self.W_in, self.W_out, self.b_in, self.b_y]
""" look up embedding """
self.x_emb = self.emb[self.x_v] # x_emb: 1D: batch_size * n_words * window, 2D: emb_dim
""" forward """
self.h = relu(T.dot(self.x_emb.reshape((batch_size * n_words, emb_dim * window)), self.W_in) + self.b_in)
self.o = T.dot(self.h, self.W_out) + self.b_y
self.p_y_given_x = T.nnet.softmax(self.o)
""" predict """
self.y_pred = T.argmax(self.o, axis=1)
self.result = T.eq(self.y_pred, self.y)
""" loss """
self.log_p = T.log(self.p_y_given_x)[T.arange(batch_size * n_words), self.y]
self.nll = -T.sum(self.log_p)
self.cost = self.nll
if opt == 'sgd':
self.updates = sgd(self.cost, self.params, self.emb, self.x_emb, self.lr)
else:
self.updates = ada_grad(self.cost, self.params, self.emb, self.x_emb, self.x, self.lr)
def convert_into_ids(corpus, vocab_word, vocab_char, vocab_tag):
id_corpus_w = []
id_corpus_c = []
id_corpus_b = []
id_corpus_t = []
for sent in corpus:
w_ids = []
c_ids = []
bs = []
t_ids = []
b = 0
for w, t in sent:
w_id = vocab_word.get_id(w.lower())
t_id = vocab_tag.get_id(t)
if w_id is None:
w_id = vocab_word.get_id(io_utils.UNK)
assert w_id is not None
assert t_id is not None
w_ids.append(w_id)
t_ids.append(t_id)
c_ids.extend([vocab_char.get_id(c) for c in w])
b += len(w)
bs.append(b)
id_corpus_w.append(w_ids)
id_corpus_c.append(c_ids)
id_corpus_b.append(bs)
id_corpus_t.append(t_ids)
assert len(id_corpus_w) == len(id_corpus_c) == len(id_corpus_b) == len(id_corpus_t)
return id_corpus_w, id_corpus_c, id_corpus_b, id_corpus_t
def set_minibatch(id_x, id_y, batch_size, window=5):
samples_x = []
samples_y = []
batch_indices = []
p = window / 2
zero_pad_w = [0 for i in xrange(p)]
prev_sent_len = -1
b_index = 0
bob = 0
eob = 0
for i in xrange(len(id_x)):
sent_x = id_x[i] # sent_w: 1D: n_words; elem=word id
sent_len = len(sent_x)
sent_x = zero_pad_w + sent_x + zero_pad_w
samples_x.extend([sent_x[j: j+window] for j in xrange(sent_len)])
samples_y.extend(id_y[i])
if b_index < batch_size and (sent_len == prev_sent_len or prev_sent_len < 0):
pass
else:
batch_indices.append((bob, eob, prev_sent_len, b_index))
bob = eob
b_index = 0
prev_sent_len = sent_len
eob += sent_len
b_index += 1
batch_indices.append((bob, eob, prev_sent_len, b_index))
return samples_x, samples_y, batch_indices
def shared_samples(samples_x, samples_y):
def shared(samples):
return theano.shared(np.asarray(samples, dtype='int32'))
return shared(samples_x), shared(samples_y)
def train(args):
print '\nNEURAL POS TAGGER START\n'
print '\tINITIAL EMBEDDING\t%s %s' % (args.word_list, args.emb_list)
print '\tWORD\t\t\tEmb Dim: %d Hidden Dim: %d' % (args.w_emb_dim, args.w_hidden_dim)
print '\tCHARACTER\t\tEmb Dim: %d Hidden Dim: %d' % (args.c_emb_dim, args.c_hidden_dim)
print '\tOPTIMIZATION\t\tMethod: %s Learning Rate: %f\n' % (args.opt, args.lr)
print '\tMINI-BATCH: %d\n' % args.batch_size
""" load data """
print 'Loading data sets...\n'
train_corpus, vocab_word, vocab_char, vocab_tag, _ = io_utils.load_conll(args.train_data)
""" limit data set """
train_corpus = train_corpus[:args.data_size]
train_corpus.sort(key=lambda a: len(a))
dev_corpus = None
if args.dev_data:
dev_corpus, dev_vocab_word, dev_vocab_char, dev_vocab_tag, _ = io_utils.load_conll(args.dev_data)
for w in dev_vocab_word.i2w:
if args.vocab_size is None or vocab_word.size() < args.vocab_size:
vocab_word.add_word(w)
for c in dev_vocab_char.i2w:
vocab_char.add_word(c)
for t in dev_vocab_tag.i2w:
vocab_tag.add_word(t)
if args.save:
io_utils.dump_data(vocab_word, 'vocab_word')
io_utils.dump_data(vocab_char, 'vocab_char')
io_utils.dump_data(vocab_tag, 'vocab_tag')
""" load word embeddings """
init_w_emb = None
if args.emb_list:
print '\tLoading pre-trained word embeddings...\n'
init_w_emb = io_utils.load_init_emb(args.emb_list, args.word_list, vocab_word)
w_emb_dim = init_w_emb.shape[1]
else:
print '\tUse random-initialized word embeddings...\n'
w_emb_dim = args.w_emb_dim
""" converting into ids """
print '\nConverting into IDs...\n'
tr_x, tr_c, tr_b, tr_y = convert_into_ids(train_corpus, vocab_word, vocab_char, vocab_tag)
tr_x, tr_y, tr_b = set_minibatch(tr_x, tr_y, args.batch_size)
tr_x, tr_y = shared_samples(tr_x, tr_y)
dev_x = None
dev_y = None
if args.dev_data:
dev_x, dev_c, dev_b, dev_y = convert_into_ids(dev_corpus, vocab_word, vocab_char, vocab_tag)
dev_x, dev_y, dev_b = set_minibatch(dev_x, dev_y, 1)
dev_x, dev_y = shared_samples(dev_x, dev_y)
print '\tTrain Sentences: %d Dev Sentences: %d' % (len(train_corpus), len(dev_corpus))
else:
print '\tTrain Sentences: %d' % len(train_corpus)
print '\tWord size: %d Char size: %d' % (vocab_word.size(), vocab_char.size())
""" set model parameters """
hidden_dim = args.w_hidden_dim
output_dim = vocab_tag.size()
window = args.window
opt = args.opt
""" symbol definition """
print '\tCompiling Theano Code...'
bos = T.iscalar('bos')
eos = T.iscalar('eos')
n_words = T.iscalar('n_words')
batch_size = T.iscalar('batch_size')
x = T.imatrix('x')
y = T.ivector('y')
lr = T.fscalar('lr')
""" tagger set up """
tagger = Model(x=x, y=y, n_words=n_words, batch_size=batch_size, lr=lr, init_emb=init_w_emb,
vocab_size=vocab_word.size(), emb_dim=w_emb_dim, hidden_dim=hidden_dim, output_dim=output_dim,
opt=opt, window=window)
train_f = theano.function(
inputs=[bos, eos, n_words, batch_size, lr],
outputs=[tagger.nll, tagger.result],
updates=tagger.updates,
givens={
x: tr_x[bos: eos],
y: tr_y[bos: eos]
},
mode='FAST_RUN'
)
dev_f = theano.function(
inputs=[bos, eos, n_words, batch_size],
outputs=tagger.result,
givens={
x: dev_x[bos: eos],
y: dev_y[bos: eos]
},
mode='FAST_RUN'
)
def _train():
for epoch in xrange(args.epoch):
_lr = args.lr / float(epoch+1)
indices = range(len(tr_b))
random.shuffle(indices)
print '\nEpoch: %d' % (epoch + 1)
print '\tBatch Index: ',
start = time.time()
total = 0.0
correct = 0
losses = 0.0
for i, index in enumerate(indices):
if i % 100 == 0 and i != 0:
print i,
sys.stdout.flush()
boundary = tr_b[index]
loss, corrects = train_f(boundary[0], boundary[1], boundary[2],boundary[3], _lr)
assert math.isnan(loss) is False, i
total += len(corrects)
correct += np.sum(corrects)
losses += loss
end = time.time()
print '\tTime: %f seconds' % (end - start)
print '\tNegative Log Likelihood: %f' % losses
print '\tAccuracy:%f Total:%d Correct:%d' % ((correct / total), total, correct)
_dev(dev_f)
def _dev(model):
print '\tBatch Index: ',
start = time.time()
total = 0.0
correct = 0
for index in xrange(len(dev_b)):
if index % 100 == 0 and index != 0:
print index,
sys.stdout.flush()
boundary = dev_b[index]
corrects = model(boundary[0], boundary[1], boundary[2], boundary[3])
total += len(corrects)
correct += np.sum(corrects)
end = time.time()
print '\tTime: %f seconds' % (end - start)
print '\tAccuracy:%f Total:%d Correct:%d' % ((correct / total), total, correct)
_train()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Train NN tagger.')
""" Mode """
parser.add_argument('-mode', default='train', help='train/test')
""" Model """
parser.add_argument('--model', default='char', help='word/char')
parser.add_argument('--save', type=bool, default=True, help='save model')
parser.add_argument('--load', type=str, default=None, help='load model')
""" Data """
parser.add_argument('--train_data', help='path to training data')
parser.add_argument('--dev_data', help='path to development data')
parser.add_argument('--test_data', help='path to test data')
parser.add_argument('--data_size', type=int, default=100000)
parser.add_argument('--vocab_size', type=int, default=100000000)
""" Neural Architectures """
parser.add_argument('--emb_list', default=None, help='initial embedding list file (word2vec output)')
parser.add_argument('--word_list', default=None, help='initial word list file (word2vec output)')
parser.add_argument('--w_emb_dim', type=int, default=100, help='dimension of word embeddings')
parser.add_argument('--c_emb_dim', type=int, default=10, help='dimension of char embeddings')
parser.add_argument('--w_hidden_dim', type=int, default=300, help='dimension of word hidden layer')
parser.add_argument('--c_hidden_dim', type=int, default=50, help='dimension of char hidden layer')
parser.add_argument('--window', type=int, default=5, help='window size for convolution')
parser.add_argument('--batch_size', type=int, default=32, help='mini batch size')
""" Training Parameters """
parser.add_argument('--opt', default='sgd', help='optimization method')
parser.add_argument('--epoch', type=int, default=10, help='number of epochs to train')
parser.add_argument('--lr', type=float, default=0.0075, help='learning rate')
args = parser.parse_args()
train(args=args)