Repository navigation
Expand file tree
/
Copy pathsummarize_benchmarks.py
More file actions
102 lines (83 loc) · 4.51 KB
/
Copy pathsummarize_benchmarks.py
File metadata and controls
102 lines (83 loc) · 4.51 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
#!/usr/bin/env python
"""Table of zero-shot part-segmentation results from run_benchmarks.sh outputs.
pixi run python summarize_benchmarks.py output/benchmarks/partcatseg_released [more dirs ...]
For each <dir>/<benchmark>/log.txt it reads the object-conditioned ("oracle_obj") result and prints
two versions of base / novel mIoU and their harmonic mean h-IoU:
reported the evaluator's numbers, as in the PartCATSeg paper. Its mIoU-base / mIoU-unbase
average only the classes whose IoU is above 0 (partcatseg_evaluation.py:263), so a
class the model never gets right is left out.
all the same split, but averaging every class with ground truth or a prediction, zeros
included. Lower, and the fairer number to track improvements with.
Base = classes seen in training, novel = held-out classes (the metadata's evaluation_set["base"]).
Writes <dir>/summary.json too. CPU only.
"""
import argparse
import json
import re
import sys
from pathlib import Path
import numpy as np
ENTRY = re.compile(r"""(['"])(IoU-.*?|mIoU-base|mIoU-unbase|h-IoU|mIoU)\1: (nan|[-0-9.e]+)""")
def oracle_result(log):
"""Metrics dict of the last object-conditioned evaluation in a detectron2 log."""
lines = [l for l in Path(log).read_text().splitlines() if "OrderedDict([('oracle_obj'" in l]
if not lines:
return None
line = lines[-1]
block = line[line.index("('oracle_obj', {") + len("('oracle_obj', {"):]
block = block[:block.index("})")]
return {m.group(2): float(m.group(3)) for m in ENTRY.finditer(block)}
def test_dataset(run_dir):
cfg = (Path(run_dir) / "config.yaml").read_text()
m = re.search(r"TEST:\s*\n\s*- (\S+)", cfg) or re.search(r"TEST: \[?\(?'?([\w]+)", cfg)
return m.group(1).strip("'\"") if m else None
def hmean(a, b):
return 2 * a * b / (a + b) if a + b else float("nan")
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("dirs", nargs="+")
args = ap.parse_args()
sys.argv = sys.argv[:1]
import baselines # noqa: F401 registers the datasets (and their base/novel split)
from detectron2.data import MetadataCatalog
rows = []
for d in map(Path, args.dirs):
summary = {}
for run in sorted(p.parent for p in d.glob("*/log.txt")):
res = oracle_result(run / "log.txt")
name = test_dataset(run)
if res is None or name is None:
print(f"{run}: no finished object-conditioned evaluation yet")
continue
meta = MetadataCatalog.get(name)
classes = list(meta.stuff_classes)
base = set(getattr(meta, "evaluation_set", {}).get("base", []))
iou = np.array([res.get(f"IoU-{c}", np.nan) for c in classes])
is_base = np.array([i in base for i in range(len(classes))])
valid = ~np.isnan(iou)
all_base = np.nanmean(iou[valid & is_base]) if (valid & is_base).any() else float("nan")
all_novel = np.nanmean(iou[valid & ~is_base]) if (valid & ~is_base).any() else float("nan")
r = {
"benchmark": run.name, "dataset": name, "classes": len(classes),
"base_classes": int(is_base.sum()), "novel_classes": int((~is_base).sum()),
"zero_iou_classes": int((iou[valid] == 0).sum()),
"reported": {"mIoU-base": res.get("mIoU-base"), "mIoU-novel": res.get("mIoU-unbase"),
"h-IoU": res.get("h-IoU")},
"all": {"mIoU": res.get("mIoU"), "mIoU-base": all_base, "mIoU-novel": all_novel,
"h-IoU": hmean(all_base, all_novel)},
}
summary[run.name] = r
rows.append((d.name, r))
(d / "summary.json").write_text(json.dumps(summary, indent=1))
if not rows:
return
f = lambda v: " n/a" if v is None or v != v else f"{v:5.1f}" # noqa: E731
print(f"\n{'run':<24} {'benchmark':<13} {'classes b/n':>11} {'zeros':>5} | "
f"{'reported: base novel h-IoU':>29} | {'all classes: base novel h-IoU mIoU':>38}")
for tag, r in rows:
rep, al = r["reported"], r["all"]
print(f"{tag:<24} {r['benchmark']:<13} {r['base_classes']:>5}/{r['novel_classes']:<5} {r['zero_iou_classes']:>5} | "
f"{'':>9}{f(rep['mIoU-base'])} {f(rep['mIoU-novel'])} {f(rep['h-IoU'])} | "
f"{'':>13}{f(al['mIoU-base'])} {f(al['mIoU-novel'])} {f(al['h-IoU'])} {f(al['mIoU'])}")
if __name__ == "__main__":
main()