Files
ISSSTELEON/Extraction/extraction/nlp/evaluation.py
T
2026-11-13 11:53:07 -06:00

113 lines
4.2 KiB
Python

"""How well extraction does against an answer key (VAR-04, VARM-05).
An answer key maps each document to the right value of each field it was
checked for; `None` means the field must stay empty, and a field left out
of a document's answers is not scored for it. Per field, a value equal to
the key is a true positive, a value where the key has another or none is a
false positive, and a key value not extracted (or extracted wrong) is a
false negative: a wrong value counts as both, as is usual for slot filling.
"""
from dataclasses import dataclass, field
from typing import Any, Mapping
from extraction.nlp.ranking import same_value
@dataclass
class FieldScore:
true_positives: int = 0
false_positives: int = 0
false_negatives: int = 0
true_negatives: int = 0
@property
def precision(self) -> float | None:
found = self.true_positives + self.false_positives
return self.true_positives / found if found else None
@property
def recall(self) -> float | None:
expected = self.true_positives + self.false_negatives
return self.true_positives / expected if expected else None
@property
def f1(self) -> float | None:
p, r = self.precision, self.recall
if p is None or r is None or p + r == 0:
return None
return 2 * p * r / (p + r)
def add(self, extracted: Any, expected: Any) -> bool:
"""Scores one value; returns whether it was right."""
if expected is None:
if extracted is None:
self.true_negatives += 1
return True
self.false_positives += 1
return False
if extracted is not None and same_value(extracted, expected):
self.true_positives += 1
return True
self.false_negatives += 1
if extracted is not None:
self.false_positives += 1
return False
def merge(self, other: "FieldScore") -> None:
self.true_positives += other.true_positives
self.false_positives += other.false_positives
self.false_negatives += other.false_negatives
self.true_negatives += other.true_negatives
def to_dict(self) -> dict[str, Any]:
return {
"verdaderos_positivos": self.true_positives,
"falsos_positivos": self.false_positives,
"falsos_negativos": self.false_negatives,
"verdaderos_negativos": self.true_negatives,
"precision": _round(self.precision),
"exhaustividad": _round(self.recall),
"f1": _round(self.f1),
}
@dataclass
class Evaluation:
fields: dict[str, FieldScore] = field(default_factory=dict)
# Per document and field, what was extracted where it differs from the key.
errors: list[dict[str, Any]] = field(default_factory=list)
@property
def overall(self) -> FieldScore:
total = FieldScore()
for score in self.fields.values():
total.merge(score)
return total
def to_dict(self, *, with_values: bool = False) -> dict[str, Any]:
"""`with_values` includes the wrong and expected values of each error;
without it, only which document and field, so a report on real
documents can be shared without what they say."""
errors = self.errors if with_values else [{"documento": e["documento"], "campo": e["campo"]} for e in self.errors]
return {
"global": self.overall.to_dict(),
"campos": {name: score.to_dict() for name, score in sorted(self.fields.items())},
"errores": errors,
}
def evaluate(extracted: Mapping[str, Mapping[str, Any]], key: Mapping[str, Mapping[str, Any]]) -> Evaluation:
"""`extracted` and `key`: per document, per field, a value."""
result = Evaluation()
for document, expected_fields in key.items():
found = extracted.get(document, {})
for name, expected in expected_fields.items():
value = found.get(name)
if not result.fields.setdefault(name, FieldScore()).add(value, expected):
result.errors.append({"documento": document, "campo": name, "extraido": value, "esperado": expected})
return result
def _round(value: float | None) -> float | None:
return None if value is None else round(value, 3)