Datasets:
Tasks:
Image Classification
Formats:
parquet
Size:
1K - 10K
Tags:
fish-recognition
fine-grained-recognition
biodiversity-informatics
benchmark
temporal-evaluation
License:
| #!/usr/bin/env python3 | |
| """Score canonical-key predictions on the fixed QT26-QC denominator.""" | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| from bootstrap import cluster_interval | |
| K_VALUES = (1, 5, 20) | |
| def read_tsv(path: Path) -> list[dict[str, str]]: | |
| with path.open("r", encoding="utf-8", newline="") as handle: | |
| return list(csv.DictReader(handle, delimiter="\t")) | |
| def normalize_predictions(row: dict[str, str], valid: set[str]) -> list[str]: | |
| normalized: list[str] = [] | |
| seen_valid: set[str] = set() | |
| for rank in range(1, 21): | |
| value = row.get(f"top{rank}", "").strip() | |
| if value in valid: | |
| if value in seen_valid: | |
| continue | |
| seen_valid.add(value) | |
| normalized.append(value or f"__MISSING_RANK_{rank}__") | |
| while len(normalized) < 20: | |
| normalized.append(f"__MISSING_AFTER_DEDUP_{len(normalized) + 1}__") | |
| return normalized[:20] | |
| def load_predictions( | |
| path: Path, public_ids: set[str], valid: set[str] | |
| ) -> dict[str, list[str]]: | |
| rows = read_tsv(path) | |
| result: dict[str, list[str]] = {} | |
| for row in rows: | |
| public_id = row.get("public_id", "") | |
| if public_id in result: | |
| raise ValueError(f"duplicate public_id: {public_id}") | |
| result[public_id] = normalize_predictions(row, valid) | |
| missing = public_ids - result.keys() | |
| extra = result.keys() - public_ids | |
| if missing or extra: | |
| raise ValueError(f"submission IDs differ: missing={len(missing)}, extra={len(extra)}") | |
| return result | |
| def score_one( | |
| truth_rows: list[dict[str, str]], predictions: dict[str, list[str]], replicates: int, seed: int | |
| ) -> tuple[dict[str, object], dict[int, np.ndarray]]: | |
| species = np.asarray([row["canonical_taxon_key"] for row in truth_rows]) | |
| hits: dict[int, np.ndarray] = {} | |
| metrics: dict[str, object] = {} | |
| for k in K_VALUES: | |
| vector = np.asarray( | |
| [ | |
| row["canonical_taxon_key"] in predictions[row["public_id"]][:k] | |
| for row in truth_rows | |
| ], | |
| dtype=np.float64, | |
| ) | |
| hits[k] = vector | |
| micro = cluster_interval(vector, species, replicates=replicates, seed=seed, macro=False) | |
| macro = cluster_interval(vector, species, replicates=replicates, seed=seed, macro=True) | |
| metrics[f"top{k}"] = { | |
| "query_micro": {"estimate": micro[0], "ci95": [micro[1], micro[2]]}, | |
| "species_macro": {"estimate": macro[0], "ci95": [macro[1], macro[2]]}, | |
| } | |
| return metrics, hits | |
| def main() -> int: | |
| root = Path(__file__).resolve().parents[1] | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("predictions", type=Path) | |
| parser.add_argument("--compare", type=Path) | |
| parser.add_argument("--roster", type=Path, default=root / "metadata" / "canonical-roster.tsv") | |
| parser.add_argument("--taxonomy", type=Path, default=root / "metadata" / "taxonomy-fishbase-25.04.tsv") | |
| parser.add_argument("--replicates", type=int, default=20_000) | |
| parser.add_argument("--seed", type=int, default=20260730) | |
| parser.add_argument("--output", type=Path) | |
| args = parser.parse_args() | |
| truth = read_tsv(args.roster) | |
| if len(truth) != 6_719 or len({row["canonical_taxon_key"] for row in truth}) != 3_121: | |
| raise ValueError("canonical roster denominator mismatch") | |
| taxonomy = read_tsv(args.taxonomy) | |
| valid = {row["canonical_taxon_key"] for row in taxonomy} | |
| ids = {row["public_id"] for row in truth} | |
| predictions = load_predictions(args.predictions, ids, valid) | |
| metrics, hits = score_one(truth, predictions, args.replicates, args.seed) | |
| output: dict[str, object] = { | |
| "status": "PASS", | |
| "queries": len(truth), | |
| "taxa": len({row["canonical_taxon_key"] for row in truth}), | |
| "bootstrap": { | |
| "unit": "target_species", | |
| "replicates": args.replicates, | |
| "seed": args.seed, | |
| }, | |
| "metrics": metrics, | |
| } | |
| if args.compare: | |
| baseline = load_predictions(args.compare, ids, valid) | |
| _, baseline_hits = score_one(truth, baseline, args.replicates, args.seed) | |
| current = hits[1].astype(bool) | |
| previous = baseline_hits[1].astype(bool) | |
| output["top1_transition"] = { | |
| "wrong_to_right": int(np.sum(~previous & current)), | |
| "right_to_wrong": int(np.sum(previous & ~current)), | |
| "net_correct": int(np.sum(current) - np.sum(previous)), | |
| } | |
| text = json.dumps(output, indent=2, sort_keys=True) + "\n" | |
| if args.output: | |
| args.output.write_text(text, encoding="utf-8") | |
| print(text, end="") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |