mir_eval developer on retainer: onset evaluation F-measure collapses when onset list is empty — mir_eval.onset.f_measure divides zero by zero on empty ref/est arrays; NumPy RuntimeWarning NaN propagates to aggregate metrics — guard empty arrays fix — 3 weeks — mir_eval developer on monthly retainer

mir_eval 0.7 (craffel/mir_eval) • Python 3.9; music information retrieval evaluation library; mir_eval.onset.f_measure(reference_onsets, estimated_onsets, window=0.05) • MIR system evaluation pipeline (2,400 mixed music + silence/speech-only tracks/month; onset detector evaluated against annotated ground truth; 15% of corpus is all-silence or speech-only tracks — onset detector correctly produces empty estimated array; ground-truth annotation also empty; mir_eval.onset.f_measure(np.array([]), np.array([])) computes precision = 0/0 and recall = 0/0; NumPy RuntimeWarning: invalid value encountered in double_scalars; both values NaN; F-measure NaN; numpy.mean() over per-track F-measures collapses aggregate to NaN whenever any track is silence); fix: guard empty arrays before mir_eval call — both empty → F=1.0 (perfect agreement); one empty → F=0.0 (complete disagreement); NaN rate 15% → 0%; aggregate F-measure reliable across all 2,400 tracks; 1.5h retainer engagement

Northfield MirEval Ltd. operated an automated evaluation pipeline for a commercial onset detection system. Each month the pipeline evaluated the system on 2,400 tracks drawn from a mixed corpus: 85% music tracks (rock, classical, jazz, electronic) and 15% all-silence or speech-only tracks (intro/outro silence segments and spoken-word podcast clips included to test false-positive suppression). For each track the pipeline ran the onset detector, compared the resulting onset times against a hand-annotated ground-truth file using mir_eval.onset.f_measure with a 50ms tolerance window, and computed the mean F-measure across all tracks as the headline evaluation metric. The pipeline had been running for eight months without issues on the original 85% music-only corpus. After the corpus was expanded to include the silence and speech-only tracks, the monthly mean F-measure began returning NaN rather than a numeric score. The engineering team initially assumed a data ingestion error — perhaps malformed annotation files — but all annotation files parsed without errors. A mir_eval retainer developer was engaged to identify why the aggregate metric had become unreliable.

The developer’s investigation began by running the pipeline with per-track logging enabled, writing each track’s individual F-measure to a CSV before the aggregate mean was computed. The CSV immediately revealed the pattern: every silence and speech-only track produced an F-measure of NaN, while all music tracks produced valid numeric scores. For the silence tracks the onset detector correctly produced an empty estimated onset array (np.array([])), and the ground-truth annotation file was also empty (no annotated onsets). Calling mir_eval.onset.f_measure(np.array([]), np.array([]), window=0.05) in isolation reproduced the problem: the function printed a NumPy RuntimeWarning: invalid value encountered in double_scalars and returned NaN. The root cause was arithmetic: mir_eval computes true positives (TP) by counting matched onset pairs within the tolerance window, false positives (FP) as unmatched estimated onsets, and false negatives (FN) as unmatched reference onsets. With both arrays empty, TP = 0, FP = 0, FN = 0. Precision = TP / (TP + FP) = 0 / 0, and recall = TP / (TP + FN) = 0 / 0 — both are 0 ÷ 0 = NaN in floating-point. The F-measure then propagates the NaN through 2 × NaN × NaN / (NaN + NaN) = NaN. When numpy.mean() aggregated the 2,400 per-track scores, any single NaN in the array caused the mean to return NaN. The fix was a three-line guard clause added before every mir_eval.onset.f_measure call: if both arrays are empty return 1.0 (the detector and annotator agree that there are no onsets — a correct result that deserves a perfect score); if exactly one array is empty return 0.0 (complete disagreement). After the fix the pipeline replaced all 360 NaN values with 1.0 for silence tracks, and switched the aggregate from numpy.mean to numpy.nanmean as a belt-and-suspenders measure, producing a reliable mean F-measure of 0.883 for the full 2,400-track corpus.

The guard clause and the corrected aggregation pattern:

# Northfield MirEval Ltd. — mir_eval 0.7 empty-array NaN diagnostic
# mir_eval 0.7; Python 3.9
# Deployment: onset evaluation pipeline, 2,400 tracks/month
# Problem: mir_eval.onset.f_measure([], []) returns NaN; propagates to mean
# Fix: guard empty arrays; both empty → F=1.0; one empty → F=0.0

import numpy as np
import mir_eval


# ── BUGGY implementation ───────────────────────────────────────────────────

def evaluate_onset_buggy(ref: np.ndarray, est: np.ndarray,
                         window: float = 0.05) -> float:
    """
    Bug: no guard for empty arrays.
    mir_eval.onset.f_measure([], []) = 0/0 → NaN.
    numpy.mean() propagates NaN to aggregate across all tracks.
    """
    _, _, f = mir_eval.onset.f_measure(ref, est, window=window)
    return f                                       # may be NaN


def aggregate_buggy(per_track_f: list) -> float:
    return float(np.mean(per_track_f))             # NaN if any element is NaN


# ── FIXED implementation ───────────────────────────────────────────────────

def evaluate_onset_fixed(ref: np.ndarray, est: np.ndarray,
                         window: float = 0.05) -> float:
    """
    Fix: guard empty arrays before mir_eval call.
    Both empty  → F=1.0 (detector and annotator agree: no onsets present).
    One empty   → F=0.0 (one side has onsets, other has none: total mismatch).
    Non-empty   → delegate to mir_eval as normal.
    """
    if len(ref) == 0 and len(est) == 0:
        return 1.0                                 # perfect agreement on silence
    if len(ref) == 0 or len(est) == 0:
        return 0.0                                 # complete disagreement

    _, _, f = mir_eval.onset.f_measure(ref, est, window=window)
    return float(f)


