forked from chen0040/keras-text-summarization
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rnn.py
805 lines (671 loc) · 33.3 KB
/
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
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
from __future__ import print_function
from keras.models import Model, Sequential
from keras.layers import Embedding, Dense, Input, RepeatVector, TimeDistributed, concatenate, Merge, add, Dropout
from keras.layers.recurrent import LSTM
from keras.preprocessing.sequence import pad_sequences
from keras.callbacks import ModelCheckpoint
import numpy as np
import os
HIDDEN_UNITS = 100
DEFAULT_BATCH_SIZE = 64
VERBOSE = 1
DEFAULT_EPOCHS = 10
class OneShotRNN(object):
model_name = 'one-shot-rnn'
"""
The first alternative model is to generate the entire output sequence in a one-shot manner.
That is, the decoder uses the context vector alone to generate the output sequence.
This model puts a heavy burden on the decoder.
It is likely that the decoder will not have sufficient context for generating a coherent output sequence as it
must choose the words and their order.
"""
def __init__(self, config):
self.num_input_tokens = config['num_input_tokens']
self.max_input_seq_length = config['max_input_seq_length']
self.num_target_tokens = config['num_target_tokens']
self.max_target_seq_length = config['max_target_seq_length']
self.input_word2idx = config['input_word2idx']
self.input_idx2word = config['input_idx2word']
self.target_word2idx = config['target_word2idx']
self.target_idx2word = config['target_idx2word']
self.config = config
self.version = 0
if 'version' in config:
self.version = config['version']
print('max_input_seq_length', self.max_input_seq_length)
print('max_target_seq_length', self.max_target_seq_length)
print('num_input_tokens', self.num_input_tokens)
print('num_target_tokens', self.num_target_tokens)
# encoder input model
model = Sequential()
model.add(Embedding(output_dim=128, input_dim=self.num_input_tokens, input_length=self.max_input_seq_length))
# encoder model
model.add(LSTM(128))
model.add(RepeatVector(self.max_target_seq_length))
# decoder model
model.add(LSTM(128, return_sequences=True))
model.add(TimeDistributed(Dense(self.num_target_tokens, activation='softmax')))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
self.model = model
def load_weights(self, weight_file_path):
if os.path.exists(weight_file_path):
self.model.load_weights(weight_file_path)
def transform_input_text(self, texts):
temp = []
for line in texts:
x = []
for word in line.lower().split(' '):
wid = 1
if word in self.input_word2idx:
wid = self.input_word2idx[word]
x.append(wid)
if len(x) >= self.max_input_seq_length:
break
temp.append(x)
temp = pad_sequences(temp, maxlen=self.max_input_seq_length)
print(temp.shape)
return temp
def transform_target_encoding(self, texts):
temp = []
for line in texts:
x = []
line2 = 'START ' + line.lower() + ' END'
for word in line2.split(' '):
x.append(word)
if len(x) >= self.max_target_seq_length:
break
temp.append(x)
temp = np.array(temp)
print(temp.shape)
return temp
def generate_batch(self, x_samples, y_samples, batch_size):
num_batches = len(x_samples) // batch_size
while True:
for batchIdx in range(0, num_batches):
start = batchIdx * batch_size
end = (batchIdx + 1) * batch_size
encoder_input_data_batch = pad_sequences(x_samples[start:end], self.max_input_seq_length)
decoder_target_data_batch = np.zeros(
shape=(batch_size, self.max_target_seq_length, self.num_target_tokens))
for lineIdx, target_words in enumerate(y_samples[start:end]):
for idx, w in enumerate(target_words):
w2idx = 0 # default [UNK]
if w in self.target_word2idx:
w2idx = self.target_word2idx[w]
if w2idx != 0:
decoder_target_data_batch[lineIdx, idx, w2idx] = 1
yield encoder_input_data_batch, decoder_target_data_batch
@staticmethod
def get_weight_file_path(model_dir_path):
return model_dir_path + '/' + OneShotRNN.model_name + '-weights.h5'
@staticmethod
def get_config_file_path(model_dir_path):
return model_dir_path + '/' + OneShotRNN.model_name + '-config.npy'
@staticmethod
def get_architecture_file_path(model_dir_path):
return model_dir_path + '/' + OneShotRNN.model_name + '-architecture.json'
def fit(self, Xtrain, Ytrain, Xtest, Ytest, epochs=None, model_dir_path=None, batch_size=None):
if epochs is None:
epochs = DEFAULT_EPOCHS
if model_dir_path is None:
model_dir_path = './models'
if batch_size is None:
batch_size = DEFAULT_BATCH_SIZE
self.version += 1
self.config['version'] = self.version
config_file_path = OneShotRNN.get_config_file_path(model_dir_path)
weight_file_path = OneShotRNN.get_weight_file_path(model_dir_path)
checkpoint = ModelCheckpoint(weight_file_path)
np.save(config_file_path, self.config)
architecture_file_path = OneShotRNN.get_architecture_file_path(model_dir_path)
open(architecture_file_path, 'w').write(self.model.to_json())
Ytrain = self.transform_target_encoding(Ytrain)
Ytest = self.transform_target_encoding(Ytest)
Xtrain = self.transform_input_text(Xtrain)
Xtest = self.transform_input_text(Xtest)
train_gen = self.generate_batch(Xtrain, Ytrain, batch_size)
test_gen = self.generate_batch(Xtest, Ytest, batch_size)
train_num_batches = len(Xtrain) // batch_size
test_num_batches = len(Xtest) // batch_size
history = self.model.fit_generator(generator=train_gen, steps_per_epoch=train_num_batches,
epochs=epochs,
verbose=VERBOSE, validation_data=test_gen, validation_steps=test_num_batches,
callbacks=[checkpoint])
self.model.save_weights(weight_file_path)
return history
def summarize(self, input_text):
input_seq = []
input_wids = []
for word in input_text.lower().split(' '):
idx = 1 # default [UNK]
if word in self.input_word2idx:
idx = self.input_word2idx[word]
input_wids.append(idx)
input_seq.append(input_wids)
input_seq = pad_sequences(input_seq, self.max_input_seq_length)
predicted = self.model.predict(input_seq)
predicted_word_idx_list = np.argmax(predicted, axis=1)
predicted_word_list = [self.target_idx2word[wid] for wid in predicted_word_idx_list[0]]
return predicted_word_list
class RecursiveRNN1(object):
model_name = 'recursive-rnn-1'
"""
A second alternative model is to develop a model that generates a single word forecast and call it recursively.
That is, the decoder uses the context vector and the distributed representation of all words generated so far as
input in order to generate the next word.
A language model can be used to interpret the sequence of words generated so far to provide a second context vector
to combine with the representation of the source document in order to generate the next word in the sequence.
The summary is built up by recursively calling the model with the previously generated word appended (or, more
specifically, the expected previous word during training).
The context vectors could be concentrated or added together to provide a broader context for the decoder to
interpret and output the next word.
"""
def __init__(self, config):
self.num_input_tokens = config['num_input_tokens']
self.max_input_seq_length = config['max_input_seq_length']
self.num_target_tokens = config['num_target_tokens']
self.max_target_seq_length = config['max_target_seq_length']
self.input_word2idx = config['input_word2idx']
self.input_idx2word = config['input_idx2word']
self.target_word2idx = config['target_word2idx']
self.target_idx2word = config['target_idx2word']
if 'version' in config:
self.version = config['version']
else:
self.version = 0
self.config = config
print('max_input_seq_length', self.max_input_seq_length)
print('max_target_seq_length', self.max_target_seq_length)
print('num_input_tokens', self.num_input_tokens)
print('num_target_tokens', self.num_target_tokens)
inputs1 = Input(shape=(self.max_input_seq_length,))
am1 = Embedding(self.num_input_tokens, 128)(inputs1)
am2 = LSTM(128)(am1)
inputs2 = Input(shape=(self.max_target_seq_length,))
sm1 = Embedding(self.num_target_tokens, 128)(inputs2)
sm2 = LSTM(128)(sm1)
decoder1 = concatenate([am2, sm2])
outputs = Dense(self.num_target_tokens, activation='softmax')(decoder1)
model = Model(inputs=[inputs1, inputs2], outputs=outputs)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
self.model = model
def load_weights(self, weight_file_path):
if os.path.exists(weight_file_path):
self.model.load_weights(weight_file_path)
def transform_input_text(self, texts):
temp = []
for line in texts:
x = []
for word in line.lower().split(' '):
wid = 1
if word in self.input_word2idx:
wid = self.input_word2idx[word]
x.append(wid)
if len(x) >= self.max_input_seq_length:
break
temp.append(x)
temp = pad_sequences(temp, maxlen=self.max_input_seq_length)
print(temp.shape)
return temp
def split_target_text(self, texts):
temp = []
for line in texts:
x = []
line2 = 'START ' + line.lower() + ' END'
for word in line2.split(' '):
x.append(word)
if len(x)+1 >= self.max_target_seq_length:
x.append('END')
break
temp.append(x)
return temp
def generate_batch(self, x_samples, y_samples, batch_size):
encoder_input_data_batch = []
decoder_input_data_batch = []
decoder_target_data_batch = []
line_idx = 0
while True:
for recordIdx in range(0, len(x_samples)):
target_words = y_samples[recordIdx]
x = x_samples[recordIdx]
decoder_input_line = []
for idx in range(0, len(target_words)-1):
w2idx = 0 # default [UNK]
w = target_words[idx]
if w in self.target_word2idx:
w2idx = self.target_word2idx[w]
decoder_input_line = decoder_input_line + [w2idx]
decoder_target_label = np.zeros(self.num_target_tokens)
w2idx_next = 0
if target_words[idx+1] in self.target_word2idx:
w2idx_next = self.target_word2idx[target_words[idx+1]]
if w2idx_next != 0:
decoder_target_label[w2idx_next] = 1
decoder_input_data_batch.append(decoder_input_line)
encoder_input_data_batch.append(x)
decoder_target_data_batch.append(decoder_target_label)
line_idx += 1
if line_idx >= batch_size:
yield [pad_sequences(encoder_input_data_batch, self.max_input_seq_length),
pad_sequences(decoder_input_data_batch,
self.max_target_seq_length)], np.array(decoder_target_data_batch)
line_idx = 0
encoder_input_data_batch = []
decoder_input_data_batch = []
decoder_target_data_batch = []
@staticmethod
def get_weight_file_path(model_dir_path):
return model_dir_path + '/' + RecursiveRNN1.model_name + '-weights.h5'
@staticmethod
def get_config_file_path(model_dir_path):
return model_dir_path + '/' + RecursiveRNN1.model_name + '-config.npy'
@staticmethod
def get_architecture_file_path(model_dir_path):
return model_dir_path + '/' + RecursiveRNN1.model_name + '-architecture.json'
def fit(self, Xtrain, Ytrain, Xtest, Ytest, epochs=None, model_dir_path=None, batch_size=None):
if epochs is None:
epochs = DEFAULT_EPOCHS
if model_dir_path is None:
model_dir_path = './models'
if batch_size is None:
batch_size = DEFAULT_BATCH_SIZE
self.version += 1
self.config['version'] = self.version
config_file_path = RecursiveRNN1.get_config_file_path(model_dir_path)
weight_file_path = RecursiveRNN1.get_weight_file_path(model_dir_path)
checkpoint = ModelCheckpoint(weight_file_path)
np.save(config_file_path, self.config)
architecture_file_path = RecursiveRNN1.get_architecture_file_path(model_dir_path)
open(architecture_file_path, 'w').write(self.model.to_json())
Ytrain = self.split_target_text(Ytrain)
Ytest = self.split_target_text(Ytest)
Xtrain = self.transform_input_text(Xtrain)
Xtest = self.transform_input_text(Xtest)
train_gen = self.generate_batch(Xtrain, Ytrain, batch_size)
test_gen = self.generate_batch(Xtest, Ytest, batch_size)
total_training_samples = sum([len(target_text)-1 for target_text in Ytrain])
total_testing_samples = sum([len(target_text)-1 for target_text in Ytest])
train_num_batches = total_training_samples // batch_size
test_num_batches = total_testing_samples // batch_size
history = self.model.fit_generator(generator=train_gen, steps_per_epoch=train_num_batches,
epochs=epochs,
verbose=VERBOSE, validation_data=test_gen, validation_steps=test_num_batches,
callbacks=[checkpoint])
self.model.save_weights(weight_file_path)
return history
def summarize(self, input_text):
input_seq = []
input_wids = []
for word in input_text.lower().split(' '):
idx = 1 # default [UNK]
if word in self.input_word2idx:
idx = self.input_word2idx[word]
input_wids.append(idx)
input_seq.append(input_wids)
input_seq = pad_sequences(input_seq, self.max_input_seq_length)
start_token = self.target_word2idx['START']
wid_list = [start_token]
sum_input_seq = pad_sequences([wid_list], self.max_target_seq_length)
terminated = False
target_text = ''
while not terminated:
output_tokens = self.model.predict([input_seq, sum_input_seq])
sample_token_idx = np.argmax(output_tokens[0, :])
sample_word = self.target_idx2word[sample_token_idx]
wid_list = wid_list + [sample_token_idx]
if sample_word != 'START' and sample_word != 'END':
target_text += ' ' + sample_word
if sample_word == 'END' or len(wid_list) >= self.max_target_seq_length:
terminated = True
else:
sum_input_seq = pad_sequences([wid_list], self.max_target_seq_length)
return target_text.strip()
class RecursiveRNN2(object):
model_name = 'recursive-rnn-2'
"""
In this third alternative, the Encoder generates a context vector representation of the source document.
This document is fed to the decoder at each step of the generated output sequence. This allows the decoder to build
up the same internal state as was used to generate the words in the output sequence so that it is primed to generate
the next word in the sequence.
This process is then repeated by calling the model again and again for each word in the output sequence until a
maximum length or end-of-sequence token is generated.
"""
MAX_DECODER_SEQ_LENGTH = 4
def __init__(self, config):
self.num_input_tokens = config['num_input_tokens']
self.max_input_seq_length = config['max_input_seq_length']
self.num_target_tokens = config['num_target_tokens']
self.max_target_seq_length = config['max_target_seq_length']
self.input_word2idx = config['input_word2idx']
self.input_idx2word = config['input_idx2word']
self.target_word2idx = config['target_word2idx']
self.target_idx2word = config['target_idx2word']
self.config = config
self.version = 0
if 'version' in config:
self.version = config['version']
# article input model
inputs1 = Input(shape=(self.max_input_seq_length,))
article1 = Embedding(self.num_input_tokens, 128)(inputs1)
article2 = Dropout(0.3)(article1)
# summary input model
inputs2 = Input(shape=(min(self.num_target_tokens, RecursiveRNN2.MAX_DECODER_SEQ_LENGTH), ))
summ1 = Embedding(self.num_target_tokens, 128)(inputs2)
summ2 = Dropout(0.3)(summ1)
summ3 = LSTM(128)(summ2)
summ4 = RepeatVector(self.max_input_seq_length)(summ3)
# decoder model
decoder1 = concatenate([article2, summ4])
decoder2 = LSTM(128)(decoder1)
outputs = Dense(self.num_target_tokens, activation='softmax')(decoder2)
# tie it together [article, summary] [word]
model = Model(inputs=[inputs1, inputs2], outputs=outputs)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
self.model = model
def load_weights(self, weight_file_path):
if os.path.exists(weight_file_path):
print('loading weights from ', weight_file_path)
self.model.load_weights(weight_file_path)
def transform_input_text(self, texts):
temp = []
for line in texts:
x = []
for word in line.lower().split(' '):
wid = 1
if word in self.input_word2idx:
wid = self.input_word2idx[word]
x.append(wid)
if len(x) >= self.max_input_seq_length:
break
temp.append(x)
temp = pad_sequences(temp, maxlen=self.max_input_seq_length)
print(temp.shape)
return temp
def split_target_text(self, texts):
temp = []
for line in texts:
x = []
line2 = 'START ' + line.lower() + ' END'
for word in line2.split(' '):
x.append(word)
if len(x)+1 >= self.max_target_seq_length:
x.append('END')
break
temp.append(x)
return temp
def generate_batch(self, x_samples, y_samples, batch_size):
encoder_input_data_batch = []
decoder_input_data_batch = []
decoder_target_data_batch = []
line_idx = 0
while True:
for recordIdx in range(0, len(x_samples)):
target_words = y_samples[recordIdx]
x = x_samples[recordIdx]
decoder_input_line = []
for idx in range(0, len(target_words)-1):
w2idx = 0 # default [UNK]
w = target_words[idx]
if w in self.target_word2idx:
w2idx = self.target_word2idx[w]
decoder_input_line = decoder_input_line + [w2idx]
decoder_target_label = np.zeros(self.num_target_tokens)
w2idx_next = 0
if target_words[idx+1] in self.target_word2idx:
w2idx_next = self.target_word2idx[target_words[idx+1]]
if w2idx_next != 0:
decoder_target_label[w2idx_next] = 1
decoder_input_data_batch.append(decoder_input_line)
encoder_input_data_batch.append(x)
decoder_target_data_batch.append(decoder_target_label)
line_idx += 1
if line_idx >= batch_size:
yield [pad_sequences(encoder_input_data_batch, self.max_input_seq_length),
pad_sequences(decoder_input_data_batch,
min(self.num_target_tokens, RecursiveRNN2.MAX_DECODER_SEQ_LENGTH))], np.array(decoder_target_data_batch)
line_idx = 0
encoder_input_data_batch = []
decoder_input_data_batch = []
decoder_target_data_batch = []
@staticmethod
def get_weight_file_path(model_dir_path):
return model_dir_path + '/' + RecursiveRNN2.model_name + '-weights.h5'
@staticmethod
def get_config_file_path(model_dir_path):
return model_dir_path + '/' + RecursiveRNN2.model_name + '-config.npy'
@staticmethod
def get_architecture_file_path(model_dir_path):
return model_dir_path + '/' + RecursiveRNN2.model_name + '-architecture.json'
def fit(self, Xtrain, Ytrain, Xtest, Ytest, epochs=None, model_dir_path=None, batch_size=None):
if epochs is None:
epochs = DEFAULT_EPOCHS
if model_dir_path is None:
model_dir_path = './models'
if batch_size is None:
batch_size = DEFAULT_BATCH_SIZE
self.version += 1
self.config['version'] = self.version
config_file_path = RecursiveRNN2.get_config_file_path(model_dir_path)
weight_file_path = RecursiveRNN2.get_weight_file_path(model_dir_path)
checkpoint = ModelCheckpoint(weight_file_path)
np.save(config_file_path, self.config)
architecture_file_path = RecursiveRNN2.get_architecture_file_path(model_dir_path)
open(architecture_file_path, 'w').write(self.model.to_json())
Ytrain = self.split_target_text(Ytrain)
Ytest = self.split_target_text(Ytest)
Xtrain = self.transform_input_text(Xtrain)
Xtest = self.transform_input_text(Xtest)
train_gen = self.generate_batch(Xtrain, Ytrain, batch_size)
test_gen = self.generate_batch(Xtest, Ytest, batch_size)
total_training_samples = sum([len(target_text)-1 for target_text in Ytrain])
total_testing_samples = sum([len(target_text)-1 for target_text in Ytest])
train_num_batches = total_training_samples // batch_size
test_num_batches = total_testing_samples // batch_size
history = self.model.fit_generator(generator=train_gen, steps_per_epoch=train_num_batches,
epochs=epochs,
verbose=VERBOSE, validation_data=test_gen, validation_steps=test_num_batches,
callbacks=[checkpoint])
self.model.save_weights(weight_file_path)
return history
def summarize(self, input_text):
input_seq = []
input_wids = []
for word in input_text.lower().split(' '):
idx = 1 # default [UNK]
if word in self.input_word2idx:
idx = self.input_word2idx[word]
input_wids.append(idx)
input_seq.append(input_wids)
input_seq = pad_sequences(input_seq, self.max_input_seq_length)
start_token = self.target_word2idx['START']
wid_list = [start_token]
sum_input_seq = pad_sequences([wid_list], min(self.num_target_tokens, RecursiveRNN2.MAX_DECODER_SEQ_LENGTH))
terminated = False
target_text = ''
while not terminated:
output_tokens = self.model.predict([input_seq, sum_input_seq])
sample_token_idx = np.argmax(output_tokens[0, :])
sample_word = self.target_idx2word[sample_token_idx]
wid_list = wid_list + [sample_token_idx]
if sample_word != 'START' and sample_word != 'END':
target_text += ' ' + sample_word
if sample_word == 'END' or len(wid_list) >= self.max_target_seq_length:
terminated = True
else:
sum_input_seq = pad_sequences([wid_list], min(self.num_target_tokens, RecursiveRNN2.MAX_DECODER_SEQ_LENGTH))
return target_text.strip()
class RecursiveRNN3(object):
model_name = 'recursive-rnn-3'
"""
In this third alternative, the Encoder generates a context vector representation of the source document.
This document is fed to the decoder at each step of the generated output sequence. This allows the decoder to build
up the same internal state as was used to generate the words in the output sequence so that it is primed to generate
the next word in the sequence.
This process is then repeated by calling the model again and again for each word in the output sequence until a
maximum length or end-of-sequence token is generated.
"""
def __init__(self, config):
self.num_input_tokens = config['num_input_tokens']
self.max_input_seq_length = config['max_input_seq_length']
self.num_target_tokens = config['num_target_tokens']
self.max_target_seq_length = config['max_target_seq_length']
self.input_word2idx = config['input_word2idx']
self.input_idx2word = config['input_idx2word']
self.target_word2idx = config['target_word2idx']
self.target_idx2word = config['target_idx2word']
self.config = config
self.version = 0
if 'version' in config:
self.version = config['version']
# article input model
inputs1 = Input(shape=(self.max_input_seq_length,))
article1 = Embedding(self.num_input_tokens, 128)(inputs1)
article2 = LSTM(128)(article1)
article3 = RepeatVector(128)(article2)
# summary input model
inputs2 = Input(shape=(self.max_target_seq_length,))
summ1 = Embedding(self.num_target_tokens, 128)(inputs2)
summ2 = LSTM(128)(summ1)
summ3 = RepeatVector(128)(summ2)
# decoder model
decoder1 = concatenate([article3, summ3])
decoder2 = LSTM(128)(decoder1)
outputs = Dense(self.num_target_tokens, activation='softmax')(decoder2)
# tie it together [article, summary] [word]
model = Model(inputs=[inputs1, inputs2], outputs=outputs)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
self.model = model
def load_weights(self, weight_file_path):
if os.path.exists(weight_file_path):
print('loading weights from ', weight_file_path)
self.model.load_weights(weight_file_path)
def transform_input_text(self, texts):
temp = []
for line in texts:
x = []
for word in line.lower().split(' '):
wid = 1
if word in self.input_word2idx:
wid = self.input_word2idx[word]
x.append(wid)
if len(x) >= self.max_input_seq_length:
break
temp.append(x)
temp = pad_sequences(temp, maxlen=self.max_input_seq_length)
print(temp.shape)
return temp
def split_target_text(self, texts):
temp = []
for line in texts:
x = []
line2 = 'START ' + line.lower() + ' END'
for word in line2.split(' '):
x.append(word)
if len(x)+1 >= self.max_target_seq_length:
x.append('END')
break
temp.append(x)
return temp
def generate_batch(self, x_samples, y_samples, batch_size):
encoder_input_data_batch = []
decoder_input_data_batch = []
decoder_target_data_batch = []
line_idx = 0
while True:
for recordIdx in range(0, len(x_samples)):
target_words = y_samples[recordIdx]
x = x_samples[recordIdx]
decoder_input_line = []
for idx in range(0, len(target_words)-1):
w2idx = 0 # default [UNK]
w = target_words[idx]
if w in self.target_word2idx:
w2idx = self.target_word2idx[w]
decoder_input_line = decoder_input_line + [w2idx]
decoder_target_label = np.zeros(self.num_target_tokens)
w2idx_next = 0
if target_words[idx+1] in self.target_word2idx:
w2idx_next = self.target_word2idx[target_words[idx+1]]
if w2idx_next != 0:
decoder_target_label[w2idx_next] = 1
decoder_input_data_batch.append(decoder_input_line)
encoder_input_data_batch.append(x)
decoder_target_data_batch.append(decoder_target_label)
line_idx += 1
if line_idx >= batch_size:
yield [pad_sequences(encoder_input_data_batch, self.max_input_seq_length),
pad_sequences(decoder_input_data_batch,
self.max_target_seq_length)], np.array(decoder_target_data_batch)
line_idx = 0
encoder_input_data_batch = []
decoder_input_data_batch = []
decoder_target_data_batch = []
@staticmethod
def get_weight_file_path(model_dir_path):
return model_dir_path + '/' + RecursiveRNN2.model_name + '-weights.h5'
@staticmethod
def get_config_file_path(model_dir_path):
return model_dir_path + '/' + RecursiveRNN2.model_name + '-config.npy'
@staticmethod
def get_architecture_file_path(model_dir_path):
return model_dir_path + '/' + RecursiveRNN2.model_name + '-architecture.json'
def fit(self, Xtrain, Ytrain, Xtest, Ytest, epochs=None, model_dir_path=None, batch_size=None):
if epochs is None:
epochs = DEFAULT_EPOCHS
if model_dir_path is None:
model_dir_path = './models'
if batch_size is None:
batch_size = DEFAULT_BATCH_SIZE
self.version += 1
self.config['version'] = self.version
config_file_path = RecursiveRNN2.get_config_file_path(model_dir_path)
weight_file_path = RecursiveRNN2.get_weight_file_path(model_dir_path)
checkpoint = ModelCheckpoint(weight_file_path)
np.save(config_file_path, self.config)
architecture_file_path = RecursiveRNN2.get_architecture_file_path(model_dir_path)
open(architecture_file_path, 'w').write(self.model.to_json())
Ytrain = self.split_target_text(Ytrain)
Ytest = self.split_target_text(Ytest)
Xtrain = self.transform_input_text(Xtrain)
Xtest = self.transform_input_text(Xtest)
train_gen = self.generate_batch(Xtrain, Ytrain, batch_size)
test_gen = self.generate_batch(Xtest, Ytest, batch_size)
total_training_samples = sum([len(target_text)-1 for target_text in Ytrain])
total_testing_samples = sum([len(target_text)-1 for target_text in Ytest])
train_num_batches = total_training_samples // batch_size
test_num_batches = total_testing_samples // batch_size
history = self.model.fit_generator(generator=train_gen, steps_per_epoch=train_num_batches,
epochs=epochs,
verbose=VERBOSE, validation_data=test_gen, validation_steps=test_num_batches,
callbacks=[checkpoint])
self.model.save_weights(weight_file_path)
return history
def summarize(self, input_text):
input_seq = []
input_wids = []
for word in input_text.lower().split(' '):
idx = 1 # default [UNK]
if word in self.input_word2idx:
idx = self.input_word2idx[word]
input_wids.append(idx)
input_seq.append(input_wids)
input_seq = pad_sequences(input_seq, self.max_input_seq_length)
start_token = self.target_word2idx['START']
wid_list = [start_token]
sum_input_seq = pad_sequences([wid_list], self.max_target_seq_length)
terminated = False
target_text = ''
while not terminated:
output_tokens = self.model.predict([input_seq, sum_input_seq])
sample_token_idx = np.argmax(output_tokens[0, :])
sample_word = self.target_idx2word[sample_token_idx]
wid_list = wid_list + [sample_token_idx]
if sample_word != 'START' and sample_word != 'END':
target_text += ' ' + sample_word
if sample_word == 'END' or len(wid_list) >= self.max_target_seq_length:
terminated = True
else:
sum_input_seq = pad_sequences([wid_list], self.max_target_seq_length)
return target_text.strip()