~ BirdCLEF 2026: Perch Embedding Probe ~
Wildlife species identification from Pantanal soundscapes
Table of Contents
Introduction
Initialization
Data Loading
Perch Label Mapping
Perch Inference
Prior Fusion
Out-of-Fold Meta-features
Embedding Probes
Test Inference
Submission
Introduction
BirdCLEF 2026 is a multi-label classification task: identify 234 wildlife species from 5-second segments of passive acoustic recordings in Brazil's Pantanal wetlands. Performance is measured by macro-averaged ROC-AUC over species that have at least one positive in the test ground truth. The submission notebook must run CPU-only within 90 minutes and without internet access.
Approach
Google's Perch v2 serves as a frozen feature extractor. No fine-tuning is performed; the 59 fully-labeled soundscape files provide enough signal to train lightweight linear probes on frozen embeddings in a few minutes on CPU.
Perch v2 (frozen)
|
+-- raw logits (234 classes, mapped from Perch's 14k-class vocab)
| |
| +-- site x hour Bayesian prior fusion
| |
| v
| fused logits (base scores)
|
+-- 1536-dim embeddings
|
v
PCA (64 dims) + per-class LogisticRegression probes
|
v
final = 0.6 * base + 0.4 * probe -> sigmoid -> submission.csv
Reference Shoutouts
Perch v2 Starter: Train + Infer by jaejohn
bc26-tensorflow-2-20-0 by kdmitrie
Initialization
The runtime environment is configured by installing TensorFlow 2.20, loading all libraries, and defining a single Settings class that centralises every path and hyperparameter. The random seed is fixed for reproducibility.
Environment
import os, platform, sys
print('Python :', sys.version)
print('OS :', platform.system(), platform.release())
print('CWD :', os.getcwd())
Python : 3.12.12 (main, Oct 10 2025, 08:52:57) [GCC 11.4.0]
OS : Linux 6.6.113+
CWD : /kaggle/working
Install
import subprocess, sys
from pathlib import Path
_WHL = Path('/kaggle/input/notebooks/kdmitrie/bc26-tensorflow-2-20-0/wheel')
if _WHL.exists():
subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', '--no-deps',
str(_WHL / 'tensorboard-2.20.0-py3-none-any.whl')], check=True)
subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', '--no-deps',
str(_WHL / 'tensorflow-2.20.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl')], check=True)
print('Installed TF 2.20.0 from Kaggle dataset wheels.')
else:
subprocess.run([sys.executable, '-m', 'pip', 'install', '-q',
'tensorflow==2.20.0', 'tensorboard==2.20.0'], check=True)
print('Installed TF 2.20.0 from PyPI.')
Installed TF 2.20.0 from Kaggle dataset wheels.
Libraries
import gc
import json
import random
import re
import warnings
from pathlib import Path
import numpy as np
import pandas as pd
import soundfile as sf
import tensorflow as tf
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import GroupKFold
from sklearn.preprocessing import StandardScaler
from tqdm.auto import tqdm
Assistant
这是一个非常精妙的方案,和之前讨论的 SED 方案走的是完全不同的技术路线。让我拆解分析。
核心思路:一行总结
不训练任何神经网络。利用 Google Perch v2 预训练模型作为冻结特征提取器,只训练轻量线性探针(Logistic Regression),配合贝叶斯先验融合,在 CPU 上几分钟跑完全部推理。
Hypothesis: V2S needs more epochs/data to catch up, or its pretraining features are less aligned with this val set.
Best V2S: 0.7575 vs Best B0: 0.8141 (-0.057)
🚫
Discovery 5: Rating Filter Hurts
v21 applied a rating ≥ 3 quality filter to training data, reducing dataset size. Result: 0.7289 — worse than unfiltered v9 (0.7755). BirdCLEF data with lower ratings still contains useful signal; aggressive filtering removes too many examples.
v9 → v21: 0.7755 → 0.7289 (-0.047)
⚠️
Discovery 6: nPCEN (no PCEN) Hurts Significantly
v26 ablated PCEN normalization in favor of standard mel normalization. Early stopped at ep3 with only 0.7262 — the worst B0 result. PCEN is load-bearing for the model's ability to generalize across soundscape recording conditions.
v9 → v26: 0.7755 → 0.7262 (-0.049) · early stop ep3
🔬
Discovery 7: Perch-Augmented Training Didn't Help
v23 used Perch outputs to augment the training data pipeline. Early stopped at ep4 with 0.7366 — below baseline. Hypothesis: Perch augmentation introduces domain mismatch or the augmentation quality was insufficient. Perch is better used as a teacher for soft labels (v24 approach) than as a training augmenter.
v9 → v23: 0.7755 → 0.7366 (-0.039) · early stop ep4
🎯
Discovery 8: LR=5e-4 Critical for V2S
V2S-v2 used LR=3e-4 → underfitting (0.7113). V2S-v3 corrected to LR=5e-4 → already at 0.7575 at ep2. For larger backbones, the same LR as B0 is needed to avoid underfitting — conservative LR scheduling is not always better.
V2S-v2 (LR=3e-4) → V2S-v3 (LR=5e-4): +0.046 at ep2
🔧 Technique Effectiveness Matrix
Technique Effect on Val AUC Evidence Verdict
Soft Pseudo Labels (r5 KD ×10) +0.039 vs no-pseudo v9 (0.7755) → v24 (0.8141) ✓ Keep — critical
Combined r4+r5 Pseudo (6601 clips) +? (early) v30 ep2=0.7871 > v27 ep2=0.7598 ⏳ Promising — monitor
ASL Loss (γ−=4, γ+=0) +0.02–0.03 vs BCE v9-asl vs v12-bce ✓ Keep — standard
Dual Loss (clip + frame) slight + v28 uses w=0.5/0.5 ✓ Keep
Hard Pseudo Soundscapes (×5) +0.01–0.02 v24/v28 extra_soundscape_csv ✓ Keep
Circular Shift Augmentation +0.005–0.01 v28 circ_shift_prob=0.5 ✓ Keep
Strong SpecAugment (time+freq mask) +0.005 v28 vs v24 ✓ Keep
Mixup (α=0.5) neutral used in v27/v28 → Keep (no harm)
GEM Frequency Pooling + all experiments use gem=True ✓ Keep — standard
Rating ≥ 3 Filter -0.047 v9 → v21 ✗ Drop — hurts
nPCEN (remove PCEN) -0.049 v9 → v26 · early stop ep3 ✗ Drop — critical failure
Perch-Augmented Training -0.039 v9 → v23 · early stop ep4 ✗ Drop — wrong usage
V2S Backbone (22.4M) -0.06 (currently) B0 0.8141 vs best V2S 0.7575 ⚠️ Monitor — needs more epochs
V2S LR=5e-4 (vs 3e-4) +0.046 V2S-v2 → V2S-v3 at ep2 ✓ Fixed — must use 5e-4
📅 Experiment Timeline
Wave 0 · Pre-2026-03-17
B0 Baseline Sweep (v9–v22)
Established ASL loss, GEM pooling, dual loss as core components. Rating filter (v21) and nPCEN (v26) ruled out. Best: v9-asl = 0.7755 → LB 0.892.
Wave 1 · 2026-03-17
V2S Backbone Exploration + Perch Augmentation
V2S-v1/v2 underperformed. v23 Perch-augmentation failed. Key insight: V2S needs LR=5e-4, not 3e-4.
Wave 2 · 2026-03-18
🚀 Breakthrough: Soft Pseudo Labels (v24)
v24 (B0 + r5 soft KD ×10) hit 0.8141 — +0.039 over baseline. Confirmed pseudo label distillation as the primary lever. v24 best = 0.8141.
Wave 3 · 2026-03-19 (now)
Kitchen-Sink + Combined Pseudo + V2S Fix
v27 (r5 soft KD alone): 0.7804. v28 (full kitchen-sink): 0.8053 and climbing. v30 (combined r4r5, 6601 clips): ep2=0.7871, very early. V2S-v3 (LR fixed, full kitchen-sink): ep2=0.7575, converging slower.
Planned · after Wave 3
4-Fold Grand Combo Training
B0 + combined_r4r5 + all proven methods → 4-fold cross-val for ensemble. Config: sed-b0-4fold-grand-v1-fold{0,1,2,3}.yaml. Launch with: bash scripts/launch_4fold_grand.sh 0/1
⚙️ Proven Best Formula (v28 template)
Model
Backbone: tf_efficientnet_b0.ns_jft_in1k
GEM Pool: p_init=3.0
Dropout: 0.1
In channels: 3
Training
Loss: ASL (γ−=4, γ+=0, clip=0.05)
LR: 5e-4 → cosine, warmup=3ep
Batch: 32, Epochs: 35
Mixup: α=0.5, circ_shift: p=0.5
Data
Labeled audio: 3 clips/file
Soundscape labels: ×5 oversample
Soft pseudo (r5, 1176 clips): ×10
Hard pseudo (r5, 1168 clips): extra_soundscape_csv
(v30/4fold: combined r4r5, 6601 clips × 10)
Augmentation
SpecAugment: time×2 (15%), freq×2 (40)
Noise: level=0.005
Gain: [0.7, 1.3]
Background noise: soundscape dir
✅ Conclusions & Next Steps
What to do next
Wait for v28, v27, v30 to finish → run model soup → compare final val AUC to confirm 4-fold formula
If v30 (r4r5) surpasses v24 (r5-only) at peak, adopt combined_pseudo_r4r5 as the 4-fold base
Launch 4-fold B0 Grand Combo: bash scripts/launch_4fold_grand.sh 0 (GPU0) and bash scripts/launch_4fold_grand.sh 1 (GPU1)
Run watchdog-triggered v31 (V2S + combined r4r5) after v27 finishes to test V2S ceiling with best data
After 4-fold complete: run model soup per fold → ensemble with Perch probe in 4fold_grand_ensemble.ipynb
Target final ensemble: 4×B0 soups (w=1.5) + 5×B0 singles (w=1.0) + Perch=0.45 / SED=0.55 VLOM
Submit when individual model holdout AUC > 0.9193 (current benchmark threshold)
Key Risk: V2S val AUC is consistently below B0 on this validation set despite having 3.6× more parameters. Possible causes: (1) shorter warmup relative to model size, (2) slower convergence needing 15+ epochs, (3) this soundscape val set happens to favor B0's feature space. Monitor V2S-v3 through ep6+ before deciding whether to include V2S in the final ensemble.
Generated 2026-03-19 · BirdCLEF 2026 · claude-sonnet-4-6
warnings.filterwarnings('ignore')
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
os.environ['CUDA_VISIBLE_DEVICES'] = '' # force CPU
tf.experimental.numpy.experimental_enable_numpy_behavior()
print('TensorFlow :', tf.version)
print('NumPy :', np.version)
print('Pandas :', pd.version)
TensorFlow : 2.20.0
NumPy : 2.0.2
Pandas : 2.3.3
Settings
Settings holds every path and hyperparameter in one place.
Cache auto-detection: the Perch inference cache is checked in candidate directories in order; the first hit wins. Compatible with V1 cache format (full_perch_meta.parquet + full_perch_arrays.npz with keys scores_full_raw / emb_full). The OOF is always recomputed from the cached embeddings using site-level folds.
seed_everything(CFG.SEED)
Data Loading
The four metadata files are loaded and the 739 exact duplicate rows are stripped from train_soundscapes_labels.csv. Multi-species segments are aggregated into a union label list and the multi-hot label matrix Y_SC is built over all soundscape rows. Only the 59 fully-labeled files, those with all 12 windows annotated, are used for OOF and probe training.
Y_SC = np.zeros((len(sc_clean), N_CLASSES), dtype=np.uint8)
for i, labels in enumerate(sc_clean['label_list']):
for lbl in labels:
if lbl in label_to_idx:
Y_SC[i, label_to_idx[lbl]] = 1
print(f'Fully-labeled files : {len(full_files)}')
print(f'Trusted windows : {len(full_truth)}')
print(f'Active classes : {int((Y_FULL_TRUTH.sum(axis=0) > 0).sum())}')
Fully-labeled files : 59
Trusted windows : 708
Active classes : 71
Perch Label Mapping
Perch v2 was trained on 14,795 classes identified by scientific name. Each of the 234 competition species is mapped to its Perch class index by joining on scientific_name. Species with no direct match are left unmapped or, for unmapped amphibians, assigned a genus-level proxy from any Perch class sharing the same genus.
print(f'Mapped : {MAPPED_MASK.sum()} / {N_CLASSES}')
print(f'Unmapped : {(~MAPPED_MASK).sum()}')
Loading Perch model...
2026-03-23 01:42:13.996375: E external/local_xla/xla/stream_executor/cuda/cuda_platform.cc:51] failed call to cuInit: INTERNAL: CUDA error: Failed call to cuInit: UNKNOWN ERROR (303)
Perch loaded.
Mapped : 203 / 234
Unmapped : 31
Class Type Indices
Species are split into texture classes (Amphibia, Insecta) and event classes (everything else). The distinction drives different prior fusion lambdas: frogs and insects are location-determined recurring textures, whereas birds are sparse acoustic events.
CLASS_NAME_MAP = taxonomy_.set_index('primary_label')['class_name'].to_dict()
TEXTURE_TAXA = {'Amphibia', 'Insecta'}
ACTIVE_CLASSES = [PRIMARY_LABELS[i] for i in np.where(Y_SC.sum(axis=0) > 0)[0]]
idx_active_texture = np.array(
[label_to_idx[c] for c in ACTIVE_CLASSES if CLASS_NAME_MAP.get(c) in TEXTURE_TAXA],
dtype=np.int32
)
idx_active_event = np.array(
[label_to_idx[c] for c in ACTIVE_CLASSES if CLASS_NAME_MAP.get(c) not in TEXTURE_TAXA],
dtype=np.int32
)
idx_mapped_active_texture = idx_active_texture[MAPPED_MASK[idx_active_texture]]
idx_mapped_active_event = idx_active_event[MAPPED_MASK[idx_active_event]]
idx_unmapped_active_texture = idx_active_texture[~MAPPED_MASK[idx_active_texture]]
idx_unmapped_active_event = idx_active_event[~MAPPED_MASK[idx_active_event]]
idx_unmapped_inactive = np.array(
[i for i in UNMAPPED_POS if PRIMARY_LABELS[i] not in ACTIVE_CLASSES], dtype=np.int32
)
print(f'Active texture classes : {len(idx_active_texture)}')
print(f'Active event classes : {len(idx_active_event)}')
print(f'Unmapped inactive : {len(idx_unmapped_inactive)}')
Active texture classes : 42
Active event classes : 33
Unmapped inactive : 2
Amphibian Genus Proxies
For unmapped amphibians that are not insect sonotypes, Perch's label list is searched for any class sharing the same genus. The maximum logit across genus matches serves as a proxy score, which is better than leaving those columns at zero.
proxy_map = {}
for _, row in unmapped_non_sonotype.iterrows():
genus = str(row['scientific_name']).split()[0]
hits = bc_labels[
bc_labels['scientific_name'].str.match(rf'^{re.escape(genus)}\s', na=False)
]
if len(hits) > 0:
proxy_map[str(row['primary_label'])] = hits['bc_index'].astype(int).tolist()
[EXPAND] Use genus proxy for ALL unmapped active classes, not just Amphibia
Amphibia, Aves, Reptilia, Mammalia — any unmapped species with a genus hit in Perch
ACTIVE_LABELS = set(PRIMARY_LABELS[i] for i in np.where(Y_SC.sum(axis=0) > 0)[0])
SELECTED_PROXY_TARGETS = sorted([
t for t in proxy_map
if t in ACTIVE_LABELS # only species that appear in training data
])
selected_proxy_pos = np.array([label_to_idx[c] for c in SELECTED_PROXY_TARGETS], dtype=np.int32)
selected_proxy_pos_to_bc = {
label_to_idx[t]: np.array(proxy_map[t], dtype=np.int32) for t in SELECTED_PROXY_TARGETS
}
Break down by class type for logging
proxy_by_class = {}
for t in SELECTED_PROXY_TARGETS:
cn = CLASS_NAME_MAP.get(t, 'Unknown')
proxy_by_class.setdefault(cn, []).append(t)
for cn, targets in sorted(proxy_by_class.items()):
print(f' Proxy [{cn}]: {len(targets)} targets — {targets}')
print(f'Total proxy targets : {len(SELECTED_PROXY_TARGETS)} (was 3 Amphibia only)')
print(f'Proxy texture classes: {len(idx_selected_proxy_active_texture)}')
print(f'Prior-only texture : {len(idx_selected_prioronly_active_texture)}')
print(f'Prior-only event : {len(idx_selected_prioronly_active_event)}')
Proxy [Amphibia]: 2 targets — ['1491113', '25073']
Proxy [Mammalia]: 1 targets — ['516975']
Proxy [Reptilia]: 1 targets — ['116570']
Total proxy targets : 4 (was 3 Amphibia only)
Proxy texture classes: 2
Prior-only texture : 25
Prior-only event : 0
Perch Inference
The 59 fully-labeled training soundscapes are run through Perch to obtain raw logits and 1536-dimensional embeddings. If a compatible cache exists (V1 format: full_perch_meta.parquet + full_perch_arrays.npz), it is loaded directly and inference is skipped to save runtime.
Audio and Inference Helpers
def read_soundscape_60s(path):
y, sr = sf.read(path, dtype='float32', always_2d=False)
if y.ndim == 2:
y = y.mean(axis=1)
if len(y) < CFG.FILE_SAMPLES:
y = np.pad(y, (0, CFG.FILE_SAMPLES - len(y)))
return y[:CFG.FILE_SAMPLES]
def infer_perch_batch(paths, verbose=True):
paths = [Path(p) for p in paths]
n_files = len(paths)
n_rows = n_files * CFG.N_WINDOWS
print(f'scores_full_raw : {scores_full_raw.shape} {scores_full_raw.dtype}')
print(f'emb_full : {emb_full.shape} {emb_full.dtype}')
print(f'Y_FULL : {Y_FULL.shape}')
Loading Perch cache from: /kaggle/input/datasets/jaejohn/perch-meta
scores_full_raw : (708, 234) float32
emb_full : (708, 1536) float32
Y_FULL : (708, 234)
Prior Fusion
Raw Perch logits reflect global species probabilities from pretraining but ignore the deployment context. Bayesian prior tables are built from the soundscape metadata, covering site prevalence, hour-of-day prevalence, and their joint prevalence, each shrunk toward the global mean. The resulting logit offsets are added to the raw scores with class-type-specific weights.
site_keys = sorted(prior_df['site'].dropna().astype(str).unique())
hour_keys = sorted(prior_df['hour_utc'].dropna().astype(int).unique())
site_to_i, site_n, site_p = {}, [], []
for s in site_keys:
mask = prior_df['site'].astype(str).values == s
site_to_i[s] = len(site_n)
site_n.append(mask.sum())
site_p.append(Y_prior[mask].mean(axis=0))
site_n = np.array(site_n, dtype=np.float32)
site_p = np.stack(site_p).astype(np.float32) if site_p else np.zeros((0, Y_prior.shape[1]), np.float32)
hour_to_i, hour_n, hour_p = {}, [], []
for h in hour_keys:
mask = prior_df['hour_utc'].astype(int).values == h
hour_to_i[h] = len(hour_n)
hour_n.append(mask.sum())
hour_p.append(Y_prior[mask].mean(axis=0))
hour_n = np.array(hour_n, dtype=np.float32)
hour_p = np.stack(hour_p).astype(np.float32) if hour_p else np.zeros((0, Y_prior.shape[1]), np.float32)
sh_to_i, sh_n_list, sh_p_list = {}, [], []
for (s, h), idx in prior_df.groupby(['site', 'hour_utc']).groups.items():
sh_to_i[(str(s), int(h))] = len(sh_n_list)
idx = np.array(list(idx))
sh_n_list.append(len(idx))
sh_p_list.append(Y_prior[idx].mean(axis=0))
sh_n = np.array(sh_n_list, dtype=np.float32)
sh_p = np.stack(sh_p_list).astype(np.float32) if sh_p_list else np.zeros((0, Y_prior.shape[1]), np.float32)
return dict(
global_p=global_p,
site_to_i=site_to_i, site_n=site_n, site_p=site_p,
hour_to_i=hour_to_i, hour_n=hour_n, hour_p=hour_p,
sh_to_i=sh_to_i, sh_n=sh_n, sh_p=sh_p,
)
Prior Logits and Score Fusion
def prior_logits(sites, hours, tables, eps=1e-4):
n = len(sites)
p = np.repeat(tables['global_p'][None, :], n, axis=0).astype(np.float32, copy=True)
code
si = np.fromiter((tables['site_to_i'].get(str(s), -1) for s in sites), np.int32, n)
hi = np.fromiter(
(tables['hour_to_i'].get(int(h), -1) if int(h) >= 0 else -1 for h in hours),
np.int32, n
)
shi = np.fromiter(
(tables['sh_to_i'].get((str(s), int(h)), -1) if int(h) >= 0 else -1
for s, h in zip(sites, hours)),
np.int32, n
)
valid = hi >= 0
if valid.any():
nh = tables['hour_n'][hi[valid]][:, None]
p[valid] = nh / (nh + 8.0) * tables['hour_p'][hi[valid]] + (1.0 - nh / (nh + 8.0)) * p[valid]
valid = si >= 0
if valid.any():
ns = tables['site_n'][si[valid]][:, None]
p[valid] = ns / (ns + 8.0) * tables['site_p'][si[valid]] + (1.0 - ns / (ns + 8.0)) * p[valid]
valid = shi >= 0
if valid.any():
nsh = tables['sh_n'][shi[valid]][:, None]
p[valid] = nsh / (nsh + 4.0) * tables['sh_p'][shi[valid]] + (1.0 - nsh / (nsh + 4.0)) * p[valid]
np.clip(p, eps, 1.0 - eps, out=p)
return (np.log(p) - np.log1p(-p)).astype(np.float32)
def smooth_cols(scores, cols, alpha=0.35):
"""Temporal smoothing: blend each window with its neighbours within the same file."""
if alpha <= 0 or len(cols) == 0:
return scores.copy()
s = scores.copy()
view = s.reshape(-1, CFG.N_WINDOWS, s.shape[1])
x = view[:, :, cols]
prev = np.concatenate([x[:, :1, :], x[:, :-1, :]], axis=1)
nxt = np.concatenate([x[:, 1:, :], x[:, -1:, :]], axis=1)
view[:, :, cols] = (1.0 - alpha) * x + 0.5 * alpha * (prev + nxt)
return s
Out-of-Fold Meta-features
The embedding probes take fused scores as input features, so those scores must be produced out-of-fold to avoid data leakage. The prior table for each validation fold is fitted on training folds only, excluding the entire validation site. GroupKFold(5) is used with groups defined by site, ensuring no site contributes to both training and validation in the same fold.
print(f'OOF baseline AUC (prior fusion only): {macro_auc(Y_FULL, oof_base):.6f}')
OOF baseline AUC (prior fusion only): 0.487292
Embedding Probes
For each class with enough positive examples, a logistic regression probe is trained on 64-dimensional PCA embeddings augmented with sequential meta-features: the raw Perch logit, the OOF prior logit, the OOF fused score, and the previous/next/mean/max fused scores within the same 60-second file. Probes trained on these honest OOF meta-features generalise better to unseen sites than probes trained on in-fold fused scores.
print(f'PCA components : {n_comp}')
print(f'Explained var : {emb_pca.explained_variance_ratio_.sum():.4f}')
[NEW] Compute class prototypes in PCA space — inspired by ProtoSSM
prototype[c] = mean(Z[Y[:,c]==1]) for each class with enough positives
CLASS_PROTOTYPES = {}
for ci in range(N_CLASSES):
pos_mask = Y_FULL[:, ci] == 1
if pos_mask.sum() >= CFG.PROBE_MIN_POS:
CLASS_PROTOTYPES[ci] = Z_FULL[pos_mask].mean(axis=0)
print(f'Class prototypes computed: {len(CLASS_PROTOTYPES)} classes')
[NEW] Build family-level index mapping from taxonomy
Used to compute family-mean score as an additional feature
FAMILY_MAP = taxonomy_.set_index('primary_label')['class_name'].to_dict()
FAMILY_GROUPS = {}
for ci, label in enumerate(PRIMARY_LABELS):
family = FAMILY_MAP.get(label, 'Unknown')
FAMILY_GROUPS.setdefault(family, []).append(ci)
Pre-compute per-family index arrays for fast slicing
FAMILY_IDX_MAP = {fam: np.array(idxs, dtype=np.int32)
for fam, idxs in FAMILY_GROUPS.items()}
Map each class index to its family name
CLASS_FAMILY = {ci: FAMILY_MAP.get(label, 'Unknown')
for ci, label in enumerate(PRIMARY_LABELS)}
print(f'Family groups: {len(FAMILY_GROUPS)} — {sorted(FAMILY_GROUPS.keys())}')
PCA components : 32
Explained var : 0.6980
Class prototypes computed: 52 classes
Family groups: 5 — ['Amphibia', 'Aves', 'Insecta', 'Mammalia', 'Reptilia']
Probe Parameter Selection
In train mode, a small grid is swept to find the best PCA dimension, minimum positives threshold, regularisation strength, and blending weight. In submit mode, the frozen values from Settings are used directly.
for cls_idx in tqdm(probe_idx, desc='Training probes'):
y = Y_FULL[:, cls_idx]
if y.sum() == 0 or y.sum() == len(y):
continue
code
# [NEW] Prototype cosine similarity feature
proto_sim = None
if cls_idx in CLASS_PROTOTYPES:
proto_sim = cosine_sim_to_prototype(Z_FULL, CLASS_PROTOTYPES[cls_idx])
# [NEW] Family-level mean score feature
family_name = CLASS_FAMILY.get(cls_idx, 'Unknown')
family_idxs = FAMILY_IDX_MAP.get(family_name, np.array([]))
# Exclude current class from family mean to avoid leakage
other_family = family_idxs[family_idxs != cls_idx]
family_mean = oof_base[:, other_family].mean(axis=1) if len(other_family) > 0 else None
X = build_class_features(
Z_FULL,
raw_col=scores_full_raw[:, cls_idx],
prior_col=oof_prior[:, cls_idx],
base_col=oof_base[:, cls_idx],
proto_sim_col=proto_sim,
family_mean_col=family_mean,
)
clf = LogisticRegression(
C=CFG.PROBE_C, max_iter=400, solver='liblinear', class_weight='balanced'
)
clf.fit(X, y)
probe_models[cls_idx] = clf
print(f'Probe models trained : {len(probe_models)} / {N_CLASSES} classes')
Probe models trained : 52 / 234 classes
Test Inference
With all components trained, the prior tables are re-fitted on the full labeled dataset with no fold exclusion. The complete pipeline, Perch inference, prior fusion, PCA projection, and probe blending, is then applied to the test soundscapes.
final_scores = test_base.copy()
for cls_idx, clf in tqdm(probe_models.items(), desc='Applying probes'):
# [NEW] Same prototype + family features as training
proto_sim = None
if cls_idx in CLASS_PROTOTYPES:
proto_sim = cosine_sim_to_prototype(Z_TEST, CLASS_PROTOTYPES[cls_idx])
print(f'final_scores : {final_scores.shape}')
print(f'Score range : {final_scores.min():.3f} to {final_scores.max():.3f}')
No test soundscapes found. Dry-run on 20 train files.
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
I0000 00:00:1774230147.425418 65 device_compiler.h:196] Compiled cluster using XLA! This line is logged at most once for the lifetime of the process.
final_scores : (240, 234)
Score range : -25.162 to 15.932
Submission
Logits are converted to probabilities via sigmoid. The output shape and integrity are validated against the expected row count and column order before submission.csv is written.