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

225 lines
9.3 KiB
Python

"""Choosing one reading per field among the candidates the extractors
propose, and learning to choose better from the corrections people make.
`HeuristicRanker` keeps the most confident candidate. `LearnedRanker` is a
logistic regression over how each candidate was found (its method, the
assertion and section of its mention, the label's score, how many other
candidates agree with it...), never over the document's words: its weights
can be read, and it holds nothing a patient wrote or was written about.
It learns online, one batch of reviewed records at a time (AdaGrad with L2,
Duchi et al., 2011), so a correction made today improves tomorrow's
extraction without retraining from scratch.
While it has seen few examples its score is blended with the heuristic
one (`HeuristicRanker`, rules included), trusting it more as examples
accumulate (`TRUST_EXAMPLES`).
"""
import math
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import date, datetime
from typing import Any, Iterable, Mapping, Sequence
from extraction.nlp.fields import ExtractedValue, FieldSpec
from extraction.nlp.text import fold
# Examples after which the learned score is trusted fully over the heuristic.
TRUST_EXAMPLES = 200
# Below this score, a field is left empty rather than filled with its best
# guess; a trusted learned ranker leaves it empty below even odds.
MIN_SCORE = 0.05
LEARNED_MIN_SCORE = 0.5
class CandidateRanker(ABC):
version: str | None = None
@property
def min_score(self) -> float:
return MIN_SCORE
@abstractmethod
def score(self, spec: FieldSpec, candidate: ExtractedValue) -> float: ...
def choose(self, spec: FieldSpec, candidates: Sequence[ExtractedValue]) -> ExtractedValue | None:
"""The best candidate, its confidence replaced by its score."""
scored = [(self.score(spec, candidate), candidate) for candidate in candidates]
if not scored:
return None
score, best = max(scored, key=lambda pair: (pair[0], pair[1].confidence))
if score < self.min_score:
return None
return best.with_confidence(score)
class HeuristicRanker(CandidateRanker):
"""The most confident candidate, except that a document about something
else than the target, or a mention the report only supposes, fills
nothing: those are left for a person, and for a learned ranker to weigh."""
def score(self, spec: FieldSpec, candidate: ExtractedValue) -> float:
if candidate.features.get("on_topic") is False or candidate.features.get("assertion") == "hipotetico":
return 0.0
return candidate.confidence
def features(spec: FieldSpec, candidate: ExtractedValue) -> dict[str, float]:
"""A candidate as named features: categorical ones one-hot, numeric ones
as they are; field and method crossed with the rest, so each field can
weigh each kind of evidence its own way."""
out: dict[str, float] = {"bias": 1.0, f"kind={spec.kind.value}": 1.0}
prefixes = (f"method={candidate.method}", f"field={spec.name}", f"field={spec.name}|method={candidate.method}")
out.update({prefix: 1.0 for prefix in prefixes})
numeric = {"heuristic": candidate.confidence}
categorical: dict[str, str] = {}
for key, value in candidate.features.items():
if isinstance(value, bool):
numeric[key] = float(value)
elif isinstance(value, (int, float)):
numeric[key] = float(value)
elif isinstance(value, str):
categorical[key] = value
numeric["log_candidates"] = math.log1p(numeric.pop("candidates", 0.0))
numeric["first"] = float(numeric.pop("rank", 1.0) == 0)
for key, value in numeric.items():
out[key] = value
out[f"method={candidate.method}|{key}"] = value
for key, value in categorical.items():
out[f"{key}={value}"] = 1.0
out[f"method={candidate.method}|{key}={value}"] = 1.0
out[f"field={spec.name}|{key}={value}"] = 1.0
return out
@dataclass
class LearnedRanker(CandidateRanker):
weights: dict[str, float] = field(default_factory=dict)
squared_gradients: dict[str, float] = field(default_factory=dict)
examples: int = 0
positives: int = 0
learning_rate: float = 0.3
l2: float = 1e-4
version: str | None = None
def probability(self, x: Mapping[str, float]) -> float:
z = sum(self.weights.get(name, 0.0) * value for name, value in x.items())
return 1.0 / (1.0 + math.exp(-max(-30.0, min(30.0, z))))
@property
def trust(self) -> float:
return min(1.0, self.examples / TRUST_EXAMPLES)
@property
def min_score(self) -> float:
return self.trust * LEARNED_MIN_SCORE + (1.0 - self.trust) * MIN_SCORE
def score(self, spec: FieldSpec, candidate: ExtractedValue) -> float:
heuristic = HeuristicRanker().score(spec, candidate)
if heuristic == 0.0 and self.trust < 1.0:
# What the rules rule out stays out until the ranker is fully trusted.
return 0.0
learned = self.probability(features(spec, candidate))
return self.trust * learned + (1.0 - self.trust) * heuristic
def learn(self, examples: Iterable["Example"], *, epochs: int = 1) -> None:
"""One pass (or `epochs`) of AdaGrad over the examples. Positives are
weighted by how rare they are among them, so a field with many wrong
candidates per right one still learns what right looks like."""
batch = list(examples)
if not batch:
return
positives = sum(1 for e in batch if e.label)
negatives = len(batch) - positives
positive_weight = min(5.0, negatives / positives) if positives else 1.0
for _ in range(epochs):
for example in batch:
x = example.x
error = self.probability(x) - (1.0 if example.label else 0.0)
scale = positive_weight if example.label else 1.0
for name, value in x.items():
gradient = scale * error * value + self.l2 * self.weights.get(name, 0.0)
accumulated = self.squared_gradients.get(name, 0.0) + gradient * gradient
self.squared_gradients[name] = accumulated
self.weights[name] = self.weights.get(name, 0.0) - self.learning_rate * gradient / (math.sqrt(accumulated) + 1e-8)
self.examples += len(batch)
self.positives += positives
def to_dict(self) -> dict[str, Any]:
return {
"weights": self.weights,
"squared_gradients": self.squared_gradients,
"examples": self.examples,
"positives": self.positives,
"learning_rate": self.learning_rate,
"l2": self.l2,
}
@classmethod
def from_dict(cls, data: Mapping[str, Any], *, version: str | None = None) -> "LearnedRanker":
return cls(
weights=dict(data.get("weights", {})),
squared_gradients=dict(data.get("squared_gradients", {})),
examples=int(data.get("examples", 0)),
positives=int(data.get("positives", 0)),
learning_rate=float(data.get("learning_rate", 0.3)),
l2=float(data.get("l2", 1e-4)),
version=version,
)
def copy(self) -> "LearnedRanker":
return LearnedRanker.from_dict(self.to_dict(), version=self.version)
def strongest(self, count: int = 15) -> list[tuple[str, float]]:
return sorted(self.weights.items(), key=lambda item: -abs(item[1]))[:count]
@dataclass(frozen=True)
class Example:
field: str
x: Mapping[str, float]
label: bool
def same_value(left: Any, right: Any) -> bool:
"""Whether an extracted value is the one a person said is right:
dates by day, numbers by value, text without case or accents."""
if left is None or right is None:
return left is None and right is None
if isinstance(left, (date, datetime)) or isinstance(right, (date, datetime)):
return _as_date(left) is not None and _as_date(left) == _as_date(right)
if isinstance(left, (int, float)) and not isinstance(left, bool) or isinstance(right, (int, float)) and not isinstance(right, bool):
try:
return abs(float(left) - float(right)) < 1e-6
except (TypeError, ValueError):
return False
return " ".join(fold(str(left)).split()) == " ".join(fold(str(right)).split())
def _as_date(value: Any) -> date | None:
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
try:
return date.fromisoformat(str(value)[:10])
except ValueError:
return None
def examples_for(
specs: Sequence[FieldSpec], candidates: Mapping[str, Sequence[ExtractedValue]], truth: Mapping[str, Any]
) -> list[Example]:
"""Labelled examples from one record: every candidate of a field whose
right value is known is right (it equals that value) or wrong. A field
known to be empty makes all its candidates wrong; a field not in
`truth` teaches nothing."""
by_name = {spec.name: spec for spec in specs}
found = []
for name, value in truth.items():
spec = by_name.get(name)
if spec is None:
continue
for candidate in candidates.get(name, ()):
found.append(Example(name, features(spec, candidate), value is not None and same_value(candidate.value, value)))
return found