-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_loader.py
1804 lines (1381 loc) · 67.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
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import io
import random
import string
import re
import copy
import json
import pandas as pd
import numpy as np
from collections import OrderedDict
import nltk
from nltk import FreqDist
from nltk.tokenize import word_tokenize
from nltk.stem.wordnet import WordNetLemmatizer
import config
COMMA_PLACEHOLDER = config.COMMA_PLACEHOLDER
EMPH_TOKEN = config.EMPH_TOKEN
CONTRAST_TOKEN = config.CONTRAST_TOKEN
CONCESSION_TOKEN = config.CONCESSION_TOKEN
# TODO: redesign the data loading so as to be object-oriented
def load_training_data(data_trainset, data_devset, input_concat=False, generate_vocab=False):
"""Generate source and target files in the required input format for the model training.
"""
training_source_file = os.path.join(config.DATA_DIR, 'training_source.txt')
training_target_file = os.path.join(config.DATA_DIR, 'training_target.txt')
dev_source_file = os.path.join(config.DATA_DIR, 'dev_source.txt')
dev_target_file = os.path.join(config.DATA_DIR, 'dev_target.txt')
# If there is an existing source and target file, skip their generation
if os.path.isfile(training_source_file) and \
os.path.isfile(training_target_file) and \
os.path.isfile(dev_source_file) and \
os.path.isfile(dev_target_file):
print('Found existing input files. Skipping their generation.')
return
dataset = init_training_data(data_trainset, data_devset)
dataset_name = dataset['dataset_name']
x_train, y_train, x_dev, y_dev = dataset['data']
slot_sep, val_sep, val_sep_closing = dataset['separators']
# TODO: do the utterances still need to be parsed into lists of words?
# Parse the utterances into lists of words
y_train = [preprocess_utterance(y) for y in y_train]
y_dev = [preprocess_utterance(y) for y in y_dev]
# Produce sequences of extracted words from the meaning representations (MRs) in the trainset
x_train_seq = []
for i, mr in enumerate(x_train):
slot_ctr = 0
emph_idxs = set()
mr_dict = OrderedDict()
# Extract the slot-value pairs into a dictionary
for slot_value in mr.split(slot_sep):
slot, value, _, _ = parse_slot_and_value(slot_value, val_sep, val_sep_closing)
if slot == EMPH_TOKEN:
emph_idxs.add(slot_ctr)
else:
mr_dict[slot] = value
slot_ctr += 1
# Delexicalize the MR and the utterance
y_train[i] = delex_sample(mr_dict, y_train[i], dataset=dataset_name, input_concat=input_concat)
slot_ctr = 0
# Convert the dictionary to a list
x_train_seq.append([])
for key, val in mr_dict.items():
# Insert the emphasis token where appropriate
if slot_ctr in emph_idxs:
x_train_seq[i].append(EMPH_TOKEN)
if len(val) > 0:
x_train_seq[i].extend([key] + val.split())
else:
x_train_seq[i].append(key)
slot_ctr += 1
if input_concat:
# Append a sequence-end token to be paired up with seq2seq's sequence-end token when concatenating
x_train_seq[i].append('<STOP>')
# Produce sequences of extracted words from the meaning representations (MRs) in the devset
x_dev_seq = []
for i, mr in enumerate(x_dev):
slot_ctr = 0
emph_idxs = set()
mr_dict = OrderedDict()
# Extract the slot-value pairs into a dictionary
for slot_value in mr.split(slot_sep):
slot, value, _, _ = parse_slot_and_value(slot_value, val_sep, val_sep_closing)
if slot == EMPH_TOKEN:
emph_idxs.add(slot_ctr)
else:
mr_dict[slot] = value
slot_ctr += 1
# Delexicalize the MR and the utterance
y_dev[i] = delex_sample(mr_dict, y_dev[i], dataset=dataset_name, input_concat=input_concat)
slot_ctr = 0
# Convert the dictionary to a list
x_dev_seq.append([])
for key, val in mr_dict.items():
# Insert the emphasis token where appropriate
if slot_ctr in emph_idxs:
x_dev_seq[i].append(EMPH_TOKEN)
if len(val) > 0:
x_dev_seq[i].extend([key] + val.split())
else:
x_dev_seq[i].append(key)
slot_ctr += 1
if input_concat:
# Append a sequence-end token to be paired up with seq2seq's sequence-end token when concatenating
x_dev_seq[i].append('<STOP>')
# Generate a vocabulary file if necessary
if generate_vocab:
generate_vocab_file(np.concatenate(x_train_seq + x_dev_seq + y_train + y_dev),
vocab_filename='vocab.lang_gen.tokens')
# generate_vocab_file(np.concatenate(x_train_seq + x_dev_seq),
# vocab_filename='vocab.lang_gen_multi_vocab.source')
# generate_vocab_file(np.concatenate(y_train + y_dev),
# vocab_filename='vocab.lang_gen_multi_vocab.target')
with io.open(training_source_file, 'w', encoding='utf8') as f_x_train:
for line in x_train_seq:
f_x_train.write('{}\n'.format(' '.join(line)))
with io.open(training_target_file, 'w', encoding='utf8') as f_y_train:
for line in y_train:
f_y_train.write('{}\n'.format(' '.join(line)))
with io.open(dev_source_file, 'w', encoding='utf8') as f_x_dev:
for line in x_dev_seq:
f_x_dev.write('{}\n'.format(' '.join(line)))
with io.open(dev_target_file, 'w', encoding='utf8') as f_y_dev:
for line in y_dev:
f_y_dev.write('{}\n'.format(' '.join(line)))
return np.concatenate(x_train_seq + x_dev_seq + y_train + y_dev).flatten()
def load_test_data(data_testset, input_concat=False):
"""Generate source and target files in the required input format for the model testing.
"""
test_source_file = os.path.join(config.DATA_DIR, 'test_source.txt')
test_source_dict_file = os.path.join(config.DATA_DIR, 'test_source_dict.json')
test_target_file = os.path.join(config.DATA_DIR, 'test_target.txt')
test_reference_file = os.path.join(config.METRICS_DIR, 'test_references.txt')
dataset = init_test_data(data_testset)
dataset_name = dataset['dataset_name']
x_test, y_test = dataset['data']
slot_sep, val_sep, val_sep_closing = dataset['separators']
# Produce sequences of extracted words from the meaning representations (MRs) in the testset
x_test_seq = []
x_test_dict = []
for i, mr in enumerate(x_test):
slot_ctr = 0
emph_idxs = set()
mr_dict = OrderedDict()
mr_dict_cased = OrderedDict()
# Extract the slot-value pairs into a dictionary
for slot_value in mr.split(slot_sep):
slot, value, _, value_orig = parse_slot_and_value(slot_value, val_sep, val_sep_closing)
if slot == EMPH_TOKEN:
emph_idxs.add(slot_ctr)
else:
mr_dict[slot] = value
mr_dict_cased[slot] = value_orig
slot_ctr += 1
# Build an MR dictionary with original values
x_test_dict.append(mr_dict_cased)
# Delexicalize the MR
delex_sample(mr_dict, dataset=dataset_name, mr_only=True, input_concat=input_concat)
slot_ctr = 0
# Convert the dictionary to a list
x_test_seq.append([])
for key, val in mr_dict.items():
# Insert the emphasis token where appropriate
if slot_ctr in emph_idxs:
x_test_seq[i].append(EMPH_TOKEN)
if len(val) > 0:
x_test_seq[i].extend([key] + val.split())
else:
x_test_seq[i].append(key)
slot_ctr += 1
if input_concat:
# Append a sequence-end token to be paired up with seq2seq's sequence-end token when concatenating
x_test_seq[i].append('<STOP>')
with io.open(test_source_file, 'w', encoding='utf8') as f_x_test:
for line in x_test_seq:
f_x_test.write('{}\n'.format(' '.join(line)))
with io.open(test_source_dict_file, 'w', encoding='utf8') as f_x_test_dict:
json.dump(x_test_dict, f_x_test_dict)
if len(y_test) > 0:
with io.open(test_target_file, 'w', encoding='utf8') as f_y_test:
for line in y_test:
f_y_test.write(line + '\n')
# Reference file for calculating metrics for test predictions
with io.open(test_reference_file, 'w', encoding='utf8') as f_y_test:
for i, line in enumerate(y_test):
if i > 0 and x_test[i] != x_test[i - 1]:
f_y_test.write('\n')
f_y_test.write(line + '\n')
def generate_vocab_file(token_sequences, vocab_filename, vocab_size=10000):
vocab_file = os.path.join(config.DATA_DIR, vocab_filename)
distr = FreqDist(token_sequences)
vocab = distr.most_common(min(len(distr), vocab_size - 3)) # cap the vocabulary size
vocab_with_reserved_tokens = ['<pad>', '<EOS>'] + list(map(lambda tup: tup[0], vocab)) + ['UNK']
with io.open(vocab_file, 'w', encoding='utf8') as f_vocab:
for token in vocab_with_reserved_tokens:
f_vocab.write('{}\n'.format(token))
def get_vocabulary(token_sequences, vocab_size=10000):
distr = FreqDist(token_sequences)
vocab = distr.most_common(min(len(distr), vocab_size)) # cap the vocabulary size
vocab_set = set(map(lambda tup: tup[0], vocab))
return vocab_set
def tokenize_mr(mr, add_eos_token=True):
"""Produces a (delexicalized) sequence of tokens from the input MR.
"""
slot_sep = ','
val_sep = '['
val_sep_closing = True
mr_seq = []
mr_dict = OrderedDict()
# extract the slot-value pairs into a dictionary
for slot_value in mr.split(slot_sep):
slot, value, _, _ = parse_slot_and_value(slot_value, val_sep, val_sep_closing)
mr_dict[slot] = value
# make a copy of the dictionary for delexing
mr_dict_delex = copy.deepcopy(mr_dict)
# delexicalize the MR
delex_sample(mr_dict_delex, mr_only=True)
# convert the dictionary to a list
for key, val in mr_dict_delex.items():
if len(val) > 0:
mr_seq.extend([key, val])
else:
mr_seq.append(key)
# append the sequence-end token
if add_eos_token:
mr_seq.append('SEQUENCE_END')
return mr_seq, mr_dict
def load_training_data_for_eval(data_trainset, data_model_outputs_train, vocab_size, max_input_seq_len, max_output_seq_len, delex=False):
dataset_name = ''
slot_sep = ''
val_sep = ''
val_sep_closing = False
if '/rest_e2e/' in data_trainset or '\\rest_e2e\\' in data_trainset:
x_train, y_train_1 = read_rest_e2e_dataset_train(data_trainset)
y_train_2 = read_predictions(data_model_outputs_train)
dataset_name = 'rest_e2e'
slot_sep = ','
val_sep = '['
val_sep_closing = True
elif '/tv/' in data_trainset or '\\tv\\' in data_trainset:
x_train, y_train_1, y_train_2 = read_tv_dataset_train(data_trainset)
if data_model_outputs_train is not None:
y_train_2 = read_predictions(data_model_outputs_train)
dataset_name = 'tv'
slot_sep = ';'
val_sep = '='
elif '/laptop/' in data_trainset or '\\laptop\\' in data_trainset:
x_train, y_train_1, y_train_2 = read_laptop_dataset_train(data_trainset)
if data_model_outputs_train is not None:
y_train_2 = read_predictions(data_model_outputs_train)
dataset_name = 'laptop'
slot_sep = ';'
val_sep = '='
else:
raise FileNotFoundError
# parse the utterances into lists of words
y_train_1 = [preprocess_utterance(y) for y in y_train_1]
y_train_2 = [preprocess_utterance(y) for y in y_train_2]
# produce sequences of extracted words from the meaning representations (MRs) in the trainset
x_train_seq = []
for i, mr in enumerate(x_train):
mr_dict = OrderedDict()
for slot_value in mr.split(slot_sep):
slot, value, _, _ = parse_slot_and_value(slot_value, val_sep, val_sep_closing)
mr_dict[slot] = value
if delex == True:
# delexicalize the MR and the utterance
y_train_1[i] = delex_sample(mr_dict, y_train_1[i], dataset=dataset_name, utterance_only=True)
y_train_2[i] = delex_sample(mr_dict, y_train_2[i], dataset=dataset_name)
# convert the dictionary to a list
x_train_seq.append([])
for key, val in mr_dict.items():
if len(val) > 0:
x_train_seq[i].extend([key, val])
else:
x_train_seq[i].append(key)
# create source vocabulary
if os.path.isfile('data/eval_vocab_source.json'):
with io.open('data/eval_vocab_source.json', 'r', encoding='utf8') as f_x_vocab:
x_vocab = json.load(f_x_vocab)
else:
x_distr = FreqDist([x_token for x in x_train_seq for x_token in x])
x_vocab = x_distr.most_common(min(len(x_distr), vocab_size - 2)) # cap the vocabulary size
with io.open('data/eval_vocab_source.json', 'w', encoding='utf8') as f_x_vocab:
json.dump(x_vocab, f_x_vocab, ensure_ascii=False)
x_idx2word = [word[0] for word in x_vocab]
x_idx2word.insert(0, '<PADDING>')
x_idx2word.append('<NA>')
x_word2idx = {word: idx for idx, word in enumerate(x_idx2word)}
# create target vocabulary
if os.path.isfile('data/eval_vocab_target.json'):
with io.open('data/eval_vocab_target.json', 'r', encoding='utf8') as f_y_vocab:
y_vocab = json.load(f_y_vocab)
else:
y_distr = FreqDist([y_token for y in y_train_1 for y_token in y] + [y_token for y in y_train_2 for y_token in y])
y_vocab = y_distr.most_common(min(len(y_distr), vocab_size - 2)) # cap the vocabulary size
with io.open('data/eval_vocab_target.json', 'w', encoding='utf8') as f_y_vocab:
json.dump(y_vocab, f_y_vocab, ensure_ascii=False)
y_idx2word = [word[0] for word in y_vocab]
y_idx2word.insert(0, '<PADDING>')
y_idx2word.append('<NA>')
y_word2idx = {token: idx for idx, token in enumerate(y_idx2word)}
# produce sequences of indexes from the MRs in the training set
x_train_enc = token_seq_to_idx_seq(x_train_seq, x_word2idx, max_input_seq_len)
# produce sequences of indexes from the utterances in the training set
y_train_1_enc = token_seq_to_idx_seq(y_train_1, y_word2idx, max_output_seq_len)
# produce sequences of indexes from the utterances in the training set
y_train_2_enc = token_seq_to_idx_seq(y_train_2, y_word2idx, max_output_seq_len)
# produce the list of the target labels in the training set
labels_train = np.concatenate((np.ones(len(y_train_1_enc)), np.zeros(len(y_train_2_enc))))
return (np.concatenate((np.array(x_train_enc), np.array(x_train_enc))),
np.concatenate((np.array(y_train_1_enc), np.array(y_train_2_enc))),
labels_train)
def load_dev_data_for_eval(data_devset, data_model_outputs_dev, vocab_size, max_input_seq_len, max_output_seq_len, delex=True):
dataset_name = ''
slot_sep = ''
val_sep = ''
val_sep_closing = False
if '/rest_e2e/' in data_devset or '\\rest_e2e\\' in data_devset:
x_dev, y_dev_1 = read_rest_e2e_dataset_dev(data_devset)
y_dev_2 = read_predictions(data_model_outputs_dev)
dataset_name = 'rest_e2e'
slot_sep = ','
val_sep = '['
val_sep_closing = True
elif '/tv/' in data_devset or '\\tv\\' in data_devset:
x_dev, y_dev_1, y_dev_2 = read_tv_dataset_dev(data_devset)
if data_model_outputs_dev is not None:
y_dev_2 = read_predictions(data_model_outputs_dev)
dataset_name = 'tv'
slot_sep = ';'
val_sep = '='
elif '/laptop/' in data_devset or '\\laptop\\' in data_devset:
x_dev, y_dev_1, y_dev_2 = read_laptop_dataset_dev(data_devset)
if data_model_outputs_dev is not None:
y_dev_2 = read_predictions(data_model_outputs_dev)
dataset_name = 'laptop'
slot_sep = ';'
val_sep = '='
else:
raise FileNotFoundError
# parse the utterances into lists of words
y_dev_1 = [preprocess_utterance(y) for y in y_dev_1]
y_dev_2 = [preprocess_utterance(y) for y in y_dev_2]
# produce sequences of extracted words from the meaning representations (MRs) in the devset
x_dev_seq = []
for i, mr in enumerate(x_dev):
mr_dict = OrderedDict()
for slot_value in mr.split(slot_sep):
slot, value, _, _ = parse_slot_and_value(slot_value, val_sep, val_sep_closing)
mr_dict[slot] = value
if delex == True:
# delexicalize the MR and the utterance
y_dev_1[i] = delex_sample(mr_dict, y_dev_1[i], dataset=dataset_name, utterance_only=True)
y_dev_2[i] = delex_sample(mr_dict, y_dev_2[i], dataset=dataset_name)
# convert the dictionary to a list
x_dev_seq.append([])
for key, val in mr_dict.items():
if len(val) > 0:
x_dev_seq[i].extend([key, val])
else:
x_dev_seq[i].append(key)
# load the source vocabulary
with io.open('data/eval_vocab_source.json', 'r', encoding='utf8') as f_x_vocab:
x_vocab = json.load(f_x_vocab)
x_idx2word = [word[0] for word in x_vocab]
x_idx2word.insert(0, '<PADDING>')
x_idx2word.append('<NA>')
x_word2idx = {word: idx for idx, word in enumerate(x_idx2word)}
# load the target vocabulary
with io.open('data/eval_vocab_target.json', 'r', encoding='utf8') as f_y_vocab:
y_vocab = json.load(f_y_vocab)
y_idx2word = [word[0] for word in y_vocab]
y_idx2word.insert(0, '<PADDING>')
y_idx2word.append('<NA>')
y_word2idx = {token: idx for idx, token in enumerate(y_idx2word)}
# produce sequences of indexes from the MRs in the devset
x_dev_enc = token_seq_to_idx_seq(x_dev_seq, x_word2idx, max_input_seq_len)
# produce sequences of indexes from the utterances in the devset
y_dev_1_enc = token_seq_to_idx_seq(y_dev_1, y_word2idx, max_output_seq_len)
# produce sequences of indexes from the utterances in the devset
y_dev_2_enc = token_seq_to_idx_seq(y_dev_2, y_word2idx, max_output_seq_len)
# produce the list of the target labels in the devset
labels_dev = np.concatenate((np.ones(len(y_dev_1_enc)), np.zeros(len(y_dev_2_enc))))
return (np.concatenate((np.array(x_dev_enc), np.array(x_dev_enc))),
np.concatenate((np.array(y_dev_1_enc), np.array(y_dev_2_enc))),
labels_dev)
def load_test_data_for_eval(data_testset, data_model_outputs_test, vocab_size, max_input_seq_len, max_output_seq_len, delex=False):
dataset_name = ''
slot_sep = ''
val_sep = ''
val_sep_closing = False
if '/rest_e2e/' in data_testset or '\\rest_e2e\\' in data_testset:
x_test, _ = read_rest_e2e_dataset_test(data_testset)
y_test = read_predictions(data_model_outputs_test)
dataset_name = 'rest_e2e'
slot_sep = ','
val_sep = '['
val_sep_closing = True
elif '/tv/' in data_testset or '\\tv\\' in data_testset:
x_test, _, y_test = read_tv_dataset_test(data_testset)
if data_model_outputs_test is not None:
y_test = read_predictions(data_model_outputs_test)
dataset_name = 'tv'
slot_sep = ';'
val_sep = '='
elif '/laptop/' in data_testset or '\\laptop\\' in data_testset:
x_test, _, y_test = read_laptop_dataset_test(data_testset)
if data_model_outputs_test is not None:
y_test = read_predictions(data_model_outputs_test)
dataset_name = 'laptop'
slot_sep = ';'
val_sep = '='
else:
raise FileNotFoundError
# parse the utterances into lists of words
y_test = [preprocess_utterance(y) for y in y_test]
#y_test_1 = [preprocess_utterance(y) for y in y_test_1]
#y_test_2 = [preprocess_utterance(y) for y in y_test_2]
# produce sequences of extracted words from the meaning representations (MRs) in the testset
x_test_seq = []
for i, mr in enumerate(x_test):
mr_dict = OrderedDict()
for slot_value in mr.split(slot_sep):
slot, value, _, _ = parse_slot_and_value(slot_value, val_sep, val_sep_closing)
mr_dict[slot] = value
if delex == True:
# delexicalize the MR and the utterance
y_test[i] = delex_sample(mr_dict, y_test[i], dataset=dataset_name)
#y_test_1[i] = delex_sample(mr_dict, y_test_1[i], dataset=dataset_name, utterance_only=True)
#y_test_2[i] = delex_sample(mr_dict, y_test_2[i], dataset=dataset_name)
# convert the dictionary to a list
x_test_seq.append([])
for key, val in mr_dict.items():
if len(val) > 0:
x_test_seq[i].extend([key, val])
else:
x_test_seq[i].append(key)
# load the source vocabulary
with io.open('data/eval_vocab_source.json', 'r', encoding='utf8') as f_x_vocab:
x_vocab = json.load(f_x_vocab)
x_idx2word = [word[0] for word in x_vocab]
x_idx2word.insert(0, '<PADDING>')
x_idx2word.append('<NA>')
x_word2idx = {word: idx for idx, word in enumerate(x_idx2word)}
# load the target vocabulary
with io.open('data/eval_vocab_target.json', 'r', encoding='utf8') as f_y_vocab:
y_vocab = json.load(f_y_vocab)
y_idx2word = [word[0] for word in y_vocab]
y_idx2word.insert(0, '<PADDING>')
y_idx2word.append('<NA>')
y_word2idx = {token: idx for idx, token in enumerate(y_idx2word)}
# produce sequences of indexes from the MRs in the test set
x_test_enc = token_seq_to_idx_seq(x_test_seq, x_word2idx, max_input_seq_len)
# produce sequences of indexes from the utterances in the test set
y_test_enc = token_seq_to_idx_seq(y_test, y_word2idx, max_output_seq_len)
#y_test_1_enc = token_seq_to_idx_seq(y_test_1, y_word2idx, max_output_seq_len)
#y_test_2_enc = token_seq_to_idx_seq(y_test_2, y_word2idx, max_output_seq_len)
# produce the list of the target labels in the test set
labels_test = np.ones(len(y_test_enc))
#labels_test = np.concatenate((np.ones(len(y_test_1_enc)), np.zeros(len(y_test_2_enc))))
return (np.array(x_test_enc),
np.array(y_test_enc),
labels_test,
x_idx2word,
y_idx2word)
#return (np.concatenate((np.array(x_test_enc), np.array(x_test_enc))),
# np.concatenate((np.array(y_test_1_enc), np.array(y_test_2_enc))),
# labels_test,
# x_idx2word,
# y_idx2word)
# ---- AUXILIARY FUNCTIONS ----
def init_training_data(data_trainset, data_devset):
if 'rest_e2e' in data_trainset and 'rest_e2e' in data_devset:
x_train, y_train = read_rest_e2e_dataset_train(data_trainset)
x_dev, y_dev = read_rest_e2e_dataset_dev(data_devset)
dataset_name = 'rest_e2e'
slot_sep = ','
val_sep = '['
val_sep_end = ']'
val_sep_closing = True
elif 'video_game' in data_trainset and 'video_game' in data_devset:
x_train, y_train = read_video_game_dataset_train(data_trainset)
x_dev, y_dev = read_video_game_dataset_dev(data_devset)
dataset_name = 'video_game'
slot_sep = ','
val_sep = '['
val_sep_end = ']'
val_sep_closing = True
elif 'tv' in data_trainset and 'tv' in data_devset:
x_train, y_train, _ = read_tv_dataset_train(data_trainset)
x_dev, y_dev, _ = read_tv_dataset_dev(data_devset)
dataset_name = 'tv'
slot_sep = ';'
val_sep = '='
val_sep_end = None
val_sep_closing = False
elif 'laptop' in data_trainset and 'laptop' in data_devset:
x_train, y_train, _ = read_laptop_dataset_train(data_trainset)
x_dev, y_dev, _ = read_laptop_dataset_dev(data_devset)
dataset_name = 'laptop'
slot_sep = ';'
val_sep = '='
val_sep_end = None
val_sep_closing = False
elif 'hotel' in data_trainset and 'hotel' in data_devset:
x_train, y_train, _ = read_hotel_dataset_train(data_trainset)
x_dev, y_dev, _ = read_hotel_dataset_dev(data_devset)
dataset_name = 'hotel'
slot_sep = ';'
val_sep = '='
val_sep_end = None
val_sep_closing = False
else:
raise ValueError('Unexpected file name or path: {0}, {1}'.format(data_trainset, data_devset))
# Replace commas in values if comma is the slot separator
if slot_sep == ',' and val_sep_end is not None:
x_train = replace_commas_in_mr_values(x_train, val_sep, val_sep_end)
x_dev = replace_commas_in_mr_values(x_dev, val_sep, val_sep_end)
return {
'dataset_name': dataset_name,
'data': (x_train, y_train, x_dev, y_dev),
'separators': (slot_sep, val_sep, val_sep_closing)
}
def init_test_data(data_testset):
if 'rest_e2e' in data_testset:
x_test, y_test = read_rest_e2e_dataset_test(data_testset)
dataset_name = 'rest_e2e'
slot_sep = ','
val_sep = '['
val_sep_end = ']'
val_sep_closing = True
elif 'video_game' in data_testset:
x_test, y_test = read_video_game_dataset_test(data_testset)
dataset_name = 'video_game'
slot_sep = ','
val_sep = '['
val_sep_end = ']'
val_sep_closing = True
elif 'tv' in data_testset:
x_test, y_test, _ = read_tv_dataset_test(data_testset)
dataset_name = 'tv'
slot_sep = ';'
val_sep = '='
val_sep_end = None
val_sep_closing = False
elif 'laptop' in data_testset:
x_test, y_test, _ = read_laptop_dataset_test(data_testset)
dataset_name = 'laptop'
slot_sep = ';'
val_sep = '='
val_sep_end = None
val_sep_closing = False
elif 'hotel' in data_testset:
x_test, y_test, _ = read_hotel_dataset_test(data_testset)
dataset_name = 'hotel'
slot_sep = ';'
val_sep = '='
val_sep_end = None
val_sep_closing = False
else:
raise ValueError('Unexpected file name or path: {0}'.format(data_testset))
# Replace commas in values if comma is the slot separator
if slot_sep == ',' and val_sep_end is not None:
x_test = replace_commas_in_mr_values(x_test, val_sep, val_sep_end)
return {
'dataset_name': dataset_name,
'data': (x_test, y_test),
'separators': (slot_sep, val_sep, val_sep_closing)
}
def read_rest_e2e_dataset_train(data_trainset):
# read the training data from file
df_train = pd.read_csv(data_trainset, header=0, encoding='utf8') # names=['mr', 'ref']
x_train = df_train.mr.tolist()
y_train = df_train.ref.tolist()
return x_train, y_train
def read_rest_e2e_dataset_dev(data_devset):
# read the development data from file
df_dev = pd.read_csv(data_devset, header=0, encoding='utf8') # names=['mr', 'ref']
x_dev = df_dev.mr.tolist()
y_dev = df_dev.ref.tolist()
return x_dev, y_dev
def read_rest_e2e_dataset_test(data_testset):
# read the test data from file
df_test = pd.read_csv(data_testset, header=0, encoding='utf8') # names=['mr', 'ref']
x_test = df_test.iloc[:, 0].tolist()
y_test = []
if df_test.shape[1] > 1:
y_test = df_test.iloc[:, 1].tolist()
return x_test, y_test
def read_video_game_dataset_train(data_trainset):
# read the training data from file
df_train = pd.read_csv(data_trainset, header=0, encoding='utf8') # names=['mr', 'ref']
x_train = df_train.mr.tolist()
y_train = df_train.ref.tolist()
return x_train, y_train
def read_video_game_dataset_dev(data_devset):
# read the development data from file
df_dev = pd.read_csv(data_devset, header=0, encoding='utf8') # names=['mr', 'ref']
x_dev = df_dev.mr.tolist()
y_dev = df_dev.ref.tolist()
# replace commas within values with a placeholder
for i, mr in enumerate(x_dev):
x_dev[i] = preprocess_mr(mr, '(', ';', '=')
return x_dev, y_dev
def read_video_game_dataset_test(data_testset):
# read the test data from file
df_test = pd.read_csv(data_testset, header=0, encoding='utf8') # names=['mr', 'ref']
x_test = df_test.iloc[:, 0].tolist()
y_test = []
if df_test.shape[1] > 1:
y_test = df_test.iloc[:, 1].tolist()
return x_test, y_test
def read_tv_dataset_train(path_to_trainset):
with io.open(path_to_trainset, encoding='utf8') as f_trainset:
# Skip the comment block at the beginning of the file
f_trainset, _ = skip_comment_block(f_trainset, '#')
# read the training data from file
df_train = pd.read_json(f_trainset, encoding='utf8')
x_train = df_train.iloc[:, 0].tolist()
y_train = df_train.iloc[:, 1].tolist()
y_train_alt = df_train.iloc[:, 2].tolist()
# transform the MR to contain the DA type as the first slot
for i, mr in enumerate(x_train):
x_train[i] = preprocess_mr(mr, '(', ';', '=')
# convert plural nouns to "[noun] -s" or "[noun] -es" form
for i, utt in enumerate(y_train):
y_train[i] = replace_plural_nouns(utt)
for i, utt in enumerate(y_train_alt):
y_train_alt[i] = replace_plural_nouns(utt)
return x_train, y_train, y_train_alt
def read_tv_dataset_dev(path_to_devset):
with io.open(path_to_devset, encoding='utf8') as f_devset:
# Skip the comment block at the beginning of the file
f_devset, _ = skip_comment_block(f_devset, '#')
# read the development data from file
df_dev = pd.read_json(f_devset, encoding='utf8')
x_dev = df_dev.iloc[:, 0].tolist()
y_dev = df_dev.iloc[:, 1].tolist()
y_dev_alt = df_dev.iloc[:, 2].tolist()
# transform the MR to contain the DA type as the first slot
for i, mr in enumerate(x_dev):
x_dev[i] = preprocess_mr(mr, '(', ';', '=')
# convert plural nouns to "[noun] -s" or "[noun] -es" form
for i, utt in enumerate(y_dev):
y_dev[i] = replace_plural_nouns(utt)
for i, utt in enumerate(y_dev_alt):
y_dev_alt[i] = replace_plural_nouns(utt)
return x_dev, y_dev, y_dev_alt
def read_tv_dataset_test(path_to_testset):
with io.open(path_to_testset, encoding='utf8') as f_testset:
# Skip the comment block at the beginning of the file
f_testset, _ = skip_comment_block(f_testset, '#')
# read the test data from file
df_test = pd.read_json(f_testset, encoding='utf8')
x_test = df_test.iloc[:, 0].tolist()
y_test = df_test.iloc[:, 1].tolist()
y_test_alt = df_test.iloc[:, 2].tolist()
# transform the MR to contain the DA type as the first slot
for i, mr in enumerate(x_test):
x_test[i] = preprocess_mr(mr, '(', ';', '=')
return x_test, y_test, y_test_alt
def read_laptop_dataset_train(path_to_trainset):
with io.open(path_to_trainset, encoding='utf8') as f_trainset:
# Skip the comment block at the beginning of the file
f_trainset, _ = skip_comment_block(f_trainset, '#')
# read the training data from file
df_train = pd.read_json(f_trainset, encoding='utf8')
x_train = df_train.iloc[:, 0].tolist()
y_train = df_train.iloc[:, 1].tolist()
y_train_alt = df_train.iloc[:, 2].tolist()
# transform the MR to contain the DA type as the first slot
for i, mr in enumerate(x_train):
x_train[i] = preprocess_mr(mr, '(', ';', '=')
return x_train, y_train, y_train_alt
def read_laptop_dataset_dev(path_to_devset):
with io.open(path_to_devset, encoding='utf8') as f_devset:
# Skip the comment block at the beginning of the file
f_devset, _ = skip_comment_block(f_devset, '#')
# read the development data from file
df_dev = pd.read_json(f_devset, encoding='utf8')
x_dev = df_dev.iloc[:, 0].tolist()
y_dev = df_dev.iloc[:, 1].tolist()
y_dev_alt = df_dev.iloc[:, 2].tolist()
# transform the MR to contain the DA type as the first slot
for i, mr in enumerate(x_dev):
x_dev[i] = preprocess_mr(mr, '(', ';', '=')
return x_dev, y_dev, y_dev_alt
def read_laptop_dataset_test(path_to_testset):
with io.open(path_to_testset, encoding='utf8') as f_testset:
# Skip the comment block at the beginning of the file
f_testset, _ = skip_comment_block(f_testset, '#')
# read the test data from file
df_test = pd.read_json(f_testset, encoding='utf8')
x_test = df_test.iloc[:, 0].tolist()
y_test = df_test.iloc[:, 1].tolist()
y_test_alt = df_test.iloc[:, 2].tolist()
# transform the MR to contain the DA type as the first slot
for i, mr in enumerate(x_test):
x_test[i] = preprocess_mr(mr, '(', ';', '=')
return x_test, y_test, y_test_alt
def read_hotel_dataset_train(path_to_trainset):
with io.open(path_to_trainset, encoding='utf8') as f_trainset:
# Skip the comment block at the beginning of the file
f_trainset, _ = skip_comment_block(f_trainset, '#')
# read the training data from file
df_train = pd.read_json(f_trainset, encoding='utf8')
x_train = df_train.iloc[:, 0].tolist()
y_train = df_train.iloc[:, 1].tolist()
y_train_alt = df_train.iloc[:, 2].tolist()
# transform the MR to contain the DA type as the first slot
for i, mr in enumerate(x_train):
x_train[i] = preprocess_mr(mr, '(', ';', '=')
return x_train, y_train, y_train_alt
def read_hotel_dataset_dev(path_to_devset):
with io.open(path_to_devset, encoding='utf8') as f_devset:
# Skip the comment block at the beginning of the file
f_devset, _ = skip_comment_block(f_devset, '#')
# read the development data from file
df_dev = pd.read_json(f_devset, encoding='utf8')
x_dev = df_dev.iloc[:, 0].tolist()
y_dev = df_dev.iloc[:, 1].tolist()
y_dev_alt = df_dev.iloc[:, 2].tolist()
# transform the MR to contain the DA type as the first slot
for i, mr in enumerate(x_dev):
x_dev[i] = preprocess_mr(mr, '(', ';', '=')
return x_dev, y_dev, y_dev_alt
def read_hotel_dataset_test(path_to_testset):
with io.open(path_to_testset, encoding='utf8') as f_testset:
# Skip the comment block at the beginning of the file
f_testset, _ = skip_comment_block(f_testset, '#')
# read the test data from file
df_test = pd.read_json(f_testset, encoding='utf8')
x_test = df_test.iloc[:, 0].tolist()
y_test = df_test.iloc[:, 1].tolist()
y_test_alt = df_test.iloc[:, 2].tolist()
# transform the MR to contain the DA type as the first slot
for i, mr in enumerate(x_test):
x_test[i] = preprocess_mr(mr, '(', ';', '=')
return x_test, y_test, y_test_alt
def read_predictions(path_to_predictions):
# read the test data from file
with io.open(path_to_predictions, encoding='utf8') as f_predictions:
y_pred = f_predictions.readlines()
return y_pred
def skip_comment_block(fd, comment_symbol):
"""Reads the initial lines of the file (represented by the file descriptor) corresponding to a comment block.
All consecutive lines starting with the given symbol are considered to be part of the comment block.
"""
comment_block = ''
line_beg = fd.tell()
line = fd.readline()
while line != '':
if not line.startswith(comment_symbol):
fd.seek(line_beg)
break
comment_block += line
line_beg = fd.tell()
line = fd.readline()
return fd, comment_block
def replace_plural_nouns(utt):
stemmer = WordNetLemmatizer()
pos_tags = nltk.pos_tag(nltk.word_tokenize(utt))
tokens_to_replace = []
tokens_new = []
for token, tag in pos_tags:
#if tag == 'NNS':
if token in ['inches', 'watts']:
tokens_to_replace.append(token)
tokens_new.append(split_plural_noun(token, stemmer))
for token_to_replace, token_new in zip(tokens_to_replace, tokens_new):
utt = utt.replace(token_to_replace, token_new)