Datasets:
File size: 8,060 Bytes
a3206bd | 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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | """Score the released BioDCASE-2026 Task 5 evaluation clips with the deployed unanimous-3
agreement-gate ensemble and write the official submission .txt.
Pipeline (mirrors final/infer.py, but on the eval set instead of cached test):
1. Perch (1536-d) and BirdMAE (1024-d) embeddings are read from parquets produced by the
sibling repo's scripts/extract_fm_embeddings.py (frozen FMs, cannot run in this repo).
2. Harmonic (102-d) and background-whitened (257-d) features are computed here, directly
from each eval wav, with the SAME helpers the deployed members were trained on.
3. GatedEnsemble(bundle.pt).predict_proba(perch, harmonic, birdmae, bgwhiten) -> (N,9).
4. argmax -> class index 0..8 -> OFFICIAL 1-based predicted_species_id via framework.metadata.
5. write file_id,predicted_species_id rows (file_id without .wav).
Run with the sibling TF venv python (has torch + librosa + soundfile + pyarrow):
.../Cross-Domain-Mosquito-Species-Classification-Tensorflow/.venv/bin/python final/predict_eval.py
Add --self-test to first confirm the bundle reproduces dev BA_unseen ~= 0.3616 on cached test.
"""
import os, sys, glob, argparse, json
import numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path.insert(0, HERE) # final/ : ensemble_model, harmonic_features, bgwhiten_features, model
sys.path.insert(0, ROOT) # repo root : framework/
from framework.metadata import SPECIES_NAMES, SPECIES_ID_TO_NAME, DOMAIN_NAMES # noqa: E402
import harmonic_features as HF # noqa: E402
import bgwhiten_features as BG # noqa: E402
# class index 0..8 -> official 1-based species id, DERIVED from metadata (not a literal +1)
_NAME_TO_SPECIES_ID = {name: int(sid) for sid, name in SPECIES_ID_TO_NAME.items()}
IDX_TO_SPECIES_ID = [_NAME_TO_SPECIES_ID[SPECIES_NAMES[i]] for i in range(len(SPECIES_NAMES))]
EVAL_PARQUET_DIR = "/home/alaska/Projects/Cross-Domain-Mosquito-Species-Classification-Tensorflow/reports/fm_embeddings/eval"
DEV_BIRDMAE_PARQUET = "/home/alaska/Projects/Cross-Domain-Mosquito-Species-Classification-Tensorflow/reports/fm_embeddings/birdmae.parquet"
def read_ids(path):
with open(path) as fh:
return [ln.strip() for ln in fh if ln.strip()]
def load_parquet_emb(path, ids, dim):
"""Return (len(ids), dim) array aligned to `ids` by file_id; missing -> zeros (counted)."""
import pyarrow.parquet as pq
t = pq.read_table(path)
fid = np.array(t.column("file_id").to_pylist())
emb = t.column("embedding").combine_chunks().values.to_numpy().reshape(-1, dim).astype(np.float32)
idx = {f: i for i, f in enumerate(fid)}
out = np.zeros((len(ids), dim), np.float32)
missing = 0
for j, f in enumerate(ids):
i = idx.get(f)
if i is None:
missing += 1
else:
out[j] = emb[i]
return out, missing
def _feat_one(args):
"""Worker: load one wav once, return (harmonic102, bgwhiten257, ok)."""
audio_root, fid = args
try:
y = HF.load_wav(os.path.join(audio_root, f"{fid}.wav"))
return HF.harmonic_feature(y), BG.bgwhiten_feature(y), True
except Exception:
return np.zeros(HF.HARM_DIM, np.float32), np.zeros(BG.BGW_DIM, np.float32), False
def compute_handcrafted(ids, audio_root, workers):
"""Harmonic (N,102) + bgwhiten (N,257) for ids, in order. Returns (harm, bgw, n_failed)."""
harm = np.zeros((len(ids), HF.HARM_DIM), np.float32)
bgw = np.zeros((len(ids), BG.BGW_DIM), np.float32)
failed = 0
work = [(audio_root, f) for f in ids]
if workers and workers > 1:
from concurrent.futures import ProcessPoolExecutor
with ProcessPoolExecutor(max_workers=workers) as ex:
for j, (h, b, ok) in enumerate(ex.map(_feat_one, work, chunksize=32)):
harm[j], bgw[j] = h, b
if not ok:
failed += 1
if (j + 1) % 2000 == 0:
print(f" handcrafted features {j+1}/{len(ids)}", flush=True)
else:
for j, w in enumerate(work):
h, b, ok = _feat_one(w)
harm[j], bgw[j] = h, b
if not ok:
failed += 1
if (j + 1) % 2000 == 0:
print(f" handcrafted features {j+1}/{len(ids)}", flush=True)
return harm, bgw, failed
def self_test():
"""Confirm GatedEnsemble(bundle) reproduces the deployed dev BA_unseen (~0.3616) on cached test."""
from ensemble_model import GatedEnsemble
P = os.path.join(ROOT, "data/perch")
d = np.load(f"{P}/test.npz", allow_pickle=True)
perch = d["emb"].astype(np.float32)
yte = d["species"].astype(int); dte = d["domain"].astype(int)
fte = np.array([str(f) for f in d["file_id"]])
def by_fid(npz, key):
h = np.load(npz, allow_pickle=True)
idx = {str(f): i for i, f in enumerate(h["file_id"])}
return h[key].astype(np.float32)[np.array([idx[f] for f in fte])]
harm = by_fid(f"{P}/harmonic_test.npz", "harm")
bgw = by_fid(f"{P}/bgwhiten_test.npz", "bgw")
bird, miss = load_parquet_emb(DEV_BIRDMAE_PARQUET, list(fte), 1024)
sm = json.load(open(f"{ROOT}/data/metadata/split_summary.json"))
ud = {SPECIES_NAMES.index(k): DOMAIN_NAMES.index(v) for k, v in sm["unseen_domain_by_species"].items()}
unseen = np.array([dte[i] == ud.get(int(yte[i]), -1) for i in range(len(yte))])
ens = GatedEnsemble(os.path.join(HERE, "bundle.pt"))
probs = ens.predict_proba(perch, harm, bird, bgw)
pred = probs.argmax(1)
yy = yte[unseen]; pp = pred[unseen]
rec = [(pp[yy == c] == c).mean() for c in range(9) if (yy == c).any()]
ba = float(np.mean(rec))
print(f"[self-test] birdmae missing={miss} gated BA_unseen={ba:.4f} (expect ~0.3616)")
assert abs(ba - 0.3616) < 0.01, f"bundle gate mismatch: {ba:.4f} != 0.3616"
print("[self-test] OK\n")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--audio-root", default=os.path.join(ROOT, "eval"))
ap.add_argument("--ids", default=os.path.join(ROOT, "data/metadata_eval/Test_ids.txt"))
ap.add_argument("--parquet-dir", default=EVAL_PARQUET_DIR)
ap.add_argument("--bundle", default=os.path.join(HERE, "bundle.pt"))
ap.add_argument("--out", default=os.path.join(ROOT, "final_submission/architecture_1/predictions.txt"))
ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) - 1))
ap.add_argument("--self-test", action="store_true")
args = ap.parse_args()
if args.self_test:
self_test()
ids = read_ids(args.ids)
print(f"eval clips: {len(ids)}")
print("loading Perch + BirdMAE eval embeddings ...")
perch, miss_p = load_parquet_emb(os.path.join(args.parquet_dir, "perch.parquet"), ids, 1536)
bird, miss_b = load_parquet_emb(os.path.join(args.parquet_dir, "birdmae.parquet"), ids, 1024)
print(f" perch missing={miss_p} birdmae missing={miss_b}")
print(f"computing harmonic + bgwhiten features ({args.workers} workers) ...")
harm, bgw, failed = compute_handcrafted(ids, args.audio_root, args.workers)
print(f" handcrafted done; unreadable clips (zero-filled)={failed}")
print("running gated ensemble ...")
from ensemble_model import GatedEnsemble
ens = GatedEnsemble(args.bundle)
probs = ens.predict_proba(perch, harm, bird, bgw)
idx = probs.argmax(1)
species_id = np.array([IDX_TO_SPECIES_ID[i] for i in idx], dtype=int)
os.makedirs(os.path.dirname(args.out), exist_ok=True)
with open(args.out, "w") as fh:
fh.write("file_id,predicted_species_id\n")
for fid, sid in zip(ids, species_id):
fh.write(f"{fid},{sid}\n")
# report
counts = {int(s): int((species_id == s).sum()) for s in range(1, 10)}
print(f"\nwrote {len(ids)} rows -> {args.out}")
print("predicted_species_id histogram (1-based):")
for s in range(1, 10):
print(f" {s:>2} {SPECIES_ID_TO_NAME[str(s)]:<26} {counts[s]:>6} ({100*counts[s]/len(ids):.1f}%)")
if __name__ == "__main__":
main()
|