UFR-Fing / src /evaluation /erc.py
anbinh39's picture
Add files using upload-large-folder tool
dadf189 verified
Raw
History Blame Contribute Delete
2.09 kB
from __future__ import annotations
import numpy as np
def _safe_div(num: float, den: float) -> float:
return num / den if den > 0 else 0.0
def _compute_threshold_for_fmr(
impostor_scores: np.ndarray,
fmr_threshold: float,
) -> float:
# Accept if match_score >= threshold. We pick quantile so that expected FMR
# is approximately fmr_threshold.
q = float(np.clip(1.0 - fmr_threshold, 0.0, 1.0))
return float(np.quantile(impostor_scores, q))
def compute_erc(
quality_scores: np.ndarray,
match_scores: np.ndarray,
labels: np.ndarray,
fmr_threshold: float = 1e-4,
rejection_ratios: np.ndarray | None = None,
) -> tuple[np.ndarray, float]:
"""Compute FNMR under progressive rejection of lowest-quality samples."""
if rejection_ratios is None:
rejection_ratios = np.linspace(0.0, 0.5, 50)
quality_scores = np.asarray(quality_scores)
match_scores = np.asarray(match_scores)
labels = np.asarray(labels)
if not (quality_scores.shape == match_scores.shape == labels.shape):
raise ValueError("quality_scores, match_scores, and labels must have same shape")
sorted_idx = np.argsort(quality_scores)
fnmr_curve = []
for rr in rejection_ratios:
n_reject = int(rr * len(sorted_idx))
keep_mask = np.ones_like(labels, dtype=bool)
keep_mask[sorted_idx[:n_reject]] = False
kept_scores = match_scores[keep_mask]
kept_labels = labels[keep_mask]
impostor = kept_scores[kept_labels == 0]
genuine = kept_scores[kept_labels == 1]
if len(impostor) == 0 or len(genuine) == 0:
fnmr_curve.append(1.0)
continue
threshold = _compute_threshold_for_fmr(impostor, fmr_threshold)
fn = float((genuine < threshold).sum())
fnmr = _safe_div(fn, float(len(genuine)))
fnmr_curve.append(fnmr)
fnmr_curve_arr = np.asarray(fnmr_curve, dtype=np.float64)
auc = float(np.trapz(fnmr_curve_arr, rejection_ratios) / (rejection_ratios[-1] - rejection_ratios[0] + 1e-12))
return fnmr_curve_arr, auc