def aggregate_fixed(per_track_f: list) -> float:
    return float(np.nanmean(per_track_f))          # skip NaN if any slip through


# ── Demonstration ──────────────────────────────────────────────────────────

TRACKS = [
    # (description, ref_onsets_sec, est_onsets_sec)
    ("music track, good detection",
     np.array([0.5, 1.2, 2.0, 2.8]),
     np.array([0.51, 1.19, 1.98, 2.82])),
    ("music track, missed onset",
     np.array([0.5, 1.2, 2.0, 2.8]),
     np.array([0.51, 1.19, 2.82])),          # 2.0s onset missed
    ("silence track, both empty",
     np.array([]),
     np.array([])),                           # all-silence: no onsets
    ("speech-only track, detector correct",
     np.array([]),
     np.array([])),                           # no music onsets
    ("silence track, false positive",
     np.array([]),
     np.array([1.3, 2.7])),                  # detector fired on silence
]

print(f"{'Track':<45} {'Buggy F':>10} {'Fixed F':>10}")
print("-" * 67)
buggy_scores, fixed_scores = [], []
for desc, ref, est in TRACKS:
    import warnings
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")        # suppress NaN RuntimeWarning
        b = evaluate_onset_buggy(ref, est)
    f = evaluate_onset_fixed(ref, est)
    buggy_scores.append(b)
    fixed_scores.append(f)
    print(f"{desc:<45} {b:>10.4f} {f:>10.4f}")

print("-" * 67)
import warnings
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    buggy_agg = aggregate_buggy(buggy_scores)
fixed_agg  = aggregate_fixed(fixed_scores)
print(f"{'Aggregate mean F':<45} {buggy_agg:>10.4f} {fixed_agg:>10.4f}")
print()
print("Root cause: mir_eval.onset.f_measure([], []) = 0/0 = NaN")
print("  NumPy RuntimeWarning: invalid value encountered in double_scalars")
print("  NaN propagates through numpy.mean() to aggregate metric")
print("  15% silence/speech-only tracks → 100% NaN aggregate")
print()
print("Fix: guard empty arrays before mir_eval call")
print("  Both empty  → F = 1.0 (detector and annotator agree: no onsets)")
print("  One empty   → F = 0.0 (complete disagreement)")
print("  Use numpy.nanmean for aggregation (belt-and-suspenders)")
print("  NaN rate: 15% → 0%; aggregate F-measure reliable; 1.5h")

Why both-empty deserves F=1.0 and one-empty deserves F=0.0, and how to handle the tolerance-window edge case

The semantically correct F-measure for the two empty-array cases follows directly from the definitions of precision and recall in information retrieval. When both reference_onsets and estimated_onsets are empty, there are no ground-truth onsets in the track (confirmed by the annotator) and the detector has correctly predicted none. This is a true-negative scenario: the system did not fire on a silent or speech-only segment, which is the desired behavior. Scoring this as F=1.0 is correct because the system’s output (empty) exactly matches the ground truth (empty). Scoring it as NaN, 0.0, or skipping it entirely would unfairly penalize the system for silence tracks and inflate the perceived difficulty of the corpus. When reference_onsets is non-empty but estimated_onsets is empty, the system missed all annotated onsets: recall = 0, precision is undefined but conventionally taken as 1.0 (zero false positives) — but recall = 0 drives F to 0.0. When reference_onsets is empty but estimated_onsets is non-empty, the system fired on a silence track: precision = 0, recall is undefined — F = 0.0. Both asymmetric cases are correctly handled by returning 0.0. After implementing the guard, the Northfield team audited the tolerance-window setting and confirmed that 50ms was appropriate for their corpus (rock and electronic music with sharp transients); they also added a per-category breakdown reporting separate mean F-measures for music, silence, and speech-only subsets, allowing them to track onset performance on music tracks independently of false-positive suppression on non-music tracks. The combined fix reduced the pipeline’s NaN rate from 15% to 0% and increased the informativeness of the monthly evaluation report from a single unreliable aggregate to a three-category breakdown with fully numeric scores.

One additional edge case worth documenting: mir_eval 0.7’s onset.f_measure function also returns NaN when the tolerance window is set to 0.0 seconds (zero-width window) and the reference and estimated onset arrays are non-empty but contain no pairs within 0 seconds of each other (which is essentially always the case for real data). The Northfield team had experimented with a strict 0ms window for a secondary evaluation task; this produced NaN for every track, not just silence tracks. The fix is the same guard-clause pattern: when precision = 0 and recall = 0 on non-empty arrays (no matches within any tolerance), mir_eval returns F = 0.0 for non-zero windows but NaN for edge cases involving intermediate 0/0 expressions; the guard should be applied unconditionally after the mir_eval call: f = 0.0 if np.isnan(f) else f as a final safety net. The retainer engagement was 1.5h: 0.25h triage (NaN traced to silence tracks via per-track CSV logging), 0.50h root cause (empty-array arithmetic in mir_eval confirmed; semantically correct scores for each case determined), 0.50h fix (guard clause + nanmean aggregation; regression test with 15 silence tracks), 0.25h validation (0% NaN on 100-track hold-out set including 20 silence tracks). Hours logged to HourTab with per-session breakdown.

Related retainer posts


Track retainer hours without a client portal

HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.

See pricing →