Hsyshasuzh/longmemory-geo / project /evaluation /compare_dior_fixed.py
Hsyshasuzh's picture
download
raw
4.25 kB
"""Evaluate frozen DOTA selection thresholds on DIOR-R selection data."""
import argparse
from copy import deepcopy
import json
from pathlib import Path
import torch
from evaluation.dior_eval import predict
from evaluation.metrics import evaluate_detection
from evaluation.compare_fair1m_dota import precision_frontier
from training.detection_loss import build_adapted_detector
from training.dior_extension import Extension
from training.model_factory import ROOT, load_pretrained_detector
def main():
parser = argparse.ArgumentParser()
parser.add_argument("checkpoint", type=Path)
parser.add_argument("initial_frontier", type=Path)
parser.add_argument("candidate_frontier", type=Path)
parser.add_argument("output", type=Path)
parser.add_argument("--save-records", type=Path)
parser.add_argument("--candidate-only", action="store_true")
args = parser.parse_args()
if args.output.exists():
raise FileExistsError(args.output)
thresholds = {
"initial": json.loads(args.initial_frontier.read_text())["results"]["initial"]["frontier"],
"candidate": json.loads(args.candidate_frontier.read_text())["results"]["candidate"]["frontier"],
}
torch.set_num_threads(4)
extension = Extension()
rows = [row for row in extension.rows if row.get("evaluation_role") == "selection_validation"]
if not rows:
raise ValueError("no DIOR-R selection rows")
pretrained = load_pretrained_detector(ROOT / "training/cache/checkpoints", device="cuda:0")
initial, _ = build_adapted_detector(pretrained, seed=42)
candidate = torch.load(args.checkpoint, map_location="cpu", weights_only=False)["model"]
results, records = {}, {}
for name, model in (("initial", initial), ("candidate", candidate)):
if args.candidate_only and name == "initial":
continue
wrapper = deepcopy(pretrained)
wrapper.model, wrapper.predictor = model.to("cuda:0").eval(), None
pool = predict(wrapper, extension, rows, device="cuda:0")
frontier = precision_frontier(pool["predictions"], pool["targets"])
unthresholded = evaluate_detection(pool["predictions"], pool["targets"], ignore_prediction_fraction=.5)
if args.save_records:
records[name] = {"predictions": deepcopy(pool["predictions"]), "targets": pool["targets"]}
selected = {int(cls): value["best"]["threshold"] for cls, value in thresholds[name].items() if value["best"]}
for row in pool["predictions"]:
row["annotations"] = [a for a in row["annotations"]
if a["category_id"] in selected and a["confidence"] >= selected[a["category_id"]]]
results[name] = {"thresholds": selected,
"in_sample_precision_frontier": frontier,
"unthresholded": unthresholded,
"metrics": evaluate_detection(pool["predictions"], pool["targets"],
ignore_prediction_fraction=.5),
"invalid_center_predictions_removed": pool["invalid_center_predictions_removed"]}
print(name, "completed", flush=True)
report = {"status": "DEVELOPMENT_DIAGNOSTIC", "results": results, "sample_ids": [r["id"] for r in rows],
"extension_content_sha256": extension.approval["content_sha256"],
"limitations": ["DIOR-R selection data was used in earlier project development; not an independent test.",
"Only four compatible classes; vehicle size labels are unsupported.",
"Thresholds were fixed on DOTA selection scenes; bridge abstains when unsupported.",
"Geographic independence and label completeness are unverified."]}
with args.output.open("x") as stream:
json.dump(report, stream, indent=2)
stream.write("\n")
if args.save_records:
with args.save_records.open("x") as stream:
json.dump(records, stream)
print(json.dumps({name: {key: value["metrics"][key] for key in ("precision", "recall", "f1")}
for name, value in results.items()}))
if __name__ == "__main__":
main()

Xet Storage Details

Size:
4.25 kB
·
Xet hash:
b02739214b794351689a06afc814f9298e8b1b5989ef365e9d33ec014bc3703e

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.