dtw-python developer on retainer: .distance accumulates over alignment path — longer recordings always exceed threshold calibrated on short clips — similarity search returns no results for 60 % of catalog — 3 weeks — dtw-python developer on monthly retainer

dtw-python 1.3.0 • Python 3.11; dtw.dtw(mfcc_a, mfcc_b).distance is cumulative path cost that scales with sequence length; 5-second clip pairs (215 MFCC frames) produce distance ≈ 350; 120-second clip pairs (5,160 MFCC frames) produce distance ≈ 8,400; SIMILAR_THRESHOLD=500 calibrated on short development clips fails for all long production clips; fix: alignment.normalizedDistance • Southfield Dtwpython Ltd. (music similarity recommendation; 50,000 clips/month; clips 5–120 seconds; similarity search returns 0 results for 60 % of catalog; 3 weeks; 2.0h retainer engagement)

Southfield Dtwpython Ltd. built a music similarity recommendation engine for a streaming catalog of 50,000 audio clips per month. Each clip was processed with librosa to produce a 20-coefficient MFCC feature matrix (shape: n_frames × 20 at hop_length=512, sr=22050 Hz) and pairs of clips were compared with dtw-python (dtw.dtw(mfcc_a, mfcc_b, dist_method=‘euclidean’)). The development team built the similarity pipeline on a development set of 2,000 manually annotated similar/not-similar clip pairs, all sourced from a single short-recording session and uniformly distributed between 5 and 15 seconds in duration. They calibrated SIMILAR_THRESHOLD = 500 on this dataset: pairs with .distance below 500 were labeled similar, pairs above 500 were not. Precision was 91%, recall 88%. When deployed to the full production catalog — which included albums, podcast episodes, and long-form field recordings ranging from 30 to 120 seconds — the pipeline returned zero similar tracks for approximately 60% of the catalog. All affected clips were longer than roughly 25 seconds.

The root cause was that dtw.dtw(x, y).distance returns the total accumulated cost summed along the entire optimal warp path, not a per-frame average. For a pair of 5-second MFCC sequences (each approximately 215 frames at hop_length=512, sr=22050 Hz), the optimal warp path visits roughly 430 frame pairs; if the per-frame Euclidean distance in MFCC space averages 0.8 for similar tracks, .distance ≈ 0.8 × 430 = 344. For a pair of 120-second MFCC sequences (each approximately 5,166 frames), the warp path visits roughly 10,332 frame pairs; the same per-frame distance of 0.8 produces .distance ≈ 0.8 × 10,332 = 8,266 — 24 times larger, even though the audio is equally similar. The threshold of 500 calibrated exclusively on 5–15-second clips was simply inapplicable to any clip pair involving recordings longer than roughly 25 seconds. A 120-second clip compared against itself — acoustically identical audio — produced .distance ≈ 7,800, exceeding the “not similar” threshold by a factor of 15. The team spent three weeks retesting MFCC parameters (n_mfcc increased from 13 to 20 to 40; delta and delta-delta features added; z-score per-clip normalization tried), swapping dist_method from ‘euclidean’ to ‘cosine’ and ‘cityblock’, and verifying audio loading — none of which addressed the root cause because the threshold, not the features, was the problem.

The annotated buggy and fixed similarity comparison, with length-invariant normalizedDistance:

# Southfield Dtwpython Ltd. — dtw-python 1.3.0 unnormalized distance fix
# dtw-python 1.3.0; Python 3.11; NumPy 1.24; librosa 0.10.1
# Music similarity recommendation; 50,000 clips/month; clips 5–120 seconds
#
# Problem: dtw.dtw(mfcc_a, mfcc_b).distance = cumulative (unnormalized) DTW path cost
#          scales linearly with sequence length (∝ N + M)
#          5-second clips (215 MFCC frames at hop=512 @22050 Hz): distance ≈ 320–450
#          120-second clips (5160 MFCC frames): distance ≈ 7,000–10,000
#          SIMILAR_THRESHOLD = 500 calibrated on 5–15-second development clips
#          all long-clip pairs exceed threshold → classified "not similar"
#          similarity search returns 0 results for 60% of catalog; 3 weeks
# Fix:     use alignment.normalizedDistance = distance / (len(a) + len(b))
#          calibrate threshold on a stratified mixed-duration development set

import numpy as np
import librosa
import dtw as dtwlib

HOP_LENGTH = 512
SR = 22050
N_MFCC = 20

# Threshold calibrated on mixed-duration dev set (5–120 sec pairs) using normalizedDistance
SIMILAR_THRESHOLD_NORMALIZED = 0.65


def extract_mfcc(audio_path: str) -> np.ndarray:
    """Load audio and extract MFCC, returning (n_frames, n_mfcc) array."""
    y, _ = librosa.load(audio_path, sr=SR)
    mfcc = librosa.feature.mfcc(y=y, sr=SR, n_mfcc=N_MFCC, hop_length=HOP_LENGTH)
    # librosa MFCC is (n_mfcc, n_frames) — transpose to (n_frames, n_mfcc) for dtw-python
    return mfcc.T


