/
test.py
1962 lines (1622 loc) 路 66.1 KB
/
test.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 copy
import itertools
import os
import logging
import structlog
from pathlib import Path
import numpy as np
from collections import defaultdict, namedtuple
from tqdm import tqdm
from typing import (
Iterable,
Iterator,
Tuple,
List,
Set,
Optional,
Text,
Union,
Dict,
Any,
NamedTuple,
TYPE_CHECKING,
)
from rasa import telemetry
from rasa.core.agent import Agent
from rasa.core.channels import UserMessage
from rasa.core.processor import MessageProcessor
from rasa.plugin import plugin_manager
from rasa.shared.nlu.training_data.training_data import TrainingData
from rasa.utils.common import TempDirectoryPath, get_temp_dir_name
import rasa.shared.utils.io
import rasa.utils.plotting as plot_utils
import rasa.utils.io as io_utils
from rasa.constants import TEST_DATA_FILE, TRAIN_DATA_FILE, NLG_DATA_FILE
import rasa.nlu.classifiers.fallback_classifier
from rasa.nlu.constants import (
RESPONSE_SELECTOR_DEFAULT_INTENT,
RESPONSE_SELECTOR_PROPERTY_NAME,
RESPONSE_SELECTOR_PREDICTION_KEY,
TOKENS_NAMES,
ENTITY_ATTRIBUTE_CONFIDENCE_TYPE,
ENTITY_ATTRIBUTE_CONFIDENCE_ROLE,
ENTITY_ATTRIBUTE_CONFIDENCE_GROUP,
RESPONSE_SELECTOR_RETRIEVAL_INTENTS,
)
from rasa.shared.nlu.constants import (
TEXT,
INTENT,
INTENT_RESPONSE_KEY,
ENTITIES,
EXTRACTOR,
PRETRAINED_EXTRACTORS,
ENTITY_ATTRIBUTE_TYPE,
ENTITY_ATTRIBUTE_GROUP,
ENTITY_ATTRIBUTE_ROLE,
NO_ENTITY_TAG,
INTENT_NAME_KEY,
PREDICTED_CONFIDENCE_KEY,
)
from rasa.nlu.classifiers import fallback_classifier
from rasa.nlu.tokenizers.tokenizer import Token
from rasa.shared.importers.importer import TrainingDataImporter
from rasa.shared.nlu.training_data.formats.rasa_yaml import RasaYAMLWriter
if TYPE_CHECKING:
from typing_extensions import TypedDict
EntityPrediction = TypedDict(
"EntityPrediction",
{
"text": Text,
"entities": List[Dict[Text, Any]],
"predicted_entities": List[Dict[Text, Any]],
},
)
logger = logging.getLogger(__name__)
structlogger = structlog.get_logger()
# Exclude 'EntitySynonymMapper' and 'ResponseSelector' as their super class
# performs entity extraction but those two classifiers don't
ENTITY_PROCESSORS = {"EntitySynonymMapper", "ResponseSelector"}
EXTRACTORS_WITH_CONFIDENCES = {"CRFEntityExtractor", "DIETClassifier"}
class CVEvaluationResult(NamedTuple):
"""Stores NLU cross-validation results."""
train: Dict
test: Dict
evaluation: Dict
NO_ENTITY = "no_entity"
IntentEvaluationResult = namedtuple(
"IntentEvaluationResult", "intent_target intent_prediction message confidence"
)
ResponseSelectionEvaluationResult = namedtuple(
"ResponseSelectionEvaluationResult",
"intent_response_key_target intent_response_key_prediction message confidence",
)
EntityEvaluationResult = namedtuple(
"EntityEvaluationResult", "entity_targets entity_predictions tokens message"
)
IntentMetrics = Dict[Text, List[float]]
EntityMetrics = Dict[Text, Dict[Text, List[float]]]
ResponseSelectionMetrics = Dict[Text, List[float]]
def log_evaluation_table(
report: Text, precision: float, f1: float, accuracy: float
) -> None: # pragma: no cover
"""Log the sklearn evaluation metrics."""
logger.info(f"F1-Score: {f1}")
logger.info(f"Precision: {precision}")
logger.info(f"Accuracy: {accuracy}")
logger.info(f"Classification report: \n{report}")
def remove_empty_intent_examples(
intent_results: List[IntentEvaluationResult],
) -> List[IntentEvaluationResult]:
"""Remove those examples without an intent.
Args:
intent_results: intent evaluation results
Returns: intent evaluation results
"""
filtered = []
for r in intent_results:
# substitute None values with empty string
# to enable sklearn evaluation
if r.intent_prediction is None:
r = r._replace(intent_prediction="")
if r.intent_target != "" and r.intent_target is not None:
filtered.append(r)
return filtered
def remove_empty_response_examples(
response_results: List[ResponseSelectionEvaluationResult],
) -> List[ResponseSelectionEvaluationResult]:
"""Remove those examples without a response.
Args:
response_results: response selection evaluation results
Returns:
Response selection evaluation results
"""
filtered = []
for r in response_results:
# substitute None values with empty string
# to enable sklearn evaluation
if r.intent_response_key_prediction is None:
r = r._replace(intent_response_key_prediction="")
if r.confidence is None:
# This might happen if response selector training data is present but
# no response selector is part of the model
r = r._replace(confidence=0.0)
if r.intent_response_key_target:
filtered.append(r)
return filtered
def drop_intents_below_freq(
training_data: TrainingData, cutoff: int = 5
) -> TrainingData:
"""Remove intent groups with less than cutoff instances.
Args:
training_data: training data
cutoff: threshold
Returns: updated training data
"""
logger.debug(
"Raw data intent examples: {}".format(len(training_data.intent_examples))
)
examples_per_intent = training_data.number_of_examples_per_intent
return training_data.filter_training_examples(
lambda ex: examples_per_intent.get(ex.get(INTENT), 0) >= cutoff
)
def write_intent_successes(
intent_results: List[IntentEvaluationResult], successes_filename: Text
) -> None:
"""Write successful intent predictions to a file.
Args:
intent_results: intent evaluation result
successes_filename: filename of file to save successful predictions to
"""
successes = [
{
"text": r.message,
"intent": r.intent_target,
"intent_prediction": {
INTENT_NAME_KEY: r.intent_prediction,
"confidence": r.confidence,
},
}
for r in intent_results
if r.intent_target == r.intent_prediction
]
if successes:
rasa.shared.utils.io.dump_obj_as_json_to_file(successes_filename, successes)
logger.info(f"Successful intent predictions saved to {successes_filename}.")
logger.debug(f"\n\nSuccessfully predicted the following intents: \n{successes}")
else:
logger.info("No successful intent predictions found.")
def _write_errors(errors: List[Dict], errors_filename: Text, error_type: Text) -> None:
"""Write incorrect intent predictions to a file.
Args:
errors: Serializable prediction errors.
errors_filename: filename of file to save incorrect predictions to
error_type: NLU entity which was evaluated (e.g. `intent` or `entity`).
"""
if errors:
rasa.shared.utils.io.dump_obj_as_json_to_file(errors_filename, errors)
logger.info(f"Incorrect {error_type} predictions saved to {errors_filename}.")
logger.debug(
f"\n\nThese {error_type} examples could not be classified "
f"correctly: \n{errors}"
)
else:
logger.info(f"Every {error_type} was predicted correctly by the model.")
def _get_intent_errors(intent_results: List[IntentEvaluationResult]) -> List[Dict]:
return [
{
"text": r.message,
"intent": r.intent_target,
"intent_prediction": {
INTENT_NAME_KEY: r.intent_prediction,
"confidence": r.confidence,
},
}
for r in intent_results
if r.intent_target != r.intent_prediction
]
def write_response_successes(
response_results: List[ResponseSelectionEvaluationResult], successes_filename: Text
) -> None:
"""Write successful response selection predictions to a file.
Args:
response_results: response selection evaluation result
successes_filename: filename of file to save successful predictions to
"""
successes = [
{
"text": r.message,
"intent_response_key_target": r.intent_response_key_target,
"intent_response_key_prediction": {
"name": r.intent_response_key_prediction,
"confidence": r.confidence,
},
}
for r in response_results
if r.intent_response_key_prediction == r.intent_response_key_target
]
if successes:
rasa.shared.utils.io.dump_obj_as_json_to_file(successes_filename, successes)
logger.info(f"Successful response predictions saved to {successes_filename}.")
structlogger.debug("test.write.response", successes=copy.deepcopy(successes))
else:
logger.info("No successful response predictions found.")
def _response_errors(
response_results: List[ResponseSelectionEvaluationResult],
) -> List[Dict]:
"""Write incorrect response selection predictions to a file.
Args:
response_results: response selection evaluation result
Returns:
Serializable prediction errors.
"""
return [
{
"text": r.message,
"intent_response_key_target": r.intent_response_key_target,
"intent_response_key_prediction": {
"name": r.intent_response_key_prediction,
"confidence": r.confidence,
},
}
for r in response_results
if r.intent_response_key_prediction != r.intent_response_key_target
]
def plot_attribute_confidences(
results: Union[
List[IntentEvaluationResult], List[ResponseSelectionEvaluationResult]
],
hist_filename: Optional[Text],
target_key: Text,
prediction_key: Text,
title: Text,
) -> None:
"""Create histogram of confidence distribution.
Args:
results: evaluation results
hist_filename: filename to save plot to
target_key: key of target in results
prediction_key: key of predictions in results
title: title of plot
"""
pos_hist = [
r.confidence
for r in results
if getattr(r, target_key) == getattr(r, prediction_key)
]
neg_hist = [
r.confidence
for r in results
if getattr(r, target_key) != getattr(r, prediction_key)
]
plot_utils.plot_paired_histogram([pos_hist, neg_hist], title, hist_filename)
def plot_entity_confidences(
merged_targets: List[Text],
merged_predictions: List[Text],
merged_confidences: List[float],
hist_filename: Text,
title: Text,
) -> None:
"""Creates histogram of confidence distribution.
Args:
merged_targets: Entity labels.
merged_predictions: Predicted entities.
merged_confidences: Confidence scores of predictions.
hist_filename: filename to save plot to
title: title of plot
"""
pos_hist = [
confidence
for target, prediction, confidence in zip(
merged_targets, merged_predictions, merged_confidences
)
if target != NO_ENTITY and target == prediction
]
neg_hist = [
confidence
for target, prediction, confidence in zip(
merged_targets, merged_predictions, merged_confidences
)
if prediction not in (NO_ENTITY, target)
]
plot_utils.plot_paired_histogram([pos_hist, neg_hist], title, hist_filename)
def evaluate_response_selections(
response_selection_results: List[ResponseSelectionEvaluationResult],
output_directory: Optional[Text],
successes: bool,
errors: bool,
disable_plotting: bool,
report_as_dict: Optional[bool] = None,
) -> Dict: # pragma: no cover
"""Creates summary statistics for response selection.
Only considers those examples with a set response.
Others are filtered out. Returns a dictionary of containing the
evaluation result.
Args:
response_selection_results: response selection evaluation results
output_directory: directory to store files to
successes: if True success are written down to disk
errors: if True errors are written down to disk
disable_plotting: if True no plots are created
report_as_dict: `True` if the evaluation report should be returned as `dict`.
If `False` the report is returned in a human-readable text format. If `None`
`report_as_dict` is considered as `True` in case an `output_directory` is
given.
Returns: dictionary with evaluation results
"""
# remove empty response targets
num_examples = len(response_selection_results)
response_selection_results = remove_empty_response_examples(
response_selection_results
)
logger.info(
f"Response Selection Evaluation: Only considering those "
f"{len(response_selection_results)} examples that have a defined response out "
f"of {num_examples} examples."
)
(
target_intent_response_keys,
predicted_intent_response_keys,
) = _targets_predictions_from(
response_selection_results,
"intent_response_key_target",
"intent_response_key_prediction",
)
report, precision, f1, accuracy, confusion_matrix, labels = _calculate_report(
output_directory,
target_intent_response_keys,
predicted_intent_response_keys,
report_as_dict,
)
if output_directory:
_dump_report(output_directory, "response_selection_report.json", report)
if successes:
successes_filename = "response_selection_successes.json"
if output_directory:
successes_filename = os.path.join(output_directory, successes_filename)
# save classified samples to file for debugging
write_response_successes(response_selection_results, successes_filename)
response_errors = _response_errors(response_selection_results)
if errors and output_directory:
errors_filename = "response_selection_errors.json"
errors_filename = os.path.join(output_directory, errors_filename)
_write_errors(response_errors, errors_filename, error_type="response")
if not disable_plotting:
confusion_matrix_filename = "response_selection_confusion_matrix.png"
if output_directory:
confusion_matrix_filename = os.path.join(
output_directory, confusion_matrix_filename
)
plot_utils.plot_confusion_matrix(
confusion_matrix,
classes=labels,
title="Response Selection Confusion Matrix",
output_file=confusion_matrix_filename,
)
histogram_filename = "response_selection_histogram.png"
if output_directory:
histogram_filename = os.path.join(output_directory, histogram_filename)
plot_attribute_confidences(
response_selection_results,
histogram_filename,
"intent_response_key_target",
"intent_response_key_prediction",
title="Response Selection Prediction Confidence Distribution",
)
predictions = [
{
"text": res.message,
"intent_response_key_target": res.intent_response_key_target,
"intent_response_key_prediction": res.intent_response_key_prediction,
"confidence": res.confidence,
}
for res in response_selection_results
]
return {
"predictions": predictions,
"report": report,
"precision": precision,
"f1_score": f1,
"accuracy": accuracy,
"errors": response_errors,
}
def _add_confused_labels_to_report(
report: Dict[Text, Dict[Text, Any]],
confusion_matrix: np.ndarray,
labels: List[Text],
exclude_labels: Optional[List[Text]] = None,
) -> Dict[Text, Dict[Text, Union[Dict, Any]]]:
"""Adds a field "confused_with" to the evaluation report.
The value is a dict of {"false_positive_label": false_positive_count} pairs.
If there are no false positives in the confusion matrix,
the dict will be empty. Typically we include the two most
commonly false positive labels, three in the rare case that
the diagonal element in the confusion matrix is not one of the
three highest values in the row.
Args:
report: the evaluation report
confusion_matrix: confusion matrix
labels: list of labels
Returns: updated evaluation report
"""
if exclude_labels is None:
exclude_labels = []
# sort confusion matrix by false positives
indices = np.argsort(confusion_matrix, axis=1)
n_candidates = min(3, len(labels))
for label in labels:
if label in exclude_labels:
continue
# it is possible to predict intent 'None'
if report.get(label):
report[label]["confused_with"] = {}
for i, label in enumerate(labels):
if label in exclude_labels:
continue
for j in range(n_candidates):
label_idx = indices[i, -(1 + j)]
false_pos_label = labels[label_idx]
false_positives = int(confusion_matrix[i, label_idx])
if (
false_pos_label != label
and false_pos_label not in exclude_labels
and false_positives > 0
):
report[label]["confused_with"][false_pos_label] = false_positives
return report
def evaluate_intents(
intent_results: List[IntentEvaluationResult],
output_directory: Optional[Text],
successes: bool,
errors: bool,
disable_plotting: bool,
report_as_dict: Optional[bool] = None,
) -> Dict: # pragma: no cover
"""Creates summary statistics for intents.
Only considers those examples with a set intent. Others are filtered out.
Returns a dictionary of containing the evaluation result.
Args:
intent_results: intent evaluation results
output_directory: directory to store files to
successes: if True correct predictions are written to disk
errors: if True incorrect predictions are written to disk
disable_plotting: if True no plots are created
report_as_dict: `True` if the evaluation report should be returned as `dict`.
If `False` the report is returned in a human-readable text format. If `None`
`report_as_dict` is considered as `True` in case an `output_directory` is
given.
Returns: dictionary with evaluation results
"""
# remove empty intent targets
num_examples = len(intent_results)
intent_results = remove_empty_intent_examples(intent_results)
logger.info(
f"Intent Evaluation: Only considering those {len(intent_results)} examples "
f"that have a defined intent out of {num_examples} examples."
)
target_intents, predicted_intents = _targets_predictions_from(
intent_results, "intent_target", "intent_prediction"
)
report, precision, f1, accuracy, confusion_matrix, labels = _calculate_report(
output_directory, target_intents, predicted_intents, report_as_dict
)
if output_directory:
_dump_report(output_directory, "intent_report.json", report)
if successes and output_directory:
successes_filename = os.path.join(output_directory, "intent_successes.json")
# save classified samples to file for debugging
write_intent_successes(intent_results, successes_filename)
intent_errors = _get_intent_errors(intent_results)
if errors and output_directory:
errors_filename = os.path.join(output_directory, "intent_errors.json")
_write_errors(intent_errors, errors_filename, "intent")
if not disable_plotting:
confusion_matrix_filename = "intent_confusion_matrix.png"
if output_directory:
confusion_matrix_filename = os.path.join(
output_directory, confusion_matrix_filename
)
plot_utils.plot_confusion_matrix(
confusion_matrix,
classes=labels,
title="Intent Confusion matrix",
output_file=confusion_matrix_filename,
)
histogram_filename = "intent_histogram.png"
if output_directory:
histogram_filename = os.path.join(output_directory, histogram_filename)
plot_attribute_confidences(
intent_results,
histogram_filename,
"intent_target",
"intent_prediction",
title="Intent Prediction Confidence Distribution",
)
predictions = [
{
"text": res.message,
"intent": res.intent_target,
"predicted": res.intent_prediction,
"confidence": res.confidence,
}
for res in intent_results
]
return {
"predictions": predictions,
"report": report,
"precision": precision,
"f1_score": f1,
"accuracy": accuracy,
"errors": intent_errors,
}
def _calculate_report(
output_directory: Optional[Text],
targets: Iterable[Any],
predictions: Iterable[Any],
report_as_dict: Optional[bool] = None,
exclude_label: Optional[Text] = None,
) -> Tuple[Union[Text, Dict], float, float, float, np.ndarray, List[Text]]:
from rasa.model_testing import get_evaluation_metrics
import sklearn.metrics
import sklearn.utils.multiclass
confusion_matrix = sklearn.metrics.confusion_matrix(targets, predictions)
labels = sklearn.utils.multiclass.unique_labels(targets, predictions)
if report_as_dict is None:
report_as_dict = bool(output_directory)
report, precision, f1, accuracy = get_evaluation_metrics(
targets, predictions, output_dict=report_as_dict, exclude_label=exclude_label
)
if report_as_dict:
report = _add_confused_labels_to_report( # type: ignore[assignment]
report,
confusion_matrix,
labels,
exclude_labels=[exclude_label] if exclude_label else [],
)
elif not output_directory:
log_evaluation_table(report, precision, f1, accuracy)
return report, precision, f1, accuracy, confusion_matrix, labels
def _dump_report(output_directory: Text, filename: Text, report: Dict) -> None:
report_filename = os.path.join(output_directory, filename)
rasa.shared.utils.io.dump_obj_as_json_to_file(report_filename, report)
logger.info(f"Classification report saved to {report_filename}.")
def merge_labels(
aligned_predictions: List[Dict], extractor: Optional[Text] = None
) -> List[Text]:
"""Concatenates all labels of the aligned predictions.
Takes the aligned prediction labels which are grouped for each message
and concatenates them.
Args:
aligned_predictions: aligned predictions
extractor: entity extractor name
Returns:
Concatenated predictions
"""
if extractor:
label_lists = [ap["extractor_labels"][extractor] for ap in aligned_predictions]
else:
label_lists = [ap["target_labels"] for ap in aligned_predictions]
return list(itertools.chain(*label_lists))
def merge_confidences(
aligned_predictions: List[Dict], extractor: Optional[Text] = None
) -> List[float]:
"""Concatenates all confidences of the aligned predictions.
Takes the aligned prediction confidences which are grouped for each message
and concatenates them.
Args:
aligned_predictions: aligned predictions
extractor: entity extractor name
Returns:
Concatenated confidences
"""
label_lists = [ap["confidences"][extractor] for ap in aligned_predictions]
return list(itertools.chain(*label_lists))
def substitute_labels(labels: List[Text], old: Text, new: Text) -> List[Text]:
"""Replaces label names in a list of labels.
Args:
labels: list of labels
old: old label name that should be replaced
new: new label name
Returns: updated labels
"""
return [new if label == old else label for label in labels]
def collect_incorrect_entity_predictions(
entity_results: List[EntityEvaluationResult],
merged_predictions: List[Text],
merged_targets: List[Text],
) -> List["EntityPrediction"]:
"""Get incorrect entity predictions.
Args:
entity_results: entity evaluation results
merged_predictions: list of predicted entity labels
merged_targets: list of true entity labels
Returns: list of incorrect predictions
"""
errors = []
offset = 0
for entity_result in entity_results:
for i in range(offset, offset + len(entity_result.tokens)):
if merged_targets[i] != merged_predictions[i]:
prediction: EntityPrediction = {
"text": entity_result.message,
"entities": entity_result.entity_targets,
"predicted_entities": entity_result.entity_predictions,
}
errors.append(prediction)
break
offset += len(entity_result.tokens)
return errors
def write_successful_entity_predictions(
entity_results: List[EntityEvaluationResult],
merged_targets: List[Text],
merged_predictions: List[Text],
successes_filename: Text,
) -> None:
"""Write correct entity predictions to a file.
Args:
entity_results: response selection evaluation result
merged_predictions: list of predicted entity labels
merged_targets: list of true entity labels
successes_filename: filename of file to save correct predictions to
"""
successes = collect_successful_entity_predictions(
entity_results, merged_predictions, merged_targets
)
if successes:
rasa.shared.utils.io.dump_obj_as_json_to_file(successes_filename, successes)
logger.info(f"Successful entity predictions saved to {successes_filename}.")
structlogger.debug("test.write.entities", successes=copy.deepcopy(successes))
else:
logger.info("No successful entity prediction found.")
def collect_successful_entity_predictions(
entity_results: List[EntityEvaluationResult],
merged_predictions: List[Text],
merged_targets: List[Text],
) -> List["EntityPrediction"]:
"""Get correct entity predictions.
Args:
entity_results: entity evaluation results
merged_predictions: list of predicted entity labels
merged_targets: list of true entity labels
Returns: list of correct predictions
"""
successes = []
offset = 0
for entity_result in entity_results:
for i in range(offset, offset + len(entity_result.tokens)):
if (
merged_targets[i] == merged_predictions[i]
and merged_targets[i] != NO_ENTITY
):
prediction: EntityPrediction = {
"text": entity_result.message,
"entities": entity_result.entity_targets,
"predicted_entities": entity_result.entity_predictions,
}
successes.append(prediction)
break
offset += len(entity_result.tokens)
return successes
def evaluate_entities(
entity_results: List[EntityEvaluationResult],
extractors: Set[Text],
output_directory: Optional[Text],
successes: bool,
errors: bool,
disable_plotting: bool,
report_as_dict: Optional[bool] = None,
) -> Dict: # pragma: no cover
"""Creates summary statistics for each entity extractor.
Logs precision, recall, and F1 per entity type for each extractor.
Args:
entity_results: entity evaluation results
extractors: entity extractors to consider
output_directory: directory to store files to
successes: if True correct predictions are written to disk
errors: if True incorrect predictions are written to disk
disable_plotting: if True no plots are created
report_as_dict: `True` if the evaluation report should be returned as `dict`.
If `False` the report is returned in a human-readable text format. If `None`
`report_as_dict` is considered as `True` in case an `output_directory` is
given.
Returns: dictionary with evaluation results
"""
aligned_predictions = align_all_entity_predictions(entity_results, extractors)
merged_targets = merge_labels(aligned_predictions)
merged_targets = substitute_labels(merged_targets, NO_ENTITY_TAG, NO_ENTITY)
result = {}
for extractor in extractors:
merged_predictions = merge_labels(aligned_predictions, extractor)
merged_predictions = substitute_labels(
merged_predictions, NO_ENTITY_TAG, NO_ENTITY
)
cleaned_targets = plugin_manager().hook.clean_entity_targets_for_evaluation(
merged_targets=merged_targets, extractor=extractor
)
if len(cleaned_targets) > 0:
cleaned_targets = cleaned_targets[0]
else:
cleaned_targets = merged_targets
logger.info(f"Evaluation for entity extractor: {extractor} ")
report, precision, f1, accuracy, confusion_matrix, labels = _calculate_report(
output_directory,
cleaned_targets,
merged_predictions,
report_as_dict,
exclude_label=NO_ENTITY,
)
if output_directory:
_dump_report(output_directory, f"{extractor}_report.json", report)
if successes:
successes_filename = f"{extractor}_successes.json"
if output_directory:
successes_filename = os.path.join(output_directory, successes_filename)
# save classified samples to file for debugging
write_successful_entity_predictions(
entity_results, cleaned_targets, merged_predictions, successes_filename
)
entity_errors = collect_incorrect_entity_predictions(
entity_results, merged_predictions, cleaned_targets
)
if errors and output_directory:
errors_filename = os.path.join(output_directory, f"{extractor}_errors.json")
_write_errors(entity_errors, errors_filename, "entity")
if not disable_plotting:
confusion_matrix_filename = f"{extractor}_confusion_matrix.png"
if output_directory:
confusion_matrix_filename = os.path.join(
output_directory, confusion_matrix_filename
)
plot_utils.plot_confusion_matrix(
confusion_matrix,
classes=labels,
title="Entity Confusion matrix",
output_file=confusion_matrix_filename,
)
if extractor in EXTRACTORS_WITH_CONFIDENCES:
merged_confidences = merge_confidences(aligned_predictions, extractor)
histogram_filename = f"{extractor}_histogram.png"
if output_directory:
histogram_filename = os.path.join(
output_directory, histogram_filename
)
plot_entity_confidences(
cleaned_targets,
merged_predictions,
merged_confidences,
title="Entity Prediction Confidence Distribution",
hist_filename=histogram_filename,
)
result[extractor] = {
"report": report,
"precision": precision,
"f1_score": f1,
"accuracy": accuracy,
"errors": entity_errors,
}
return result
def is_token_within_entity(token: Token, entity: Dict) -> bool:
"""Checks if a token is within the boundaries of an entity."""
return determine_intersection(token, entity) == len(token.text)
def does_token_cross_borders(token: Token, entity: Dict) -> bool:
"""Checks if a token crosses the boundaries of an entity."""
num_intersect = determine_intersection(token, entity)
return 0 < num_intersect < len(token.text)
def determine_intersection(token: Token, entity: Dict) -> int:
"""Calculates how many characters a given token and entity share."""
pos_token = set(range(token.start, token.end))
pos_entity = set(range(entity["start"], entity["end"]))
return len(pos_token.intersection(pos_entity))
def do_entities_overlap(entities: List[Dict]) -> bool:
"""Checks if entities overlap.
I.e. cross each others start and end boundaries.
Args:
entities: list of entities
Returns: true if entities overlap, false otherwise.
"""
sorted_entities = sorted(entities, key=lambda e: e["start"])
for i in range(len(sorted_entities) - 1):
curr_ent = sorted_entities[i]
next_ent = sorted_entities[i + 1]
if (
next_ent["start"] < curr_ent["end"]
and next_ent["entity"] != curr_ent["entity"]
):
structlogger.warning(
"test.overlaping.entities",
current_entity=copy.deepcopy(curr_ent),
next_entity=copy.deepcopy(next_ent),
)
return True
return False