-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathnbt.py
1944 lines (1376 loc) · 72.1 KB
/
nbt.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
# -*- coding: utf-8 -*-
#!/usr/local/bin/python
import os
import sys
from copy import deepcopy
import json
import time
import cPickle
import numpy
import tensorflow as tf
import random
import math
import string
import ConfigParser
import types
import codecs
from random import shuffle
from numpy.linalg import norm
from models import model_definition
global_var_asr_count = 1
lp = {}
lp["english"] = u"en"
lp["german"] = u"de"
lp["italian"] = u"it"
lp["russian"] = u"ru"
lp["sh"] = u"sh"
lp["bulgarian"] = u"bg"
lp["polish"] = u"pl"
lp["spanish"] = u"es"
lp["french"] = u"fr"
lp["portuguese"] = u"pt"
lp["swedish"] = u"sv"
lp["dutch"] = u"nl"
def xavier_vector(word, D=300):
"""
Returns a D-dimensional vector for the word.
We hash the word to always get the same vector for the given word.
"""
seed_value = hash_string(word)
numpy.random.seed(seed_value)
neg_value = - math.sqrt(6)/math.sqrt(D)
pos_value = math.sqrt(6)/math.sqrt(D)
rsample = numpy.random.uniform(low=neg_value, high=pos_value, size=(D,))
norm = numpy.linalg.norm(rsample)
rsample_normed = rsample/norm
return rsample_normed
def hash_string(s):
return abs(hash(s)) % (10 ** 8)
def compare_request_lists(list_a, list_b):
if len(list_a) != len(list_b):
return False
list_a.sort()
list_b.sort()
for idx in range(0, len(list_a)):
if list_a[idx] != list_b[idx]:
return False
return True
def evaluate_woz(evaluated_dialogues, dialogue_ontology):
"""
Given a list of (transcription, correct labels, predicted labels), this measures joint goal (as in Matt's paper),
and f-scores, as presented in Shawn's NIPS paper.
Assumes request is always there in the ontology.
"""
print_mode=True
informable_slots = list(set(["food", "area", "price range", "prezzo", "cibo", "essen", "preisklasse", "gegend"]) & set(dialogue_ontology.keys()))
dialogue_count = len(evaluated_dialogues)
if "request" in dialogue_ontology:
req_slots = [str("req_" + x) for x in dialogue_ontology["request"]]
requestables = ["request"]
else:
req_slots = []
requestables = []
# print req_slots
true_positives = {}
false_negatives = {}
false_positives = {}
req_match = 0.0
req_full_turn_count = 0.0
req_acc_total = 0.0 # number of turns which express requestables
req_acc_correct = 0.0
for slot in dialogue_ontology:
true_positives[slot] = 0
false_positives[slot] = 0
false_negatives[slot] = 0
for value in requestables + req_slots + ["request"]:
true_positives[value] = 0
false_positives[value] = 0
false_negatives[value] = 0
correct_turns = 0 # when there is at least one informable, do all of them match?
incorrect_turns = 0 # when there is at least one informable, if any are different.
slot_correct_turns = {}
slot_incorrect_turns = {}
for slot in informable_slots:
slot_correct_turns[slot] = 0.0
slot_incorrect_turns[slot] = 0.0
dialogue_joint_metrics = []
dialogue_req_metrics = []
dialogue_slot_metrics = {}
for slot in informable_slots:
dialogue_slot_metrics[slot] = []
for idx in range(0, dialogue_count):
dialogue = evaluated_dialogues[idx]["dialogue"]
# print dialogue
curr_dialogue_goal_joint_total = 0.0 # how many turns have informables
curr_dialogue_goal_joint_correct = 0.0
curr_dialogue_goal_slot_total = {} # how many turns in current dialogue have specific informables
curr_dialogue_goal_slot_correct = {} # and how many of these are correct
for slot in informable_slots:
curr_dialogue_goal_slot_total[slot] = 0.0
curr_dialogue_goal_slot_correct[slot] = 0.0
creq_tp = 0.0
creq_fn = 0.0
creq_fp = 0.0
# to compute per-dialogue f-score for requestables
for turn in dialogue:
# first update full requestable
req_full_turn_count += 1.0
if requestables:
if compare_request_lists(turn[1]["True State"]["request"], turn[2]["Prediction"]["request"]):
req_match += 1.0
if len(turn[1]["True State"]["request"]) > 0:
req_acc_total += 1.0
if compare_request_lists(turn[1]["True State"]["request"], turn[2]["Prediction"]["request"]):
req_acc_correct += 1.0
# per dialogue requestable metrics
if requestables:
true_requestables = turn[1]["True State"]["request"]
predicted_requestables = turn[2]["Prediction"]["request"]
for each_true_req in true_requestables:
if each_true_req in dialogue_ontology["request"] and each_true_req in predicted_requestables:
true_positives["request"] += 1
creq_tp += 1.0
true_positives["req_" + each_true_req] += 1
elif each_true_req in dialogue_ontology["request"]:
false_negatives["request"] += 1
false_negatives["req_" + each_true_req] += 1
creq_fn += 1.0
# print "FN:", turn[0], "---", true_requestables, "----", predicted_requestables
for each_predicted_req in predicted_requestables:
# ignore matches, already counted, now need just negatives:
if each_predicted_req not in true_requestables:
false_positives["request"] += 1
false_positives["req_" + each_predicted_req] += 1
creq_fp += 1.0
# print "-- FP:", turn[0], "---", true_requestables, "----", predicted_requestables
# print turn
inf_present = {}
inf_correct = {}
for slot in informable_slots:
inf_present[slot] = False
inf_correct[slot] = True
informable_present = False
informable_correct = True
for slot in informable_slots:
try:
true_value = turn[1]["True State"][slot]
predicted_value = turn[2]["Prediction"][slot]
except:
print "PROBLEM WITH", turn, "slot:", slot, "inf slots", informable_slots
if true_value != "none":
informable_present = True
inf_present[slot] = True
if true_value == predicted_value: # either match or none, so not incorrect
if true_value != "none":
true_positives[slot] += 1
else:
if true_value == "none":
false_positives[slot] += 1
elif predicted_value == "none":
false_negatives[slot] += 1
else:
# spoke to Shawn - he does this as false negatives for now - need to think about how we evaluate it properly.
false_negatives[slot] += 1
informable_correct = False
inf_correct[slot] = False
if informable_present:
curr_dialogue_goal_joint_total += 1.0
if informable_correct:
correct_turns += 1
curr_dialogue_goal_joint_correct += 1.0
else:
incorrect_turns += 1
for slot in informable_slots:
if inf_present[slot]:
curr_dialogue_goal_slot_total[slot] += 1.0
if inf_correct[slot]:
slot_correct_turns[slot] += 1.0
curr_dialogue_goal_slot_correct[slot] += 1.0
else:
slot_incorrect_turns[slot] += 1.0
# current dialogue requestables
if creq_tp + creq_fp > 0.0:
creq_precision = creq_tp / (creq_tp + creq_fp)
else:
creq_precision = 0.0
if creq_tp + creq_fn > 0.0:
creq_recall = creq_tp / (creq_tp + creq_fn)
else:
creq_recall = 0.0
if creq_precision + creq_recall == 0:
if creq_tp == 0 and creq_fn == 0 and creq_fn == 0:
# no requestables expressed, special value
creq_fscore = -1.0
else:
creq_fscore = 0.0 # none correct but some exist
else:
creq_fscore = (2 * creq_precision * creq_recall) / (creq_precision + creq_recall)
dialogue_req_metrics.append(creq_fscore)
# and current dialogue informables:
for slot in informable_slots:
if curr_dialogue_goal_slot_total[slot] > 0:
dialogue_slot_metrics[slot].append(float(curr_dialogue_goal_slot_correct[slot]) / curr_dialogue_goal_slot_total[slot])
else:
dialogue_slot_metrics[slot].append(-1.0)
if informable_slots:
if curr_dialogue_goal_joint_total > 0:
current_dialogue_joint_metric = float(curr_dialogue_goal_joint_correct) / curr_dialogue_goal_joint_total
dialogue_joint_metrics.append(current_dialogue_joint_metric)
else:
# should not ever happen when all slots are used, but for validation we might not have i.e. area mentioned
dialogue_joint_metrics.append(-1.0)
if informable_slots:
goal_joint_total = float(correct_turns) / float(correct_turns + incorrect_turns)
slot_gj = {}
total_true_positives = 0
total_false_negatives = 0
total_false_positives = 0
precision = {}
recall = {}
fscore = {}
# FSCORE for each requestable slot:
if requestables:
add_req = ["request"] + req_slots
else:
add_req = []
for slot in informable_slots + add_req:
if slot not in ["request"] and slot not in req_slots:
total_true_positives += true_positives[slot]
total_false_positives += false_positives[slot]
total_false_negatives += false_negatives[slot]
precision_denominator = (true_positives[slot] + false_positives[slot])
if precision_denominator != 0:
precision[slot] = float(true_positives[slot]) / precision_denominator
else:
precision[slot] = 0
recall_denominator = (true_positives[slot] + false_negatives[slot])
if recall_denominator != 0:
recall[slot] = float(true_positives[slot]) / recall_denominator
else:
recall[slot] = 0
if precision[slot] + recall[slot] != 0:
fscore[slot] = (2 * precision[slot] * recall[slot]) / (precision[slot] + recall[slot])
print "REQ - slot", slot, round(precision[slot], 3), round(recall[slot], 3), round(fscore[slot], 3)
else:
fscore[slot] = 0
total_count_curr = true_positives[slot] + false_negatives[slot] + false_positives[slot]
#if "req" in slot:
#if slot in ["area", "food", "price range", "request"]:
#print "Slot:", slot, "Count:", total_count_curr, true_positives[slot], false_positives[slot], false_negatives[slot], "[Precision, Recall, Fscore]=", round(precision[slot], 2), round(recall[slot], 2), round(fscore[slot], 2)
#print "Slot:", slot, "TP:", true_positives[slot], "FN:", false_negatives[slot], "FP:", false_positives[slot]
if requestables:
requested_accuracy_all = req_match / req_full_turn_count
if req_acc_total != 0:
requested_accuracy_exist = req_acc_correct / req_acc_total
else:
requested_accuracy_exist = 1.0
slot_gj["request"] = round(requested_accuracy_exist, 3)
#slot_gj["requestf"] = round(fscore["request"], 3)
for slot in informable_slots:
slot_gj[slot] = round(float(slot_correct_turns[slot]) / float(slot_correct_turns[slot] + slot_incorrect_turns[slot]), 3)
# NIKOLA TODO: will be useful for goal joint
if len(informable_slots) == 3:
# print "\n\nGoal Joint: " + str(round(goal_joint_total, 3)) + "\n"
slot_gj["joint"] = round(goal_joint_total, 3)
if "request" in slot_gj:
del slot_gj["request"]
return slot_gj
def process_turn_hyp(transcription, language):
"""
Returns the clean (i.e. handling interpunction signs) string for the given language.
"""
exclude = set(string.punctuation)
exclude.remove("'")
transcription = ''.join(ch for ch in transcription if ch not in exclude)
transcription = transcription.lower()
transcription = transcription.replace(u"’", "'")
transcription = transcription.replace(u"‘", "'")
transcription = transcription.replace("don't", "dont")
if language == "it" or language == "italian":# or language == "en" or language == "english":
transcription = transcription.replace("'", " ")
if language == "en" or language == "english":# or language == "en" or language == "english":
transcription = transcription.replace("'", "")
return transcription
def process_woz_dialogue(woz_dialogue,language,override_en_ontology):
"""
Returns a list of (tuple, belief_state) for each turn in the dialogue.
"""
# initial belief state
# belief state to be given at each turn
if language == "english" or language == "en" or override_en_ontology:
null_bs = {}
null_bs["food"] = "none"
null_bs["price range"] = "none"
null_bs["area"] = "none"
null_bs["request"] = []
informable_slots = ["food", "price range", "area"]
pure_requestables = ["address", "phone", "postcode"]
elif (language == "italian" or language == "it"):
null_bs = {}
null_bs["area"] = "none"
null_bs["cibo"] = "none"
null_bs["prezzo"] = "none"
null_bs["request"] = []
informable_slots = ["cibo", "prezzo", "area"]
pure_requestables = ["codice postale", "telefono", "indirizzo"]
elif (language == "german" or language == "de"):
null_bs = {}
null_bs["gegend"] = "none"
null_bs["essen"] = "none"
null_bs["preisklasse"] = "none"
null_bs["request"] = []
informable_slots = ["essen", "preisklasse", "gegend"]
pure_requestables = ["postleitzahl", "telefon", "adresse"]
prev_belief_state = deepcopy(null_bs)
dialogue_representation = []
# user talks first, so there is no requested DA initially.
current_req = [""]
current_conf_slot = [""]
current_conf_value = [""]
lp = {}
lp["german"] = u"de_"
lp["italian"] = u"it_"
for idx, turn in enumerate(woz_dialogue):
current_DA = turn["system_acts"]
current_req = []
current_conf_slot = []
current_conf_value = []
for each_da in current_DA:
if each_da in informable_slots:
current_req.append(each_da)
elif each_da in pure_requestables:
current_conf_slot.append("request")
current_conf_value.append(each_da)
else:
if type(each_da) is list:
current_conf_slot.append(each_da[0])
current_conf_value.append(each_da[1])
if not current_req:
current_req = [""]
if not current_conf_slot:
current_conf_slot = [""]
current_conf_value = [""]
current_transcription = turn["transcript"]
current_transcription = process_turn_hyp(current_transcription, language)
read_asr = turn["asr"]
current_asr = []
for (hyp, score) in read_asr:
current_hyp = process_turn_hyp(hyp, language)
current_asr.append((current_hyp, score))
old_trans = current_transcription
exclude = set(string.punctuation)
exclude.remove("'")
current_transcription = ''.join(ch for ch in current_transcription if ch not in exclude)
current_transcription = current_transcription.lower()
current_labels = turn["turn_label"]
current_bs = deepcopy(prev_belief_state)
#print "=====", prev_belief_state
if "request" in prev_belief_state:
del prev_belief_state["request"]
current_bs["request"] = [] # reset requestables at each turn
for label in current_labels:
(c_slot, c_value) = label
if c_slot in informable_slots:
current_bs[c_slot] = c_value
elif c_slot == "request":
current_bs["request"].append(c_value)
curr_lab_dict = {}
for x in current_labels:
if x[0] != "request":
curr_lab_dict[x[0]] = x[1]
dialogue_representation.append(((current_transcription, current_asr), current_req, current_conf_slot, current_conf_value, deepcopy(current_bs), deepcopy(prev_belief_state)))
#print "====", current_transcription, "current bs", current_bs, "past bs", prev_belief_state, "this turn update", curr_lab_dict
prev_belief_state = deepcopy(current_bs)
return dialogue_representation
def load_woz_data(file_path, language, percentage=1.0,override_en_ontology=False):
"""
This method loads WOZ dataset as a collection of utterances.
Testing means load everything, no split.
"""
woz_json = json.load(codecs.open(file_path, "r", "utf-8"))
dialogues = []
training_turns = []
dialogue_count = len(woz_json)
percentage = float(percentage)
dialogue_count = int(percentage * float(dialogue_count))
if dialogue_count != 200:
print "Percentage is:", percentage, "so loading:", dialogue_count
for idx in range(0, dialogue_count):
current_dialogue = process_woz_dialogue(woz_json[idx]["dialogue"], language, override_en_ontology)
dialogues.append(current_dialogue)
for turn_idx, turn in enumerate(current_dialogue):
if turn_idx == 0:
prev_turn_label = []
else:
prev_turn_label = current_label
current_label = []
for req_slot in turn[4]["request"]:
current_label.append(("request", req_slot))
#print "adding reqslot:", req_slot
# this now includes requests:
for inf_slot in turn[4]:
# print (inf_slot, turn[5][inf_slot])
if inf_slot != "request":
current_label.append((inf_slot, turn[4][inf_slot]))
# if inf_slot == "request":
# print "!!!!!", inf_slot, turn[5][inf_slot]
transcription_and_asr = turn[0]
current_utterance = (transcription_and_asr, turn[1], turn[2], turn[3], current_label, turn[5]) #turn [5] is the past belief state
#print "$$$$", current_utterance
training_turns.append(current_utterance)
# print "Number of utterances in", file_path, "is:", len(training_turns)
return (dialogues, training_turns)
def track_woz_data(dialogues, model_variables, word_vectors, dialogue_ontology, sessions):
"""
This method evaluates the WOZ dialogues.
"""
evaluated_dialogues = []
list_of_belief_states = []
dialogue_count = len(dialogues)
#print "DIALOGUE COUNT: ", dialogue_count
for idx in range(0, dialogue_count):
if idx % 100 == 0 and (dialogue_count == 400): # progress for test
print idx, "/", dialogue_count, "done."
evaluated_dialogue, belief_states = track_dialogue_woz(model_variables, word_vectors, dialogue_ontology, dialogues[idx], sessions)
evaluated_dialogues.append(evaluated_dialogue)
list_of_belief_states.append(belief_states)
dialogue_count = len(evaluated_dialogues)
indexed_dialogues = []
for d_idx in range(0, dialogue_count):
new_dialogue = {}
new_dialogue["dialogue_idx"] = d_idx
new_dialogue["dialogue"] = evaluated_dialogues[d_idx]
indexed_dialogues.append(new_dialogue)
return indexed_dialogues, list_of_belief_states
def track_dialogue_woz(model_variables, word_vectors, dialogue_ontology, woz_dialogue, sessions):
"""
This produces a list of belief states predicted for the given WOZ dialogue.
"""
prev_belief_states = {}
belief_states = {} # for each slot, a list of numpy arrays.
turn_count = len(woz_dialogue)
#print "Turn count:", turn_count
slots_to_track = list(set(dialogue_ontology.keys()) & set(sessions.keys()) )
for slot in slots_to_track:
belief_states[slot] = {}
if slot != "request":
value_count = len(dialogue_ontology[slot]) + 1
prev_belief_states[slot] = numpy.zeros((value_count,), dtype="float32")
predictions_for_dialogue = []
# to be able to combine predictions, we must also return the belief states for each turn. So for each turn, a dictionary indexed by slot values which points to the distribution.
list_of_belief_states = []
#print woz_dialogue
for idx, trans_and_req_and_label_and_currlabel in enumerate(woz_dialogue):
list_of_belief_states.append({})
current_bs = {}
for slot in slots_to_track:
if type(model_variables) is dict:
mx = model_variables[slot]
else:
mx = model_variables
#print trans_and_req_and_label_and_currlabel
(transcription_and_asr, req_slot, conf_slot, conf_value, label, prev_belief_state) = trans_and_req_and_label_and_currlabel
if idx == 0 or slot == "request":
# this should put empty belief state
example = [(transcription_and_asr, req_slot, conf_slot, conf_value, prev_belief_state)]
else:
# and this has the previous prediction, the one we just made in the previous iteration. We do not want to use the right one, the one used for training.
example = [(transcription_and_asr, req_slot, conf_slot, conf_value, prev_bs)]
#print example
transcription = transcription_and_asr[0]
asr = transcription_and_asr[1]
if slot == "request":
updated_belief_state = sliding_window_over_utterance(sessions[slot], example, word_vectors, dialogue_ontology, mx, slot, print_mode=False)
# updated_belief_state[updated_belief_state < 0.5] = 0
list_of_belief_states[idx]["request"] = updated_belief_state
else:
updated_belief_state = sliding_window_over_utterance(sessions[slot], example, word_vectors, dialogue_ontology, mx, slot, print_mode=False)
#updated_belief_state = softmax(updated_belief_state)
#updated_belief_state = update_belief_state(prev_belief_states[slot], new_belief_state)
prev_belief_states[slot] = updated_belief_state
list_of_belief_states[idx][slot] = updated_belief_state
for idx_value, value in enumerate(dialogue_ontology[slot]):
if slot in "request":
current_bs[slot] = print_belief_state_woz_requestables(dialogue_ontology[slot], updated_belief_state, threshold=0.5)
else:
current_bs[slot] = print_belief_state_woz_informable(dialogue_ontology[slot], updated_belief_state, threshold=0.01) # swap to 0.001 Nikola
# print idx, slot, current_bs[slot], current_bs
prev_bs = deepcopy(current_bs)
trans_plus_sys = "User: " + transcription
# + req_slot, conf_slot, conf_value
if req_slot[0] != "":
trans_plus_sys += " System Request: " + str(req_slot)
if conf_slot[0] != "":
trans_plus_sys += " System Confirm: " + str(conf_slot) + " " + str(conf_value)
trans_plus_sys += " ASR: " + str(asr)
predictions_for_dialogue.append((trans_plus_sys, {"True State": label}, {"Prediction": current_bs}))
return predictions_for_dialogue, list_of_belief_states
def print_belief_state_woz_informable(curr_values, distribution,threshold):
"""
Returns the top one if it is above threshold.
"""
max_value = "none"
max_score = 0.0
total_value = 0.0
for idx, value in enumerate(curr_values):
total_value += distribution[idx]
if distribution[idx] >= threshold:
if distribution[idx] >= max_score:
max_value = value
max_score = distribution[idx]
if max_score >= (1.0 - total_value):
return max_value
else:
return "none"
def print_belief_state_woz_requestables(curr_values, distribution, threshold):
"""
Returns the top one if it is above threshold.
"""
requested_slots = []
# now we just print to JSON file:
for idx, value in enumerate(curr_values):
if distribution[idx] >= threshold:
requested_slots.append(value)
return requested_slots
def generate_data(utterances, word_vectors, dialogue_ontology, target_slot):
"""
Generates a data representation we can subsequently use.
Let's say negative requests are now - those utterances which express no requestables.
"""
# each list element is a tuple with features for that utterance (unigram, bigram, trigram).
feature_vectors = extract_feature_vectors(utterances, word_vectors)
# indexed by slot, these two dictionaries contain lists of positive and negative examples
# for training each slot. Each list element is (utterance_id, slot_id, value_id)
positive_examples = {}
negative_examples = {}
list_of_slots = [target_slot]
list_of_slots = dialogue_ontology.keys() #["food", "area", "price range", "request"]
for slot_idx, slot in enumerate(list_of_slots):
positive_examples[slot] = []
negative_examples[slot] = []
for utterance_idx, utterance in enumerate(utterances):
slot_expressed_in_utterance = False
# utterance[4] is the current label
# utterance[5] is the previous one
for (slotA, valueA) in utterance[4]:
if slotA == slot and (valueA != "none" and valueA != []):
slot_expressed_in_utterance = True # if this is True, no negative examples for softmax.
#if slot == "request":
# print slotA, valueA, utterance, utterance[4]
if slot != "request":
for value_idx, value in enumerate(dialogue_ontology[slot]):
if (slot, value) in utterance[4]: # utterances are ((trans, asr), sys_req_act, sys_conf, labels)
positive_examples[slot].append((utterance_idx, utterance, value_idx))
#print "POS:", utterance_idx, utterance, value_idx, value
else:
if not slot_expressed_in_utterance:
negative_examples[slot].append((utterance_idx, utterance, value_idx))
#print "NEG:", utterance_idx, utterance, value_idx, value
elif slot == "request":
if not slot_expressed_in_utterance:
negative_examples[slot].append((utterance_idx, utterance, []))
# print utterance[0][0], utterance[4]
else:
values_expressed = []
for value_idx, value in enumerate(dialogue_ontology[slot]):
if (slot, value) in utterance[4]: # utterances are ((trans, asr), sys_req_act, sys_conf, labels)
values_expressed.append(value_idx)
positive_examples[slot].append((utterance_idx, utterance, values_expressed))
# print utterances[utterance_idx], "---", values_expressed
#positive_examples[slot] = set(positive_examples[slot])
#negative_examples[slot] = set(negative_examples[slot])
return feature_vectors, positive_examples, negative_examples
def binary_mask(example, requestable_count):
"""
takes a list, i.e. 2,3,4, and if req count is 8, returns: 00111000
"""
zeros = numpy.zeros((requestable_count,), dtype=numpy.float32)
for x in example:
zeros[x] = 1
return zeros
def delexicalise_utterance_values(utterance, target_slot, target_values):
"""
Takes a list of words which represent the current utterance, the loaded vectors, finds all occurrences of both slot name and slot value,
and then returns the updated vector with "delexicalised tag" in them.
"""
if type(utterance) is list:
utterance = " ".join(utterance)
if target_slot == "request":
value_count = len(target_values)
else:
value_count = len(target_values)+1
delexicalised_vector = numpy.zeros((value_count,), dtype="float32")
for idx, target_value in enumerate(target_values):
if " " + target_value + " " in utterance:
delexicalised_vector[idx] = 1.0
return delexicalised_vector
def generate_examples(target_slot, feature_vectors, word_vectors, dialogue_ontology,
positive_examples, negative_examples, positive_count=None, negative_count=None):
"""
This method returns a minibatch of positive_count examples followed by negative_count examples.
If these two are not set, it creates the full dataset (used for validation and test).
It returns: (features_unigram, features_bigram, features_trigram, features_slot,
features_values, y_labels) - all we need to pass to train.
"""
# total number of positive and negative examples.
pos_example_count = len(positive_examples[target_slot])
neg_example_count = len(negative_examples[target_slot])
if target_slot != "request":
label_count = len(dialogue_ontology[target_slot]) + 1 # NONE
else:
label_count = len(dialogue_ontology[target_slot])
doing_validation = False
# for validation?
if positive_count is None:
positive_count = pos_example_count
doing_validation = True
if negative_count is None:
negative_count = neg_example_count
doing_validation = True
if pos_example_count == 0 or positive_count == 0 or negative_count == 0 or neg_example_count == 0:
print "#### SKIPPING (NO DATA): ", target_slot, pos_example_count, positive_count, neg_example_count, negative_count
return None
positive_indices = []
negative_indices = []
if positive_count > 0:
positive_indices = numpy.random.choice(pos_example_count, positive_count)
else:
print target_slot, positive_count, negative_count
if negative_count > 0:
negative_indices = numpy.random.choice(neg_example_count, negative_count)
examples = []
labels = []
prev_labels = []
for idx in positive_indices:
examples.append(positive_examples[target_slot][idx])
if negative_count > 0:
for idx in negative_indices:
examples.append(negative_examples[target_slot][idx])
value_count = len(dialogue_ontology[target_slot])
# each element of this array is (xs_unigram, xs_bigram, xs_trigram, fv_slot, fv_value):
features_requested_slots = []
features_confirm_slots = []
features_confirm_values = []
features_slot = []
features_values = []
features_full = []
features_delex = []
features_previous_state = []
# feature vector of the used slot:
slot_fv = word_vectors[unicode(target_slot)]
# now go through all examples (positive followed by negative).
for idx_example, example in enumerate(examples):
(utterance_idx, utterance, value_idx) = example
utterance_fv = feature_vectors[utterance_idx]
# prev belief state is in utterance[5]
prev_belief_state = utterance[5]
if idx_example < positive_count:
if target_slot != "request":
labels.append(value_idx) # includes dontcare
else:
labels.append(binary_mask(value_idx, len(dialogue_ontology["request"])))
else:
if target_slot != "request":
labels.append(value_count) # NONE - for this we need to make sure to not include utterances which express this slot
else:
labels.append([]) #wont ever use this
# handling of previous labels:
if target_slot != "request":
prev_labels.append(prev_belief_state[target_slot])
# for now, we just deal with the utterance, and not with WOZ data.
# TODO: need to get a series of delexicalised vectors, one for each value.
delex_features = delexicalise_utterance_values(utterance[0][0], target_slot, dialogue_ontology[target_slot])
features_full.append(utterance_fv[0])
features_requested_slots.append(utterance_fv[1])
features_confirm_slots.append(utterance_fv[2])
features_confirm_values.append(utterance_fv[3])
features_delex.append(delex_features)
prev_belief_state_vector = numpy.zeros((label_count,), dtype="float32")
if target_slot != "request":
prev_value = prev_belief_state[target_slot]
if prev_value == "none" or prev_value not in dialogue_ontology[target_slot]:
prev_belief_state_vector[label_count-1] = 1
else:
prev_belief_state_vector[dialogue_ontology[target_slot].index(prev_value)] = 1
features_previous_state.append(prev_belief_state_vector)
features_requested_slots = numpy.array(features_requested_slots)
features_confirm_slots = numpy.array(features_confirm_slots)
features_confirm_values = numpy.array(features_confirm_values)
features_full = numpy.array(features_full)
features_delex = numpy.array(features_delex)
features_previous_state = numpy.array(features_previous_state)
y_labels = numpy.zeros((positive_count + negative_count, label_count), dtype="float32")
for idx in range(0, positive_count):
if target_slot != "request":
y_labels[idx, labels[idx]] = 1
else:
y_labels[idx, :] = labels[idx]
if target_slot != "request":
y_labels[positive_count:, label_count-1] = 1# NONE, 0-indexing
return (features_full, features_requested_slots, features_confirm_slots, \
features_confirm_values, features_delex, y_labels, features_previous_state)
def evaluate_model(dataset_name, sess, model_variables, data, target_slot, utterances, dialogue_ontology, \
positive_examples, negative_examples, print_mode=False, epoch_id=""):