This commit is contained in:
+101
-24
@@ -10,29 +10,72 @@ import yaml
|
||||
from torch.utils.data import DataLoader
|
||||
|
||||
from data.dataset import EvidenceDataset, collate_evidence
|
||||
from data.schema import FACT_TYPE, NULL_TYPE, RULE_TYPE
|
||||
from losses.matching_loss import hungarian_matching_loss
|
||||
from models.evidence_model import EvidenceExtractorModel
|
||||
|
||||
|
||||
def slot_counts(predictions: dict[str, torch.Tensor], targets: list[torch.Tensor]) -> dict[str, int]:
|
||||
subjects = predictions["subject_logits"].argmax(-1).cpu()
|
||||
predicates = predictions["predicate_logits"].argmax(-1).cpu()
|
||||
objects = predictions["object_logits"].argmax(-1).cpu()
|
||||
valid = predictions["valid_logits"].argmax(-1).cpu().bool()
|
||||
counts = {"tp": 0, "fp": 0, "fn": 0, "component_correct": 0, "component_total": 0}
|
||||
for batch_index, facts in enumerate(targets):
|
||||
predicted = {
|
||||
(int(subjects[batch_index, slot]), int(predicates[batch_index, slot]), int(objects[batch_index, slot]))
|
||||
for slot in range(subjects.shape[1])
|
||||
if valid[batch_index, slot]
|
||||
}
|
||||
expected = {tuple(map(int, row.tolist())) for row in facts}
|
||||
COUNT_KEYS = ("tp", "fp", "fn", "component_correct", "component_total")
|
||||
|
||||
|
||||
def empty_counts() -> dict[str, int]:
|
||||
return {key: 0 for key in COUNT_KEYS}
|
||||
|
||||
|
||||
def decode_rows(predictions: dict[str, torch.Tensor], batch_index: int) -> list[tuple[int, ...]]:
|
||||
types = predictions["type_logits"].argmax(-1)[batch_index].cpu()
|
||||
subjects = predictions["subject_logits"].argmax(-1)[batch_index].cpu()
|
||||
predicates = predictions["predicate_logits"].argmax(-1)[batch_index].cpu()
|
||||
objects = predictions["object_logits"].argmax(-1)[batch_index].cpu()
|
||||
consequent_predicates = predictions["consequent_predicate_logits"].argmax(-1)[
|
||||
batch_index
|
||||
].cpu()
|
||||
consequent_objects = predictions["consequent_object_logits"].argmax(-1)[batch_index].cpu()
|
||||
rows = []
|
||||
for slot, state_type in enumerate(types.tolist()):
|
||||
if state_type == NULL_TYPE:
|
||||
continue
|
||||
consequence = (
|
||||
(int(consequent_predicates[slot]), int(consequent_objects[slot]))
|
||||
if state_type == RULE_TYPE
|
||||
else (-1, -1)
|
||||
)
|
||||
rows.append(
|
||||
(
|
||||
state_type,
|
||||
int(subjects[slot]),
|
||||
int(predicates[slot]),
|
||||
int(objects[slot]),
|
||||
*consequence,
|
||||
)
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def slot_counts(
|
||||
predictions: dict[str, torch.Tensor],
|
||||
targets: list[torch.Tensor],
|
||||
state_type: int | None = None,
|
||||
) -> dict[str, int]:
|
||||
counts = empty_counts()
|
||||
for batch_index, target_tensor in enumerate(targets):
|
||||
predicted = set(decode_rows(predictions, batch_index))
|
||||
expected = {tuple(map(int, row.tolist())) for row in target_tensor}
|
||||
if state_type is not None:
|
||||
predicted = {row for row in predicted if row[0] == state_type}
|
||||
expected = {row for row in expected if row[0] == state_type}
|
||||
counts["tp"] += len(predicted & expected)
|
||||
counts["fp"] += len(predicted - expected)
|
||||
counts["fn"] += len(expected - predicted)
|
||||
for triple in predicted:
|
||||
best = max((sum(a == b for a, b in zip(triple, target)) for target in expected), default=0)
|
||||
for row in predicted:
|
||||
compatible = [target for target in expected if target[0] == row[0]]
|
||||
width = 6 if row[0] == RULE_TYPE else 4
|
||||
best = max(
|
||||
(sum(a == b for a, b in zip(row[:width], target[:width])) for target in compatible),
|
||||
default=0,
|
||||
)
|
||||
counts["component_correct"] += best
|
||||
counts["component_total"] += 3
|
||||
counts["component_total"] += width
|
||||
return counts
|
||||
|
||||
|
||||
@@ -43,26 +86,61 @@ def summarize(counts: dict[str, int]) -> dict[str, float]:
|
||||
"precision": precision,
|
||||
"recall": recall,
|
||||
"f1": 2 * precision * recall / max(1e-12, precision + recall),
|
||||
"component_accuracy": counts["component_correct"] / max(1, counts["component_total"]),
|
||||
"component_accuracy": counts["component_correct"]
|
||||
/ max(1, counts["component_total"]),
|
||||
}
|
||||
|
||||
|
||||
def null_slot_counts(
|
||||
predictions: dict[str, torch.Tensor], targets: list[torch.Tensor]
|
||||
) -> tuple[int, int]:
|
||||
matching = hungarian_matching_loss(predictions, targets)
|
||||
predicted_types = predictions["type_logits"].argmax(-1)
|
||||
correct = 0
|
||||
total = predicted_types.numel()
|
||||
for batch_index, (slots, target_indices) in enumerate(matching.assignments):
|
||||
expected = torch.full_like(predicted_types[batch_index], NULL_TYPE)
|
||||
if len(slots):
|
||||
expected[slots] = targets[batch_index].to(expected.device)[target_indices, 0]
|
||||
correct += int((predicted_types[batch_index] == expected).sum())
|
||||
return correct, total
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def evaluate(
|
||||
model: EvidenceExtractorModel, loader: DataLoader, device: torch.device
|
||||
) -> dict[str, Any]:
|
||||
model.eval()
|
||||
totals = {
|
||||
"visual": {"tp": 0, "fp": 0, "fn": 0, "component_correct": 0, "component_total": 0},
|
||||
"text": {"tp": 0, "fp": 0, "fn": 0, "component_correct": 0, "component_total": 0},
|
||||
"visual_fact": empty_counts(),
|
||||
"text_all": empty_counts(),
|
||||
"text_fact": empty_counts(),
|
||||
"text_rule": empty_counts(),
|
||||
}
|
||||
null_correct = 0
|
||||
null_total = 0
|
||||
for batch in loader:
|
||||
outputs = model(batch["images"].to(device), batch["rules_text"])
|
||||
for modality, target_name in (("visual", "visual_facts"), ("text", "text_facts")):
|
||||
counts = slot_counts(outputs[modality], batch[target_name])
|
||||
requests = (
|
||||
("visual_fact", "visual", "visual_targets", FACT_TYPE),
|
||||
("text_all", "text", "text_targets", None),
|
||||
("text_fact", "text", "text_targets", FACT_TYPE),
|
||||
("text_rule", "text", "text_targets", RULE_TYPE),
|
||||
)
|
||||
for name, modality, target_name, state_type in requests:
|
||||
counts = slot_counts(outputs[modality], batch[target_name], state_type)
|
||||
for key, value in counts.items():
|
||||
totals[modality][key] += value
|
||||
return {modality: summarize(value) for modality, value in totals.items()}
|
||||
totals[name][key] += value
|
||||
for modality, target_name in (
|
||||
("visual", "visual_targets"),
|
||||
("text", "text_targets"),
|
||||
):
|
||||
correct, count = null_slot_counts(outputs[modality], batch[target_name])
|
||||
null_correct += correct
|
||||
null_total += count
|
||||
result = {name: summarize(counts) for name, counts in totals.items()}
|
||||
result["null_slot_accuracy"] = null_correct / max(1, null_total)
|
||||
return result
|
||||
|
||||
|
||||
def main() -> None:
|
||||
@@ -91,4 +169,3 @@ def main() -> None:
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user