-
Notifications
You must be signed in to change notification settings - Fork 2
/
data_loader.py
411 lines (338 loc) · 15.7 KB
/
data_loader.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
#!/usr/bin/python3
# Author: GMFTBY
# Time: 2019.9.25
'''
data loader of [flatten, hierarchical], [cf, ncf], [GCN, unGCN] mode
'''
import torch
import torch.nn as nn
import numpy as np
import math
import random
import ipdb
import nltk
from utils import *
def load_data(src, tgt, src_vocab, tgt_vocab, maxlen):
# sort by the lengths
# convert src data from [datasize, (user, utterance)] into [datasize, turns, lengths]
# convert tgt data from [datasize, (user, utterance)] into [datasize, length]
src_w2idx, src_idx2w = load_pickle(src_vocab)
tgt_w2idx, tgt_idx2w = load_pickle(tgt_vocab)
src, tgt = load_pickle(src), load_pickle(tgt)
# src
src_d = []
for example in src:
turn = []
for user, utterance in example:
if '<0>' in utterance: user_c = '<0>'
elif '<1>' in utterance: user_c = '<1>'
utterance = utterance.replace(user_c, '').strip()
line = [src_w2idx['<sos>'], src_w2idx[user_c]] + [src_w2idx.get(w, src_w2idx['<unk>']) for w in nltk.word_tokenize(utterance)] + [src_w2idx['<eos>']]
if len(line) > maxlen:
line = [src_w2idx['<sos>']] + line[-maxlen:]
turn.append(line)
src_d.append(turn)
# tgt
tgt_d = []
for example in tgt:
turn = []
user, utterance = example[0]
if '<0>' in utterance: user_c = '<0>'
elif '<1>' in utterance: user_c = '<1>'
utterance = utterance.replace(user_c, '').strip()
line = [tgt_w2idx['<sos>'], tgt_w2idx[user_c]] + [tgt_w2idx.get(w, tgt_w2idx['<unk>']) for w in nltk.word_tokenize(utterance)] + [tgt_w2idx['<eos>']]
if len(line) > maxlen:
line = [tgt_w2idx['<sos>']] + line[-maxlen:]
tgt_d.append(line)
return src_d, tgt_d
def load_data_flatten(src, tgt, src_vocab, tgt_vocab, maxlen):
# return [datasize, length]
src_w2idx, src_idx2w = load_pickle(src_vocab)
tgt_w2idx, tgt_idx2w = load_pickle(tgt_vocab)
src, tgt = load_pickle(src), load_pickle(tgt)
def load_(data, vocab):
d = []
for example in data:
utterances = ' <eou> '.join([i[1] for i in example])
utterances = utterances.replace('<0>', '').strip()
utterances = utterances.replace('<1>', '').strip()
line = [vocab['<sos>']] + [vocab.get(w, vocab['<unk>']) for w in nltk.word_tokenize(utterances)] + [vocab['<eos>']]
if len(line) > maxlen:
line = [vocab['<sos>']] + line[-maxlen:]
d.append(line)
return d
src_dataset = load_(src, src_w2idx)
tgt_dataset = load_(tgt, tgt_w2idx)
return src_dataset, tgt_dataset
def get_batch_data_flatten(src, tgt, src_vocab, tgt_vocab, batch_size, maxlen, plus=0):
# flatten mode donot need plus
src_w2idx, src_idx2w = load_pickle(src_vocab)
tgt_w2idx, tgt_idx2w = load_pickle(tgt_vocab)
src_dataset, tgt_dataset = load_data_flatten(src, tgt, src_vocab, tgt_vocab, maxlen)
turns = [len(dialog) for dialog in src_dataset]
turnidx = np.argsort(turns)
# sort by the length of the turns
src_dataset = [src_dataset[idx] for idx in turnidx]
tgt_dataset = [tgt_dataset[idx] for idx in turnidx]
# batch convert to tensor
fidx, bidx = 0, 0
while fidx < len(src_dataset):
bidx = fidx + batch_size
sbatch, tbatch = src_dataset[fidx:bidx], tgt_dataset[fidx:bidx]
# shuffle
shuffleidx = np.arange(0, len(sbatch))
np.random.shuffle(shuffleidx)
sbatch = [sbatch[idx] for idx in shuffleidx]
tbatch = [tbatch[idx] for idx in shuffleidx]
bs = len(sbatch)
# pad sbatch and tbatch
turn_lengths = [len(sbatch[i]) for i in range(bs)]
pad_sequence(src_w2idx['<pad>'], sbatch, bs)
pad_sequence(tgt_w2idx['<pad>'], tbatch, bs)
# [seq_len, batch]
sbatch = torch.tensor(sbatch, dtype=torch.long).transpose(0, 1)
tbatch = torch.tensor(tbatch, dtype=torch.long).transpose(0, 1)
turn_lengths = torch.tensor(turn_lengths, dtype=torch.long)
if torch.cuda.is_available():
tbatch = tbatch.cuda()
sbatch = sbatch.cuda()
turn_lengths = turn_lengths.cuda()
fidx = bidx
yield sbatch, tbatch, turn_lengths
def get_batch_data(src, tgt, src_vocab, tgt_vocab, batch_size, maxlen, plus=0):
src_w2idx, src_idx2w = load_pickle(src_vocab)
tgt_w2idx, tgt_idx2w = load_pickle(tgt_vocab)
src_dataset, tgt_dataset = load_data(src, tgt, src_vocab, tgt_vocab, maxlen)
turns = [len(dialog) for dialog in src_dataset]
turnidx = np.argsort(turns)
src_dataset = [src_dataset[idx] for idx in turnidx]
tgt_dataset = [tgt_dataset[idx] for idx in turnidx]
turns = [len(dialog) for dialog in src_dataset]
fidx, bidx = 0, 0
while fidx < len(src_dataset):
bidx = fidx + batch_size
head = turns[fidx]
cidx = 10000
for p, i in enumerate(turns[fidx:bidx]):
if i != head:
cidx = p
break
cidx = fidx + cidx
bidx = min(bidx, cidx)
sbatch, tbatch = src_dataset[fidx:bidx], tgt_dataset[fidx:bidx]
if len(sbatch[0]) <= plus:
fidx = bidx
continue
shuffleidx = np.arange(0, len(sbatch))
np.random.shuffle(shuffleidx)
sbatch = [sbatch[idx] for idx in shuffleidx]
tbatch = [tbatch[idx] for idx in shuffleidx]
sbatch = transformer_list(sbatch) # [turns, batch, lengths]
bs, ts = len(sbatch[0]), len(sbatch)
turn_lengths = []
for i in range(ts):
lengths = []
for item in sbatch[i]:
lengths.append(len(item))
turn_lengths.append(lengths)
pad_sequence(src_w2idx['<pad>'], sbatch[i], bs)
pad_sequence(tgt_w2idx['<pad>'], tbatch, bs)
srcbatch = []
for i in range(ts):
pause = torch.tensor(sbatch[i], dtype=torch.long).transpose(0, 1)
if torch.cuda.is_available():
pause = pause.cuda()
srcbatch.append(pause)
sbatch = srcbatch
tbatch = torch.tensor(tbatch, dtype=torch.long).transpose(0, 1)
if torch.cuda.is_available():
tbatch = tbatch.cuda()
turn_lengths = torch.tensor(turn_lengths, dtype=torch.long)
if torch.cuda.is_available():
turn_lengths = turn_lengths.cuda()
fidx = bidx
yield sbatch, tbatch, turn_lengths
def get_batch_data_cf(src, tgt, src_vocab, tgt_vocab, batch_size, maxlen, plus=0):
'''get batch data of [cf & hierarchical]
return data:
- sbatch: [turn, batch, length]
- tbatch: [batch, length]
- subatch: [batch], src user
- tubatch: [batch], tgt user
- label: [batch], speaking timing
- turn_lengths: [batch]
'''
src_w2idx, src_idx2w = load_pickle(src_vocab)
tgt_w2idx, tgt_idx2w = load_pickle(tgt_vocab)
src_dataset, src_user, tgt_dataset, tgt_user, label = load_data_cf(src, tgt, src_vocab, tgt_vocab, maxlen)
turns = [len(dialog) for dialog in src_dataset]
turnidx = np.argsort(turns)
# [datasize, turn, lengths]
src_dataset = [src_dataset[idx] for idx in turnidx]
tgt_dataset = [tgt_dataset[idx] for idx in turnidx]
src_user = [src_user[idx] for idx in turnidx]
tgt_user = [tgt_user[idx] for idx in turnidx]
label = [label[idx] for idx in turnidx]
turns = [len(dialog) for dialog in src_dataset]
fidx, bidx = 0, 0
while fidx < len(src_dataset):
bidx = fidx + batch_size
head = turns[fidx]
cidx = 10000
for p, i in enumerate(turns[fidx:bidx]):
if i != head:
cidx = p
break
cidx = fidx + cidx
bidx = min(bidx, cidx)
sbatch, tbatch, subatch, tubatch, lbatch = src_dataset[fidx:bidx], tgt_dataset[fidx:bidx], src_user[fidx:bidx], tgt_user[fidx:bidx], label[fidx:bidx]
if len(sbatch[0]) <= plus:
fidx = bidx
continue
shuffleidx = np.arange(0, len(sbatch))
np.random.shuffle(shuffleidx)
sbatch = [sbatch[idx] for idx in shuffleidx] # [batch, turns, lengths]
tbatch = [tbatch[idx] for idx in shuffleidx] # [batch, lengths]
subatch = [subatch[idx] for idx in shuffleidx] # [batch, turns]
tubatch = [tubatch[idx] for idx in shuffleidx] # [batch,]
lbatch = [lbatch[idx] for idx in shuffleidx] # [batch,]
sbatch = transformer_list(sbatch) # [turns, batch, lengths]
bs, ts = len(sbatch[0]), len(sbatch)
turn_lengths = []
for i in range(ts):
lengths = []
for item in sbatch[i]:
lengths.append(len(item))
turn_lengths.append(lengths)
pad_sequence(src_w2idx['<pad>'], sbatch[i], bs)
pad_sequence(tgt_w2idx['<pad>'], tbatch, bs)
# convert to tensor
srcbatch = []
for i in range(ts):
pause = torch.tensor(sbatch[i], dtype=torch.long).transpose(0, 1)
if torch.cuda.is_available():
pause = pause.cuda()
srcbatch.append(pause) # [turns, seq_len, batch]
sbatch = srcbatch
tbatch = torch.tensor(tbatch, dtype=torch.long).transpose(0, 1) # [seq_len, batch]
subatch = torch.tensor(subatch, dtype=torch.long).transpose(0, 1) # [turns, batch]
tubatch = torch.tensor(tubatch, dtype=torch.long) # [batch]
lbatch = torch.tensor(lbatch, dtype=torch.float) # [batch]
turn_lengths = torch.tensor(turn_lengths, dtype=torch.long) # [batch]
if torch.cuda.is_available():
tbatch = tbatch.cuda()
subatch = subatch.cuda()
tubatch = tubatch.cuda()
lbatch = lbatch.cuda()
turn_lengths = turn_lengths.cuda()
fidx = bidx
yield sbatch, tbatch, subatch, tubatch, lbatch, turn_lengths
def get_batch_data_cf_graph(src, tgt, graph, src_vocab, tgt_vocab, batch_size, maxlen, plus=0):
'''get batch data of [cf & hierarchical & graph]
return data:
- sbatch: [turn, batch, length]
- tbatch: [batch, length]
- gbatch: [batch, ([2, num_edge], [num_edge])]
- subatch: [batch], src user
- tubatch: [batch], tgt user
- label: [batch], speaking timing
- turn_lengths: [batch]
'''
src_w2idx, src_idx2w = load_pickle(src_vocab)
tgt_w2idx, tgt_idx2w = load_pickle(tgt_vocab)
src_dataset, src_user, tgt_dataset, tgt_user, label = load_data_cf(src, tgt, src_vocab, tgt_vocab, maxlen)
graph = load_pickle(graph) # [datasize, (edges, weight)]
turns = [len(dialog) for dialog in src_dataset]
# prune the dataset before the shuffle processing
turnidx = np.argsort(turns)
# [datasize, turn, lengths]
src_dataset = [src_dataset[idx] for idx in turnidx]
tgt_dataset = [tgt_dataset[idx] for idx in turnidx]
graph = [graph[idx] for idx in turnidx]
src_user = [src_user[idx] for idx in turnidx]
tgt_user = [tgt_user[idx] for idx in turnidx]
label = [label[idx] for idx in turnidx]
turns = [len(dialog) for dialog in src_dataset]
fidx, bidx = 0, 0
while fidx < len(src_dataset):
bidx = fidx + batch_size
head = turns[fidx]
cidx = 10000
for p, i in enumerate(turns[fidx:bidx]):
if i != head:
cidx = p
break
cidx = fidx + cidx
bidx = min(bidx, cidx)
sbatch, tbatch, subatch, tubatch, lbatch = src_dataset[fidx:bidx], tgt_dataset[fidx:bidx], src_user[fidx:bidx], tgt_user[fidx:bidx], label[fidx:bidx]
gbatch = graph[fidx:bidx]
# check the turn size for the plus experiment mode
if len(sbatch[0]) <= plus:
fidx = bidx
continue
shuffleidx = np.arange(0, len(sbatch))
np.random.shuffle(shuffleidx)
sbatch = [sbatch[idx] for idx in shuffleidx] # [batch, turns, lengths]
tbatch = [tbatch[idx] for idx in shuffleidx] # [batch, lengths]
subatch = [subatch[idx] for idx in shuffleidx] # [batch, turns]
tubatch = [tubatch[idx] for idx in shuffleidx] # [batch,]
lbatch = [lbatch[idx] for idx in shuffleidx] # [batch,]
gbatch = [gbatch[idx] for idx in shuffleidx] # [batch, ([2, edges_num], [edges_num]),]
sbatch = transformer_list(sbatch) # [turns, batch, lengths]
bs, ts = len(sbatch[0]), len(sbatch)
# gbatch can be converted to a DataLoader which only hold one batch
# https://pytorch-geometric.readthedocs.io/en/latest/notes/create_dataset.html, FAQ(2)
# the dataloader will be created in the model/when2talk.py
# because of it needs the hidden state of the utterance encode as the node features, here we only need to return the gbatch
turn_lengths = []
for i in range(ts):
lengths = []
for item in sbatch[i]:
lengths.append(len(item))
turn_lengths.append(lengths)
pad_sequence(src_w2idx['<pad>'], sbatch[i], bs)
pad_sequence(tgt_w2idx['<pad>'], tbatch, bs)
# convert to tensor
srcbatch = []
for i in range(ts):
pause = torch.tensor(sbatch[i], dtype=torch.long).transpose(0, 1)
if torch.cuda.is_available():
pause = pause.cuda()
srcbatch.append(pause) # [turns, seq_len, batch]
sbatch = srcbatch
tbatch = torch.tensor(tbatch, dtype=torch.long).transpose(0, 1) # [seq_len, batch]
subatch = torch.tensor(subatch, dtype=torch.long).transpose(0, 1) # [turns, batch]
tubatch = torch.tensor(tubatch, dtype=torch.long) # [batch]
lbatch = torch.tensor(lbatch, dtype=torch.float) # [batch]
turn_lengths = torch.tensor(turn_lengths, dtype=torch.long) # [batch]
if torch.cuda.is_available():
tbatch = tbatch.cuda()
subatch = subatch.cuda()
tubatch = tubatch.cuda()
lbatch = lbatch.cuda()
turn_lengths = turn_lengths.cuda()
fidx = bidx
yield sbatch, tbatch, gbatch, subatch, tubatch, lbatch, turn_lengths
if __name__ == "__main__":
# batch_num = 0
# for sbatch, tbatch, turn_lengths in get_batch_data_flatten('./data/cornell-corpus/ncf/src-train.pkl',
# './data/cornell-corpus/ncf/tgt-train.pkl',
# './processed/cornell/iptvocab.pkl',
# './processed/cornell/optvocab.pkl', 32, 150):
# print(len(sbatch), tbatch.shape, turn_lengths.shape)
# batch_num += 1
# print(batch_num)
batch_num, zero, one = 0, 0, 0
# stat the ratio of the 0 label in the cf mode dataset
for sbatch, tbatch, gbatch, subatch, tubatch, lbatch, turn_lengths in get_batch_data_cf_graph('./data/dailydialog-corpus/cf/src-train.pkl',
'./data/dailydialog-corpus/cf/tgt-train.pkl',
'./processed/dailydialog/train-graph.pkl',
'./processed/dailydialog/iptvocab.pkl',
'./processed/dailydialog/optvocab.pkl', 32, 50):
if batch_num == 6719:
ipdb.set_trace()
batch_num += 1
o = torch.sum(lbatch).item()
one += o
zero += len(lbatch) - o
print(batch_num, zero, one)