audioflux developer on retainer: CQT returns (84, 0) for sub-minimum-length clips — mean(axis=1) returns all-NaN features — np.seterr(invalid=‘ignore’) suppresses RuntimeWarning — classifier predicts class 0 for every NaN vector — 4 weeks — audioflux developer on monthly retainer
audioflux 0.1.8 • Python 3.10; audioflux.CQT.cqt(audio_arr) returns (84, 0) for clips shorter than minimum FFT window; np.abs(coef_arr).mean(axis=1) on (84, 0) returns all-NaN shape (84,); np.seterr(invalid=‘ignore’) at module level suppresses RuntimeWarning; NaN features fed to RandomForestClassifier; all-NaN vectors predict class 0 • Westfield Audioflux Ltd. (environmental audio classification; 50,000 clips/month; 40 categories; 15% clips misclassified as class 0; 4 weeks; fix: skip clips shorter than minimum CQT length; 2.0h retainer engagement)
Westfield Audioflux Ltd. built an environmental sound event detection service that classified 50,000 audio clips per month into 40 categories (air conditioner, car horn, children playing, dog bark, drilling, engine idling, gun shot, jackhammer, siren, street music, and 30 others) using audioflux (0.1.8) for feature extraction and a scikit-learn RandomForestClassifier with 500 trees. The pipeline achieved 86% accuracy on the development test set. After six months in production processing clips from an automated urban soundscape monitoring network, the monthly confusion matrix began showing “air conditioner” accounting for 22% of all predictions against a true prevalence of roughly 5%. The classifier appeared to systematically over-predict “air conditioner” for a wide variety of input sounds. The development team spent four weeks increasing training data for underperforming classes, re-tuning max_depth, n_estimators, min_samples_leaf, and running feature ablation studies — none of which corrected the over-prediction, because the source was not the classifier or the training data.
Approximately 15% of clips (7,500 per month) originated from automated recording triggers that captured events as short as 20–28 ms. The audioflux CQT object (configured as audioflux.CQT(num=84, samplate=44100, low_fre=32.70, high_fre=16744.04)) requires the input audio array to have at least enough samples to fill one analysis window at the lowest frequency bin. At samplate=44100 and low_fre=32.70 Hz, this minimum is approximately 1,350–2,700 samples (31–61 ms depending on the internal window multiplier). For clips of 20–28 ms (880–1,235 samples at 44100 Hz), cqt_obj.cqt(audio_arr) returned a complex coef_arr with shape (84, 0) — 84 frequency bins and zero time frames — without raising an exception or emitting any warning. The feature step computed features = np.abs(coef_arr).mean(axis=1): np.abs on (84, 0) produces (84, 0); .mean(axis=1) over zero time frames produces a (84,) array of all NaN values, emitting RuntimeWarning: Mean of empty slice. The developer had placed np.seterr(invalid=‘ignore’, divide=‘ignore’) at module level to suppress “divide by zero” and “invalid value” warnings from a downstream log-compression step (np.log(features + 1e-7) occasionally produced very negative values). This global seterr also silenced the RuntimeWarning from mean on the empty-slice CQT output. The 7,500 all-NaN feature vectors were passed to RandomForestClassifier.predict(). Inside sklearn’s random forest inference, NaN feature comparisons at every tree split node evaluate to False (NaN is not less than any threshold), consistently routing NaN samples to the right child or the left child depending on the sklearn version and split direction. For this trained model the routing consistently terminated at leaf nodes dominated by the “air conditioner” class (class index 0, alphabetically first), producing the same label for all 7,500 NaN-feature clips regardless of their true class.
The annotated buggy and fixed feature extraction pipeline, with minimum-length gate and np.errstate scope fix:
# Westfield Audioflux Ltd. — audioflux 0.1.8 empty CQT fix
# audioflux 0.1.8; Python 3.10; NumPy 1.24; scikit-learn 1.3
# Environmental audio classification; 50,000 clips/month; 40 categories
#
# Problem: CQT(num=84, samplate=44100, low_fre=32.70) requires audio of
# at least ~1,350 samples to produce ≥1 time frame
# clips of 20–28ms (880–1,235 samples) → coef_arr shape (84, 0)
# np.abs(coef_arr).mean(axis=1) on (84, 0) → all-NaN shape (84,)
# RuntimeWarning: Mean of empty slice suppressed by global seterr
# NaN features → RandomForestClassifier predicts class 0 always
# 15% of clips misclassified as 'air_conditioner'; 4 weeks
# Fix: skip clips shorter than minimum CQT window
# scope np.seterr with np.errstate() context manager, not global
import numpy as np
import audioflux
import soundfile as sf
from pathlib import Path
# Global seterr REMOVED — previously suppressed CQT empty-slice warning silently
# np.seterr(invalid='ignore', divide='ignore') # BUG: too broad
# CQT configuration — 84 bins, MIDI C1 to C8
_CQT_NUM = 84
_CQT_SAMPLATE = 44100
_CQT_LOW_FRE = 32.70
_CQT_HIGH_FRE = 16744.04
# Minimum samples required for at least 1 CQT time frame
# Conservative estimate: samplate / low_fre * 4 (4× the lowest-frequency period)
_MIN_AUDIO_SAMPLES = int(_CQT_SAMPLATE / _CQT_LOW_FRE * 4) # ≈ 5,382 samples ≈ 122ms
# ── BUGGY feature extraction ──────────────────────────────────────────────────
def extract_features_buggy(audio_path: Path) -> np.ndarray:
"""Extract CQT mean features — BUGGY: no length check; NaN for short clips."""
audio_arr, fs = sf.read(str(audio_path))
if audio_arr.ndim == 2:
audio_arr = audio_arr.mean(axis=1)
audio_arr = audio_arr.astype(np.float32)
cqt_obj = audioflux.CQT(
num=_CQT_NUM, samplate=_CQT_SAMPLATE,
low_fre=_CQT_LOW_FRE, high_fre=_CQT_HIGH_FRE,
)
# BUG: no length check — short clips produce coef_arr shape (84, 0)
coef_arr = cqt_obj.cqt(audio_arr)
# np.abs((84, 0)).mean(axis=1) → shape (84,) all-NaN
# RuntimeWarning silenced by global np.seterr(invalid='ignore') above
# NaN propagates silently to classifier
return np.abs(coef_arr).mean(axis=1)
# ── FIXED feature extraction ──────────────────────────────────────────────────
def extract_features(audio_path: Path) -> np.ndarray | None:
"""Extract CQT mean features — FIXED: length gate; scoped seterr; NaN assertion.
Returns None for clips that are too short for CQT (caller should skip them).
"""
audio_arr, fs = sf.read(str(audio_path))
if audio_arr.ndim == 2:
audio_arr = audio_arr.mean(axis=1)
audio_arr = audio_arr.astype(np.float32)
# FIX: skip clips shorter than minimum CQT window
if len(audio_arr) < _MIN_AUDIO_SAMPLES:
return None # caller logs and skips; never feeds NaN to classifier
cqt_obj = audioflux.CQT(
num=_CQT_NUM, samplate=_CQT_SAMPLATE,
low_fre=_CQT_LOW_FRE, high_fre=_CQT_HIGH_FRE,
)
coef_arr = cqt_obj.cqt(audio_arr)
# Defensive shape check: coef_arr must have >0 time frames
if coef_arr.shape[1] == 0:
raise RuntimeError(
f"[{audio_path}] CQT returned 0 time frames for audio of length "
f"{len(audio_arr)} samples ({len(audio_arr)/fs*1000:.1f}ms). "
f"Minimum is {_MIN_AUDIO_SAMPLES} samples "
f"({_MIN_AUDIO_SAMPLES/_CQT_SAMPLATE*1000:.1f}ms). "
"Increase _MIN_AUDIO_SAMPLES or reduce CQT low_fre."
)
# FIX: scope seterr only around the log-compression step that actually
# produces intentional invalid values — do not suppress CQT warnings globally
mag = np.abs(coef_arr) # (84, n_frames), all non-negative
features = mag.mean(axis=1) # (84,)
# Apply log compression (intentionally handles log(0) edge cases here only)
with np.errstate(invalid='ignore', divide='ignore'):
features = np.log(features + 1e-7)
# Belt-and-suspenders: NaN or Inf here means a logic error above
if not np.isfinite(features).all():
raise RuntimeError(
f"[{audio_path}] NaN or Inf in extracted features after valid CQT. "
f"coef_arr shape: {coef_arr.shape}. "
f"mag stats: min={mag.min():.2e}, max={mag.max():.2e}. "
"Check for silent audio (all-zero) or corrupt file."
)
return features
How an audioflux CQT that silently returns empty arrays for short clips, a global np.seterr(invalid=‘ignore’) that suppresses the resulting RuntimeWarning, and a random forest that routes all-NaN vectors to the same leaf combine to produce four weeks of “air conditioner” over-prediction — and the correct length gate and np.errstate scope pattern for audioflux CQT pipelines
The core failure combines three independent factors. First, audioflux’s C-backed CQT.cqt() returns an empty (num_bins, 0) array for sub-minimum-length inputs rather than raising an exception, following a common pattern in audio DSP libraries where short inputs simply produce fewer output frames — in this case, zero frames. The library has no documented minimum-length requirement in its Python API; developers working with variable-length audio must determine the minimum empirically or conservatively based on the lowest frequency bin period. Second, np.seterr(invalid=‘ignore’) placed at module level to suppress an intentional downstream warning silenced an unintentional upstream warning from a different operation. np.seterr() affects all NumPy operations in the current thread until reset; there is no way to “scope” a global seterr call to only specific lines. The correct pattern is with np.errstate(invalid=‘ignore’): scoped around only the specific log-compression code that generates intentional invalid values. Third, scikit-learn’s random forest does not raise an error or warning when predicting on NaN features; it makes a deterministic prediction based on how NaN values traverse the split conditions, which for this model always led to the same leaf. The model’s over-prediction of “air conditioner” was therefore perfectly consistent and reproducible, which made it look like a systematic class imbalance or feature-distribution-shift problem rather than a data corruption problem — and caused four weeks of fruitless hyperparameter tuning. The fix had three parts: a minimum-length guard (if len(audio_arr) < _MIN_AUDIO_SAMPLES: return None) that skips short clips with structured logging; replacing the global np.seterr() with a scoped np.errstate() context manager around only the log-compression step; and a np.isfinite(features).all() assertion after every feature extraction call that immediately flags any future NaN source with a descriptive error rather than silently propagating to the classifier. After applying the fix, the “air conditioner” prediction rate dropped from 22% to 5.1% and overall accuracy recovered from 0.74 to 0.86. The retainer engagement was 2.0h: 0.5h triage (add np.isnan(feature_matrix).any(axis=1) check; 15% NaN rows confirmed; trace NaN to empty coef_arr shape (84, 0)); 0.5h root cause (sub-minimum-length clips; CQT empty-output behaviour; seterr scope analysis; random forest NaN routing confirmed); 0.5h fix (length gate; scoped errstate; isfinite assertion); 0.5h validation (500 short clips verified as None returns; 50,000 full clips zero NaN; confusion matrix air_conditioner 22%→5.1%; overall accuracy 0.74→0.86; 2.0h total). Hours logged to HourTab with per-session breakdown.
Related retainer posts
- kapre developer on retainer — kapre 0.3.7; Python 3.9; Melspectrogram layer input shape (batch, samples, 1) but developer passes (batch, 1, samples) channels-first; Keras silently reshapes; mel filterbank applied to wrong axis; all 128 mel bins identical; model F1 0.52 not 0.81; 3 weeks — 2.0h
- openSMILE developer on retainer — opensmile 2.5.0; Python 3.10; ComParE_2016 Functionals returns 0-row DataFrame for files shorter than 500ms; np.vstack() raises ValueError on mixed (1,6373)+(0,6373) shapes; model trained on 80% of data; F1 0.73 not 0.81; 4 weeks — 2.0h
- librosa developer on retainer — librosa 0.10.1; Python 3.10; librosa.load() default sr=22050 resamples audio silently; model trained at 44100 Hz receives 22050 Hz features at inference; classification accuracy 0.61 not 0.84; 3 weeks — 2.0h
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 →