-
Notifications
You must be signed in to change notification settings - Fork 22
/
helpers.py
332 lines (271 loc) · 9.75 KB
/
helpers.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
import numpy as np
import random
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.DEBUG)
import math
import sys
from time import gmtime, strftime
import json
from math import tanh
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
"""build data"""
def build_emoji_index(vocab_path, emoji_list):
vocab_file = open(vocab_path, encoding="utf-8")
vocab_data = vocab_file.readlines()
vocab_file.close()
i = 0
emoji_index = {}
emoji_index_l = []
emoji_sorted = []
for index, line in enumerate(vocab_data):
word = line.rstrip()
if word in emoji_list:
emoji_index[index] = i
emoji_index_l.append(index)
emoji_sorted.append(word)
i += 1
assert i == 64
return emoji_index, emoji_index_l, emoji_sorted
# 20000 to 64 64 to 20000
def build_vocab(vocab_path):
vocab_file = open(vocab_path, encoding="utf-8")
vocab_data = vocab_file.readlines()
vocab_file.close()
index2word = dict()
word2index = dict()
for index, line in enumerate(vocab_data):
word = line.rstrip()
index2word[index] = word
word2index[word] = index
return word2index, index2word
def build_data(ori_path, rep_path, word2index):
unk_i = word2index['<unk>']
ori_file = open(ori_path, encoding="utf-8")
ori_tweets = ori_file.readlines()
ori_file.close()
rep_file = open(rep_path, encoding="utf-8")
rep_tweets = rep_file.readlines()
rep_file.close()
assert(len(ori_tweets) == len(rep_tweets))
emojis = []
ori_seqs = []
rep_seqs = []
for i in range(len(ori_tweets)):
ori_words = ori_tweets[i].split()
ori_tweet = [word2index.get(word, unk_i) for word in ori_words[1:]]
rep_words = rep_tweets[i].split()
rep_tweet = [word2index.get(word, unk_i) for word in rep_words]
assert len(ori_tweet) >= 3 and len(rep_tweet) >= 2
ori_seqs.append(ori_tweet)
rep_seqs.append(rep_tweet)
emojis.append(word2index.get(ori_words[0], unk_i))
return [
emojis,
ori_seqs,
rep_seqs
]
def generate_one_batch(data_l, start_i, end_i, s, e):
emojis = data_l[0]
ori_seqs = data_l[1]
rep_seqs = data_l[2]
if e is None:
e = len(emojis)
emoji_vec = np.array(emojis[s:e], dtype=np.int32)
ori_lengths = np.array([len(seq) for seq in ori_seqs[s:e]])
max_ori_len = np.max(ori_lengths)
min_ori_len = np.min(ori_lengths)
assert(min_ori_len > 0)
ori_matrix = np.zeros([max_ori_len, e - s], dtype=np.int32)
for i, seq in enumerate(ori_seqs[s:e]):
for j, elem in enumerate(seq):
ori_matrix[j, i] = elem
rep_lengths = np.array([len(seq) for seq in rep_seqs[s:e]])
max_rep_len = np.max(rep_lengths)
rep_matrix = np.zeros([max_rep_len, e - s], dtype=np.int32)
rep_input_matrix = np.zeros([max_rep_len + 1, e - s], dtype=np.int32)
rep_output_matrix = np.zeros([max_rep_len + 1, e - s], dtype=np.int32)
rep_input_matrix[0, :] = start_i
for i, seq in enumerate(rep_seqs[s:e]):
for j, elem in enumerate(seq):
rep_matrix[j, i] = elem
rep_input_matrix[j + 1, i] = elem
rep_output_matrix[j, i] = elem
rep_output_matrix[len(seq), i] = end_i
return [
emoji_vec,
ori_matrix,
ori_lengths,
rep_matrix,
rep_lengths,
rep_input_matrix,
rep_output_matrix
]
def batch_generator(data_l, start_i, end_i, batch_size, permutate=True):
# shuffle
emojis = data_l[0]
ori_seqs = data_l[1]
rep_seqs = data_l[2]
if permutate:
all_input = list(zip(emojis, ori_seqs, rep_seqs))
random.shuffle(all_input)
new_all = list(zip(*all_input))
else:
new_all = [emojis, ori_seqs, rep_seqs]
data_size = len(emojis)
num_batches = int((data_size - 1.) / batch_size) + 1
rtn = []
for batch_num in range(num_batches):
e = min((batch_num + 1) * batch_size, data_size)
s = e - batch_size
assert(s >= 0)
rtn.append(generate_one_batch(new_all, start_i, end_i, s, e))
return rtn
# for discriminator
def build_dis_data(human_path, machine_path, word2index):
unk_i = word2index['<unk>']
with open(human_path, encoding="utf-8") as f:
human_tweets = f.readlines()
with open(machine_path, encoding="utf-8") as f:
machine_tweets = f.readlines()
seqs = []
for i in range(len(human_tweets)):
words = human_tweets[i].split()
tweet = [word2index.get(word, unk_i) for word in words]
if len(tweet) < 3:
continue
seqs.append(tweet)
labels = [0] * len(seqs)
for i in range(len(machine_tweets)):
words = machine_tweets[i].split()
tweet = [word2index.get(word, unk_i) for word in words]
if len(tweet) < 3:
continue
seqs.append(tweet)
labels += [1] * (len(seqs)-len(labels))
assert len(labels) == len(seqs)
return [seqs, labels]
def generate_dis_batches(data_l, batch_size, permutate):
seqs = data_l[0]
labels = data_l[1]
if permutate:
all_input = list(zip(seqs, labels))
random.shuffle(all_input)
seqs, labels = list(zip(*all_input))
data_size = len(labels)
num_batches = int((data_size - 1.) / batch_size) + 1
batches = []
for batch_num in range(num_batches):
e = min((batch_num + 1) * batch_size, data_size)
s = e - batch_size
assert (s >= 0)
labels_vec = np.array(labels[s:e], dtype=np.int32)
text_lengths = np.array([len(seq) for seq in seqs[s:e]])
max_text_len = np.max(text_lengths)
min_text_len = np.min(text_lengths)
assert (min_text_len > 0)
text_matrix = np.zeros([max_text_len, batch_size], dtype=np.int32)
for i, seq in enumerate(seqs[s:e]):
for j, elem in enumerate(seq):
text_matrix[j, i] = elem
one_batch = [text_matrix, text_lengths, labels_vec]
batches.append(one_batch)
return batches
"""utils"""
def safe_exp(value):
"""Exponentiation with catching of overflow error."""
try:
ans = math.exp(value)
except OverflowError:
ans = float("inf")
return ans
def generate_graph():
graph_def = tf.get_default_graph().as_graph_def()
graphpb_txt = str(graph_def)
with open('miscellanies/graphpb.txt', 'w') as f:
f.write(graphpb_txt)
exit(0)
class Printer(object):
def __init__(self, f, index2word=None):
self.log_f = f
self.index2word = index2word
def __call__(self, s, new_line=True):
if new_line:
now = strftime("%m-%d %H:%M:%S", gmtime())
s += "\t" + now
self.log_f.write(s)
if new_line:
self.log_f.write("\n")
self.log_f.flush()
print(s, end="", file=sys.stdout)
if new_line:
sys.stdout.write("\n")
sys.stdout.flush()
def put_bleu(self, recon_loss, kl_loss, bow_loss, ppl, bleu_score, precisions_list, name):
self("%s: " % name, new_line=False)
format_string = '\trecon/kl/bow-loss/ppl:\t%.3f\t%.3f\t%.3f\t%.3f\tBLEU:' + '\t%.1f' * 5
format_tuple = (recon_loss, kl_loss, bow_loss, ppl, bleu_score) + tuple(precisions_list)
self(format_string % format_tuple)
def put_step(self, epoch, step):
self("epoch:%d step:%d\t" % (epoch, step), new_line=False)
def put_list(self, l):
for ll in l:
self("%.3f\t" % ll, new_line=False)
self('')
def put_example(self, model):
def _put_example(indices):
to_write = ''
for index in indices:
to_write += self.index2word[index] + ' '
return to_write
ori = _put_example(model.ori_sample)
rep = _put_example(model.rep_sample)
out = _put_example(model.out_sample)
self('ori: ' + ori)
self('rep: ' + rep)
self('out: ' + out)
def print_out(s, f=None, new_line=True):
"""Similar to print but with support to flush and output to a file."""
if f:
f.write(s)
if new_line:
f.write("\n")
f.flush()
# stdout
print(s, end="", file=sys.stdout)
if new_line:
sys.stdout.write("\n")
sys.stdout.flush()
def put_eval(recon_loss, kl_loss, bow_loss, ppl, bleu_score, precisions_list, name, f):
print_out("%s: " % name, new_line=False, f=f)
format_string = '\trecon/kl/bow-loss/ppl:\t%.3f\t%.3f\t%.3f\t%.3f\tBLEU:' + '\t%.1f' * 5
format_tuple = (recon_loss, kl_loss, bow_loss, ppl, bleu_score) + tuple(precisions_list)
print_out(format_string % format_tuple, f=f)
def write_out(filename, corpus, index2word):
with open(filename, 'w', encoding="utf-8") as f:
for seq in corpus:
to_write = ''
for index in seq:
to_write += index2word[index] + ' '
f.write(to_write + '\n')
def write_out_for_eval(filename, corpus, emo_correct, emojis, index2word):
# assert len(corpus) == len(emojis)
# assert len(corpus) == len(emo_correct)
with open(filename, 'w', encoding="utf-8") as f:
for i, seq in enumerate(corpus):
to_write = '%s %d %d ' % (index2word[emojis[i]], int(emo_correct[i]), emojis[i])
for index in seq:
to_write += index2word[index] + ' '
f.write(to_write + '\n')
def restore_best(file):
with open(file) as f:
best_dict = json.load(f)
best_bleu, best_epoch, best_step = best_dict["bleu"], best_dict["epoch"], best_dict["step"]
return best_bleu, best_epoch, best_step
def get_kl_weight(global_step, total_step, ratio):
# python3!
progress = global_step / total_step
if progress >= ratio:
return 1.
else:
return tanh(6 * progress / ratio - 3) + 1