| from __future__ import annotations |
|
|
| import random |
| from collections import defaultdict |
|
|
| import numpy as np |
| from torch.utils.data import Sampler |
|
|
|
|
| class CrossSensorBatchSampler(Sampler): |
| """Batch sampler that guarantees k_cross (identity, finger) groups each |
| contribute ≥2 samples from *different* sensors per batch. |
| |
| Remaining slots are filled randomly from the full index pool. |
| |
| FVC records (single-sensor per identity, dataset starts with "fvc") are |
| excluded from anchor groups but are eligible for random fill slots. |
| """ |
|
|
| def __init__( |
| self, |
| records: list[dict], |
| batch_size: int, |
| k_cross: int = 16, |
| seed: int = 42, |
| ): |
| self.batch_size = batch_size |
| self.k_cross = k_cross |
| self.rng = random.Random(seed) |
|
|
| |
| raw: dict[tuple, dict[str, list[int]]] = defaultdict( |
| lambda: defaultdict(list) |
| ) |
| for i, rec in enumerate(records): |
| ds = rec.get("dataset", "") |
| if ds.startswith("fvc"): |
| continue |
| |
| |
| key = (rec["identity_id"], rec["finger_id"]) |
| raw[key][rec["sensor_id"]].append(i) |
|
|
| |
| self.eligible: list[dict[str, list[int]]] = [ |
| dict(sensor_map) |
| for sensor_map in raw.values() |
| if len(sensor_map) >= 2 |
| ] |
|
|
| self._all = np.arange(len(records), dtype=np.int64) |
| self._n_batches = max(1, len(records) // batch_size) |
|
|
| print( |
| f"CrossSensorBatchSampler: {len(self.eligible)} eligible anchor groups " |
| f"| k_cross={k_cross} anchored pairs/batch " |
| f"| {self._n_batches} batches/epoch" |
| ) |
|
|
| def __len__(self) -> int: |
| return self._n_batches |
|
|
| def __iter__(self): |
| rng = self.rng |
| eligible = self.eligible |
| k = min(self.k_cross, len(eligible)) |
|
|
| for _ in range(self._n_batches): |
| |
| anchor_groups = rng.sample(eligible, k) |
| anchor_set: set[int] = set() |
|
|
| for sensor_map in anchor_groups: |
| sensors = list(sensor_map.keys()) |
| s1, s2 = rng.sample(sensors, 2) |
| anchor_set.add(rng.choice(sensor_map[s1])) |
| anchor_set.add(rng.choice(sensor_map[s2])) |
|
|
| batch = list(anchor_set) |
|
|
| |
| remaining = self.batch_size - len(batch) |
| if remaining > 0: |
| mask = np.ones(len(self._all), dtype=bool) |
| mask[np.fromiter(anchor_set, dtype=np.int64)] = False |
| pool = self._all[mask].tolist() |
| fill_n = min(remaining, len(pool)) |
| batch.extend(rng.sample(pool, fill_n)) |
|
|
| rng.shuffle(batch) |
| yield batch |
|
|