forked from thunlp/TensorFlow-Summarization
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsummarization.py
More file actions
241 lines (209 loc) · 9.56 KB
/
summarization.py
File metadata and controls
241 lines (209 loc) · 9.56 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
import logging
import math
import os
import random
import sys
import time
import numpy as np
import tensorflow as tf
import bigru_model
import data_util
tf.app.flags.DEFINE_float("learning_rate", 1., "Learning rate.")
tf.app.flags.DEFINE_integer("size", 400, "Size of hidden layers.")
tf.app.flags.DEFINE_integer("embsize", 200, "Size of embedding.")
tf.app.flags.DEFINE_integer("num_layers", 1, "Number of layers in the model.")
tf.app.flags.DEFINE_string("data_dir", "data", "Data directory")
tf.app.flags.DEFINE_string("test_file", "", "Test filename.")
tf.app.flags.DEFINE_string("test_output", "output.txt", "Test output.")
tf.app.flags.DEFINE_string("train_dir", "model", "Training directory.")
tf.app.flags.DEFINE_string("tfboard", "tfboard", "Tensorboard log directory.")
tf.app.flags.DEFINE_boolean("decode", False, "Set to True for testing.")
tf.app.flags.DEFINE_boolean("geneos", True, "Do not generate EOS. ")
tf.app.flags.DEFINE_float(
"max_gradient", 1.0, "Clip gradients l2 norm to this range.")
tf.app.flags.DEFINE_integer(
"batch_size", 80, "Batch size in training / beam size in testing.")
tf.app.flags.DEFINE_integer(
"doc_vocab_size", 30000, "Document vocabulary size.")
tf.app.flags.DEFINE_integer(
"sum_vocab_size", 30000, "Summary vocabulary size.")
tf.app.flags.DEFINE_integer(
"max_train", 0, "Limit on the size of training data (0: no limit).")
tf.app.flags.DEFINE_integer(
"max_iter", 1000000, "Maximum training iterations.")
tf.app.flags.DEFINE_integer(
"steps_per_validation", 1000, "Training steps between validations.")
tf.app.flags.DEFINE_integer(
"steps_per_checkpoint", 10000, "Training steps between checkpoints.")
tf.app.flags.DEFINE_string(
"checkpoint", "", "Checkpoint to load (use up-to-date if not set)")
FLAGS = tf.app.flags.FLAGS
# We use a number of buckets for sampling
_buckets = [(30, 10), (50, 20), (70, 20), (100, 20), (200, 30)]
def create_bucket(source, target):
data_set = [[] for _ in _buckets]
for s, t in zip(source, target):
t = [data_util.ID_GO] + t + [data_util.ID_EOS]
for bucket_id, (s_size, t_size) in enumerate(_buckets):
if len(s) <= s_size and len(t) <= t_size:
data_set[bucket_id].append([s, t])
break
return data_set
def create_model(session, forward_only):
"""Create model and initialize or load parameters in session."""
dtype = tf.float32
model = bigru_model.BiGRUModel(
FLAGS.doc_vocab_size,
FLAGS.sum_vocab_size,
_buckets,
FLAGS.size,
FLAGS.num_layers,
FLAGS.embsize,
FLAGS.max_gradient,
FLAGS.batch_size,
FLAGS.learning_rate,
forward_only=forward_only,
dtype=dtype)
if FLAGS.checkpoint != "":
ckpt = FLAGS.checkpoint
else:
ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)
if ckpt:
ckpt = ckpt.model_checkpoint_path
if ckpt and tf.train.checkpoint_exists(ckpt):
logging.info("Reading model parameters from %s" % ckpt)
model.saver.restore(session, ckpt)
else:
logging.info("Created model with fresh parameters.")
session.run(tf.global_variables_initializer())
return model
def train():
logging.info("Preparing summarization data.")
docid, sumid, doc_dict, sum_dict = \
data_util.load_data(
FLAGS.data_dir + "/train.article.txt",
FLAGS.data_dir + "/train.title.txt",
FLAGS.data_dir + "/doc_dict.txt",
FLAGS.data_dir + "/sum_dict.txt",
FLAGS.doc_vocab_size, FLAGS.sum_vocab_size)
val_docid, val_sumid = \
data_util.load_valid_data(
FLAGS.data_dir + "/valid.article.filter.txt",
FLAGS.data_dir + "/valid.title.filter.txt",
doc_dict, sum_dict)
with tf.Session() as sess:
# Create model.
logging.info("Creating %d layers of %d units." %
(FLAGS.num_layers, FLAGS.size))
train_writer = tf.summary.FileWriter(FLAGS.tfboard, sess.graph)
model = create_model(sess, False)
# Read data into buckets and compute their sizes.
logging.info("Create buckets.")
dev_set = create_bucket(val_docid, val_sumid)
train_set = create_bucket(docid, sumid)
train_bucket_sizes = [len(train_set[b]) for b in range(len(_buckets))]
train_total_size = float(sum(train_bucket_sizes))
train_buckets_scale = [
sum(train_bucket_sizes[:i + 1]) / train_total_size
for i in range(len(train_bucket_sizes))]
for (s_size, t_size), nsample in zip(_buckets, train_bucket_sizes):
logging.info("Train set bucket ({}, {}) has {} samples.".format(
s_size, t_size, nsample))
# This is the training loop.
step_time, loss = 0.0, 0.0
current_step = sess.run(model.global_step)
while current_step <= FLAGS.max_iter:
random_number_01 = np.random.random_sample()
bucket_id = min([i for i in range(len(train_buckets_scale))
if train_buckets_scale[i] > random_number_01])
# Get a batch and make a step.
start_time = time.time()
encoder_inputs, decoder_inputs, encoder_len, decoder_len = \
model.get_batch(train_set, bucket_id)
step_loss, _ = model.step(
sess, encoder_inputs, decoder_inputs,
encoder_len, decoder_len, False, train_writer)
step_time += (time.time() - start_time) / \
FLAGS.steps_per_validation
loss += step_loss * FLAGS.batch_size / np.sum(decoder_len) \
/ FLAGS.steps_per_validation
current_step += 1
# Once in a while, we save checkpoint.
if current_step % FLAGS.steps_per_checkpoint == 0:
# Save checkpoint and zero timer and loss.
checkpoint_path = os.path.join(FLAGS.train_dir, "model.ckpt")
model.saver.save(sess, checkpoint_path,
global_step=model.global_step)
# Once in a while, we print statistics and run evals.
if current_step % FLAGS.steps_per_validation == 0:
# Print statistics for the previous epoch.
perplexity = np.exp(float(loss))
logging.info(
"global step %d step-time %.2f ppl %.2f" % (model.global_step.eval(), step_time, perplexity))
step_time, loss = 0.0, 0.0
# Run evals on development set and print their perplexity.
for bucket_id in range(len(_buckets)):
if len(dev_set[bucket_id]) == 0:
logging.info(" eval: empty bucket %d" % (bucket_id))
continue
encoder_inputs, decoder_inputs, encoder_len, decoder_len =\
model.get_batch(dev_set, bucket_id)
eval_loss, _ = model.step(sess, encoder_inputs,
decoder_inputs, encoder_len,
decoder_len, True)
eval_loss = eval_loss * FLAGS.batch_size \
/ np.sum(decoder_len)
eval_ppx = np.exp(float(eval_loss))
logging.info(" eval: bucket %d ppl %.2f" %
(bucket_id, eval_ppx))
sys.stdout.flush()
def decode():
# Load vocabularies.
doc_dict = data_util.load_dict(FLAGS.data_dir + "/doc_dict.txt")
sum_dict = data_util.load_dict(FLAGS.data_dir + "/sum_dict.txt")
if doc_dict is None or sum_dict is None:
logging.warning("Dict not found.")
data = data_util.load_test_data(FLAGS.test_file, doc_dict)
with tf.Session() as sess:
# Create model and load parameters.
logging.info("Creating %d layers of %d units." %
(FLAGS.num_layers, FLAGS.size))
model = create_model(sess, True)
result = []
for idx, token_ids in enumerate(data):
# Get a 1-element batch to feed the sentence to the model.
encoder_inputs, decoder_inputs, encoder_len, decoder_len =\
model.get_batch(
{0: [(token_ids, [data_util.ID_GO, data_util.ID_EOS])]}, 0)
if FLAGS.batch_size == 1 and FLAGS.geneos:
loss, outputs = model.step(sess,
encoder_inputs, decoder_inputs,
encoder_len, decoder_len, True)
outputs = [np.argmax(item) for item in outputs[0]]
else:
outputs = model.step_beam(
sess, encoder_inputs, encoder_len, geneos=FLAGS.geneos)
# If there is an EOS symbol in outputs, cut them at that point.
if data_util.ID_EOS in outputs:
outputs = outputs[:outputs.index(data_util.ID_EOS)]
gen_sum = " ".join(data_util.sen_map2tok(outputs, sum_dict[1]))
gen_sum = data_util.sen_postprocess(gen_sum)
result.append(gen_sum)
logging.info("Finish {} samples. :: {}".format(idx, gen_sum[:75]))
with open(FLAGS.test_output, "w") as f:
for item in result:
print(item, file=f)
def main(_):
if FLAGS.decode:
decode()
else:
train()
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s",
datefmt='%b %d %H:%M')
try:
os.makedirs(FLAGS.train_dir)
except:
pass
tf.app.run()