evaluation_utils.py
20.9 KB
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
import urllib.parse
import json
import typing
from collections import Counter
from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score, confusion_matrix
from morfeusz2 import Morfeusz
from .hybrid_tree_utils import tree2dict, correct_lemma, TreeNode
from .ner_utils import get_nes
from .constants import MASK_VALUE, HEADS, DEPRELS, GRAPH_HEADS, GRAPH_DEPRELS, LEMMAS, TAGS, NE_IOBS
from .type_utils import TokenList, LabelDict
def _tree2spans(
tree: TreeNode,
spans: list[tuple[tuple[int, ...], str, bool]],
labeled: bool,
headed: bool,
discontinuous_only: bool,
skip_categories: list[str] | None = None
) -> set[int]:
if headed and not labeled:
raise RuntimeError('cant’t use headed=True with labeled=False')
if not tree.children:
assert (tree.from_index is not None)
return {tree.from_index}
if skip_categories is None:
skip_categories = []
span = set()
for child in tree.children:
span.update(_tree2spans(child, spans, labeled, headed, discontinuous_only, skip_categories))
if tree.category not in skip_categories:
sorted_span = tuple(sorted(span))
if discontinuous_only and sorted_span == tuple(range(sorted_span[0], sorted_span[-1] + 1)):
# continuous constituent
pass
else:
assert (tree.category is not None)
spans += [(sorted_span, tree.category if labeled else 'SPAN', tree.is_head if headed else False)]
return span
def tree2spans(
tree: TreeNode,
labeled: bool = True,
headed: bool = False,
discontinuous_only: bool = False,
skip_categories: list[str] | None = None
) -> set[tuple[tuple[int, ...], str, bool]]:
spans: list[tuple[tuple[int, ...], str, bool]] = []
_tree2spans(tree, spans, labeled, headed, discontinuous_only, skip_categories)
# TODO
#try:
# assert(len(spans) == len(set(spans)))
#except:
# show_tree(tree)
# (display(spans))
# 1/0
return set(spans)
def _tree2edges(tree: TreeNode, edges: list[tuple[str, str, int, int, str]]) -> int:
if not tree.children:
assert (tree.from_index is not None)
return tree.from_index
head_index = None
child_edges = []
for child in tree.children:
child_head_index = _tree2edges(child, edges)
child_cat = child.category if child.children else '<TERMINAL>'
assert (child_cat is not None)
deprel = child.attributes['deprel'] if not child.is_head else '<HEAD>'
child_edges.append((child_head_index, child_cat, deprel))
if child.is_head:
assert(head_index is None)
head_index = child_head_index
assert(head_index is not None)
assert(tree.category is not None)
for child_head_index, child_cat, deprel in child_edges:
assert (child_cat is not None)
edges.append((tree.category, child_cat, head_index, child_head_index, deprel))
return head_index
def tree2edges(tree: TreeNode) -> set[tuple[str, str, int, int, str]]:
edges: list[tuple[str, str, int, int, str]] = []
_tree2edges(tree, edges)
#TODO?
#if len(edges) != len(set(edges)):
# #show_tree(tree)
# #1/0
return set(edges)
# TODO mixed and masked data!
class EvaluationMetric(object):
def __init__(self, name: str) -> None:
self.name = name
self.total = 0
self.masked = 0
def update(
self,
tokens: TokenList,
tags_true: LabelDict,
tags_pred: LabelDict,
tree_true: TreeNode | None,
tree_pred: TreeNode | None,
) -> None:
raise NotImplementedError
def calculate(self) -> dict[str, typing.Any]:
return {
'result' : self.do_calculate(),
'total instances' : self.total,
'masked instances' : self.masked,
}
def do_calculate(self) -> typing.Any:
raise NotImplementedError
class TokenMetric(EvaluationMetric):
def __init__(self, name: str) -> None:
super().__init__(name)
self.true: list[typing.Any] = []
self.pred: list[typing.Any] = []
def get_labels(self, tags: LabelDict) -> list[typing.Any] | None:
raise NotImplementedError
def update(
self,
tokens: TokenList,
tags_true: LabelDict,
tags_pred: LabelDict,
tree_true: TreeNode | None,
tree_pred: TreeNode | None,
) -> None:
self.total += 1
labels_true = self.get_labels(tags_true)
if labels_true is not None:
self.true += labels_true
labels_pred = self.get_labels(tags_pred)
assert (labels_pred is not None)
self.pred += labels_pred
else:
self.masked += 1
def _calculate(self, true: list[typing.Any], pred: list[typing.Any]) -> typing.Any:
raise NotImplementedError
def do_calculate(self) -> typing.Any:
# for Składnica merged data with masked deprels...
filtered = [(t, p) for t, p in zip(self.true, self.pred) if t is not None]
if filtered:
true, pred = map(list, zip(*filtered))
return self._calculate(true, pred)
else:
return 'N/A'
class AccuracyMetric(TokenMetric):
def __init__(self, name: str) -> None:
super().__init__(name)
def _calculate(self, true: list[typing.Any], pred: list[typing.Any]) -> typing.Any:
if not (true or pred):
return 'N/A'
return accuracy_score(true, pred)
class UAS(AccuracyMetric):
def __init__(self) -> None:
super().__init__('UAS')
def get_labels(self, tags: LabelDict) -> list[int] | None:
if MASK_VALUE in tags[HEADS]:
return None
return [h if h is not None else -1 for h in tags[HEADS]]
class LAS(AccuracyMetric):
def __init__(self) -> None:
super().__init__('LAS')
def get_labels(self, tags: LabelDict) -> list[str] | None:
# for Składnica merged data with masked deprels...
if MASK_VALUE in tags[HEADS] or None in tags[DEPRELS]:
return None
return [f'{h}#{d.split(":")[0]}' for h, d in zip(tags[HEADS], tags[DEPRELS])] # type: ignore[union-attr] # all deprels are not None
class Tagging(AccuracyMetric):
def __init__(self) -> None:
super().__init__('tagging')
def get_labels(self, tags: LabelDict) -> list[str] | None:
if None in tags[TAGS]:
return None
return tags[TAGS] # type: ignore[return-value] # all tags are not None
class TaggingCorr(AccuracyMetric):
def __init__(self, morfeusz: Morfeusz) -> None:
super().__init__('tagging*')
self.morfeusz = morfeusz
# TODO test: this looks unnecessary since we override update()? or use correct_lemma in get_labels?
#def get_labels(self, tags: LabelDict) -> list[str] | None:
# if MASK_VALUE in tags[TAGS]:
# return None
# return tags[TAGS] # type: ignore[return-value] # all tags are not None
def update(
self,
tokens: TokenList,
tags_true: LabelDict,
tags_pred: LabelDict,
tree_true: TreeNode | None,
tree_pred: TreeNode | None,
) -> None:
self.total += 1
if None in tags_true[TAGS]:
self.masked += 1
else:
self.true += tags_true[TAGS]
self.pred += [
correct_lemma(*x, self.morfeusz)[1] for x in zip( # type: ignore [arg-type]
tokens, tags_pred[LEMMAS], tags_pred[TAGS])
]
class Lemmatisation(AccuracyMetric):
def __init__(self) -> None:
super().__init__('lemmatisation')
def get_labels(self, tags: LabelDict) -> list[str] | None:
if None in tags[LEMMAS]:
return None
return tags[LEMMAS] # type: ignore[return-value] # all lemmas are not None
class LemmatisationCorr(AccuracyMetric):
def __init__(self, morfeusz: Morfeusz) -> None:
super().__init__('lemmatisation*')
self.morfeusz = morfeusz
def update(
self,
tokens: TokenList,
tags_true: LabelDict,
tags_pred: LabelDict,
tree_true: TreeNode | None,
tree_pred: TreeNode | None,
) -> None:
self.total += 1
if None in tags_true[LEMMAS]:
self.masked += 1
else:
self.true += tags_true[LEMMAS]
self.pred += [
correct_lemma(*x, self.morfeusz)[0] for x in zip( # type: ignore [arg-type]
tokens, tags_pred[LEMMAS], tags_pred[TAGS])
]
class PrecisionRecallFscore(EvaluationMetric):
def __init__(self, name: str) -> None:
super().__init__(name)
self.true_positive = 0
self.precision_denominator = 0
self.recall_denominator = 0
self.partial_true_positives: dict[typing.Any, int] = Counter()
self.partial_precision_denominators: dict[typing.Any, int] = Counter()
self.partial_recall_denominators: dict[typing.Any, int] = Counter()
self.unit_keys: set[typing.Any] = set()
def get_units(self, tree: TreeNode | None, tags: LabelDict) -> set[typing.Any] | None:
raise NotImplementedError
def get_unit_key(self, unit: typing.Any) -> typing.Any:
raise NotImplementedError
def update(
self,
tokens: TokenList,
tags_true: LabelDict,
tags_pred: LabelDict,
tree_true: TreeNode | None,
tree_pred: TreeNode | None,
) -> None:
self.total += 1
units_true = self.get_units(tree_true, tags_true)
if units_true is None:
self.masked += 1
else:
units_pred = self.get_units(tree_pred, tags_pred)
assert (units_pred is not None)
common = units_true.intersection(units_pred)
self.true_positive += len(units_true.intersection(units_pred))
self.precision_denominator += len(units_pred)
self.recall_denominator += len(units_true)
for unit in units_true.union(units_pred):
key = self.get_unit_key(unit)
self.unit_keys.add(key)
if unit in units_true:
self.partial_recall_denominators[key] += 1
if unit in units_pred:
self.partial_precision_denominators[key] += 1
if unit in common:
self.partial_true_positives[key] += 1
def do_calculate(self) -> typing.Any:
f: float | str = 0
p = self.true_positive / self.precision_denominator if self.precision_denominator else 'N/A'
r = self.true_positive / self.recall_denominator if self.recall_denominator else 'N/A'
if self.precision_denominator and self.recall_denominator:
assert (isinstance(p, float))
assert (isinstance(r, float))
if p or r:
f = (2 * p * r) / (p + r)
else:
f = 'N/A'
ret = {
'total' : {
'P' : p,
'R' : r,
'F1': f,
}
}
for key in self.unit_keys:
pd = self.partial_precision_denominators[key]
pr = self.partial_recall_denominators[key]
p = (self.partial_true_positives[key] / pd) if pd else 'N/A'
r = (self.partial_true_positives[key] / pr) if pr else 'N/A'
if pd and pr:
assert (isinstance(p, float))
assert (isinstance(r, float))
f = ((2 * p * r) / (p + r)) if p or r else 0.0
else:
f = 'N/A'
ret[key] = {
'P' : p,
'R' : r,
'F1' : f,
'n' : self.partial_recall_denominators[key],
}
return ret
class Spans(PrecisionRecallFscore):
def __init__(
self,
name: str,
labeled: bool,
headed: bool,
discontinuous_only: bool = False,
skip_categories: list[str] | None = None,
) -> None:
super().__init__(name)
self.labeled = labeled
self.headed = headed
self.discontinuous_only = discontinuous_only
self.skip_categories = skip_categories if skip_categories is not None else []
def get_unit_key(self, unit: tuple[tuple[int, ...], str, bool]) -> str:
# unit: <span, cat, is_head>
return unit[1]# if len(unit[0]) > 1 else '<PRETERMINAL>'
def get_units(self, tree: TreeNode | None, tags: LabelDict) -> set[tuple[tuple[int, ...], str, bool]] | None:
if not tree:
return None
return tree2spans(
tree,
labeled=self.labeled,
headed=self.headed,
discontinuous_only=self.discontinuous_only,
skip_categories=self.skip_categories
)
class HeadedSpans(Spans):
def __init__(self, **kwargs: typing.Any) -> None:
super().__init__('headed constit.', labeled=True, headed=True, **kwargs)
class NonHeadedSpans(Spans):
def __init__(self, **kwargs: typing.Any) -> None:
super().__init__('constituents', labeled=True, headed=False, **kwargs)
class UnlabeledSpans(Spans):
def __init__(self, **kwargs: typing.Any) -> None:
super().__init__('bracketing', labeled=False, headed=False, **kwargs)
class HeadedSpansDiscontinuous(Spans):
def __init__(self, **kwargs: typing.Any) -> None:
super().__init__('disc. headed constit.', labeled=True, headed=True, discontinuous_only=True, **kwargs)
class NonHeadedSpansDiscontinuous(Spans):
def __init__(self, **kwargs: typing.Any) -> None:
super().__init__('disc. constituents', labeled=True, headed=False, discontinuous_only=True, **kwargs)
class UnlabeledSpansDiscontinuous(Spans):
def __init__(self, **kwargs: typing.Any) -> None:
super().__init__('disc. bracketing', labeled=False, headed=False, discontinuous_only=True, **kwargs)
class Edges(PrecisionRecallFscore):
def __init__(self) -> None:
super().__init__('edges')
def get_unit_key(self, unit: tuple[str, str, int, int, str]) -> tuple[str, str, str]:
# unit = from_cat, to_cat, from_index, to_index, deprel
return (unit[0], unit[1], unit[4])
def get_units(self, tree: TreeNode | None, tags: LabelDict) -> set[tuple[str, str, int, int, str]] | None:
if not tree or None in tags[DEPRELS]:
return None
return tree2edges(tree)
class Deprels(PrecisionRecallFscore):
def __init__(self) -> None:
super().__init__('deprels')
def get_unit_key(self, unit: tuple[int, str]) -> str:
# unit = idx, deprel
return unit[1]
def get_units(self, tree: TreeNode | None, tags: LabelDict) -> set[tuple[int, str]] | None:
if None in tags[DEPRELS]:
return None
return set(enumerate(tags[DEPRELS])) # type: ignore [arg-type]
class DepArcs(PrecisionRecallFscore):
def __init__(self) -> None:
super().__init__('deparcs')
def get_unit_key(self, unit: tuple[int, tuple[str, int]]) -> str:
# unit = idx, (deprel, parent)
return unit[1][0]
def get_units(self, tree: TreeNode | None, tags: LabelDict) -> set[tuple[int, tuple[str, int | None]]] | None:
if None in tags[DEPRELS]:
return None
return set(enumerate(zip(tags[DEPRELS], tags[HEADS]))) # type: ignore [arg-type]
class EUAS(PrecisionRecallFscore):
def __init__(self) -> None:
super().__init__('EUAS')
def get_unit_key(self, unit: tuple[int, int]) -> str:
# unit = idx, parent
# no grouping here
return ''
def get_units(self, tree: TreeNode | None, tags: LabelDict) -> set[tuple[int, int | None]] | None:
if MASK_VALUE in tags[HEADS] or [MASK_VALUE] in tags[GRAPH_HEADS]:
return None
ret = set(enumerate(tags[HEADS]))
# In EUD, standard i->j edge implies no enhanced i->j edge,
# but in predicate-argument graphs it’s possible (at most one enhanced i->j).
# For now, treat them as one *unlabeled* edge (and differentiate in ELAS).
# Alternative: index the enhanced ones as, e.g. (i, f'{j}e')
for idx, heads in enumerate(tags[GRAPH_HEADS]):
for h in heads:
ret.add((idx, h))
return ret
class ELAS(PrecisionRecallFscore):
def __init__(self) -> None:
super().__init__('ELAS')
def get_unit_key(self, unit: tuple[int, tuple[str, int]]) -> str:
# unit = idx, (deprel, parent)
return unit[1][0]
def get_units(self, tree: TreeNode | None, tags: LabelDict) -> set[tuple[int, tuple[str, int | None]]] | None:
if MASK_VALUE in tags[HEADS] or [MASK_VALUE] in tags[GRAPH_HEADS]:
return None
ret = set(enumerate(zip(tags[DEPRELS], tags[HEADS])))
for idx, (deprels, heads) in enumerate(zip(tags[GRAPH_DEPRELS], tags[GRAPH_HEADS])):
for d, h in zip(deprels, heads):
ret.add((idx, (d, h)))
return ret # type: ignore [return-value] # all deprels are not None
# graph unlabeled attachment – only the enhanced edges
class GUAS(PrecisionRecallFscore):
def __init__(self) -> None:
super().__init__('GUAS')
def get_unit_key(self, unit: tuple[int, int]) -> str:
# unit = idx, parent
# no grouping here
return ''
def get_units(self, tree: TreeNode | None, tags: LabelDict) -> set[tuple[int, int | None]] | None:
if [MASK_VALUE] in tags[GRAPH_HEADS]:
return None
ret = set()
for idx, heads in enumerate(tags[GRAPH_HEADS]):
for h in heads:
ret.add((idx, h))
return ret
# graph labeled attachment – only the enhanced edges
class GLAS(PrecisionRecallFscore):
def __init__(self) -> None:
super().__init__('GLAS')
def get_unit_key(self, unit: tuple[int, tuple[str, int]]) -> str:
# unit = idx, (deprel, parent)
return unit[1][0]
def get_units(self, tree: TreeNode | None, tags: LabelDict) -> set[tuple[int, tuple[str, int | None]]] | None:
if [MASK_VALUE] in tags[GRAPH_HEADS]:
return None
ret = set()
# In EUD, standard i->j edge implies no enhanced i->j edge,
# but in predicate-argument graphs it’s possible (at most one enhanced i->j).
# For now, treat them as one *unlabeled* edge (and differentiate in ELAS).
# Alternative: index the enhanced ones as, e.g. (i, f'{j}e')
for idx, (deprels, heads) in enumerate(zip(tags[GRAPH_DEPRELS], tags[GRAPH_HEADS])):
for d, h in zip(deprels, heads):
assert (d is not None)
ret.add((idx, (d, h)))
return ret
class NER(PrecisionRecallFscore):
def __init__(self) -> None:
super().__init__('NER')
def get_unit_key(self, unit: tuple[tuple[int, ...], str]) -> str:
# unit = span, ne_type
return unit[1]
def get_units(self, tree: TreeNode | None, tags: LabelDict) -> set[tuple[int, tuple[str, int | None]]] | None:
if None in tags[NE_IOBS]:
return None
ne_tags = tags[NE_IOBS]
# tokens in returned units will have indices, so anything works as text form here
nes = get_nes(['_' for _ in ne_tags], ne_tags)
return set((tuple(idx for idx, _ in tokens), ne_type) for tokens, ne_type in nes)
class ConfusionMatrix(TokenMetric):
def __init__(self, name: str) -> None:
super().__init__(name)
def _calculate(self, true: list[typing.Any], pred: list[typing.Any]) -> typing.Any:
labels = sorted(set(true + pred))
errors = Counter((t, p) for t, p in zip(true, pred) if t != p)
return confusion_matrix(true, pred, labels=labels), labels, errors
class DeprelsConfusionMatrix(ConfusionMatrix):
def __init__(self) -> None:
super().__init__('deprels_cf')
def get_labels(self, tags: LabelDict) -> list[str] | None:
if None in tags[DEPRELS]:
return None
return tags[DEPRELS] # type: ignore[return-value] # all deprels are not None
class DepArcsConfusionMatrix(ConfusionMatrix):
def __init__(self) -> None:
super().__init__('deparcs_cf')
def get_labels(self, tags: LabelDict) -> list[tuple[str, int]] | None:
if None in tags[DEPRELS]:
return None
return list(zip(tags[DEPRELS], tags[HEADS])) # type: ignore [arg-type]
def _calculate(self, true: list[typing.Any], pred: list[typing.Any]) -> typing.Any:
new_true, new_pred = [], []
i = 0
for t, p in zip(true, pred):
new_true.append(t[0])
new_pred.append(p[0] if p[1] == t[1] else '—')
true, pred = new_true, new_pred
labels = sorted(set(true + pred))
errors = Counter((t, p) for t, p in zip(true, pred) if t != p)
return confusion_matrix(true, pred, labels=labels), labels, errors