# ── BUGGY similarity comparison ───────────────────────────────────────────────

def are_similar_buggy(mfcc_a: np.ndarray, mfcc_b: np.ndarray) -> bool:
    """BUGGY: .distance is cumulative path cost — always fails for long clips."""
    alignment = dtwlib.dtw(mfcc_a, mfcc_b, dist_method='euclidean')
    # BUG: .distance = sum of per-frame Euclidean distances along entire warp path
    # Scales linearly with warp path length (≈ N + M for symmetric DTW)
    # 5-second clip pairs (215 frames): distance ≈ 320–450 → passes threshold 500
    # 120-second clip pairs (5160 frames): distance ≈ 7,000–10,000 → fails threshold 500
    # Threshold of 500 calibrated on short dev clips is inapplicable to long clips
    return alignment.distance < 500  # BUG: 500 hard-coded from short-clip calibration


# ── FIXED similarity comparison ───────────────────────────────────────────────

def are_similar(mfcc_a: np.ndarray, mfcc_b: np.ndarray) -> bool:
    """FIXED: .normalizedDistance = .distance / (N+M) — length-invariant."""
    alignment = dtwlib.dtw(mfcc_a, mfcc_b, dist_method='euclidean')
    # FIX: .normalizedDistance divides cumulative cost by warp path normalization factor
    # For step_pattern=symmetric2 (default): normalization_factor = len(mfcc_a) + len(mfcc_b)
    # Result is the per-frame-pair average distance — comparable across all durations
    # Calibrate once on a stratified mixed-duration development set
    return alignment.normalizedDistance < SIMILAR_THRESHOLD_NORMALIZED


# ── Validation: self-comparison always produces normalizedDistance = 0.0 ──────

def validate_self_similarity(mfcc: np.ndarray, label: str) -> None:
    """Sanity check: a clip compared to itself must produce normalizedDistance = 0.0."""
    alignment = dtwlib.dtw(mfcc, mfcc, dist_method='euclidean')
    assert alignment.normalizedDistance == 0.0, (
        f"[{label}] Self-comparison produced normalizedDistance = "
        f"{alignment.normalizedDistance:.6f}, expected 0.0. "
        f".distance = {alignment.distance:.4f}, "
        f"warp path length ≈ {len(mfcc) * 2} frames."
    )
    assert alignment.distance == 0.0, (
        f"[{label}] Self-comparison produced .distance = {alignment.distance:.6f}, "
        "expected 0.0. MFCC array contains NaN or Inf."
    )

How a DTW similarity threshold calibrated on short clips silently breaks for every long recording — and the correct normalization pattern for duration-invariant dtw-python comparisons

The core failure combines two independent factors. First, dtw-python’s .distance attribute is a cumulative path cost: it sums the per-frame pairwise distances between matched MFCC frames along the entire optimal warp path. This is mathematically correct — it represents the minimum total alignment cost — but it is not a fixed-scale similarity measure because it grows with sequence length. For symmetric DTW patterns the warp path visits approximately N + M frame pairs (where N and M are the lengths of the two sequences), so .distance scales linearly with duration even when two tracks are equally similar at every comparable time step. Second, the development set used to calibrate the similarity threshold was restricted to a single recording session with clips of 5–15 seconds, a duration range that represented only 40% of the production catalog. No one on the team explicitly checked whether the threshold would generalize to longer clips, because the development evaluation metrics (91% precision, 88% recall) provided strong false confidence. The characteristic failure mode — “no similar tracks found for most of the catalog” — looks superficially like a data coverage problem or an overly-strict threshold, which prompted weeks of MFCC re-tuning rather than threshold analysis. The fix had three parts: replace .distance with .normalizedDistance everywhere in the similarity pipeline; recalibrate the threshold on a development set stratified across the full duration range; and add a self-comparison validation at startup that asserts normalizedDistance == 0.0 for a 5-second, 30-second, 60-second, and 120-second clip to verify that the normalization is working correctly across all duration strata. After applying the fix, similarity search coverage recovered to 98% of the catalog and precision/recall were maintained at 90%/87% across all duration quartiles. The retainer engagement was 2.0h: 0.5h triage (log .distance per clip duration quartile; self-comparison of 120-second clip produces distance 7,800, confirming it exceeds threshold before any inter-clip comparison); 0.5h root cause (.distance cumulative path cost; .normalizedDistance per-frame average; symmetric2 normalization_factor = N+M; threshold calibration set restricted to 5–15-second clips); 0.5h fix (replace .distance with .normalizedDistance across pipeline; recalibrate threshold on stratified mixed-duration dev set; add self-comparison startup assertion); 0.5h validation (60-second self-comparison normalizedDistance = 0.0 confirmed; 120-second self-comparison normalizedDistance = 0.0 confirmed; similarity search returns results for 98% of catalog; precision 90%, recall 87% across all duration strata; 2.0h total). 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 →