gammatone developer on retainer: make_erb_filters returns (nfilts, num_taps) but developer iterates transposed rows — fcoefs.T[i] is a cross-frequency amplitude cross-section not a filter — all 64 channels lose frequency selectivity — bird call accuracy 0.84→0.52 — 4 weeks — gammatone developer on monthly retainer

gammatone 0.0.4 • Python 3.9; gammatone.fir.make_erb_filters(fs=44100, num_taps=441, low_freq=50) returns (nfilts, num_taps) = (64, 441); developer transposes to (441, 64) and iterates fcoefs.T[i]; each row of the transposed matrix is a cross-frequency amplitude profile at time step i, not a band-pass filter; all 64 channels produce broadband output; bird call frequency patterns destroyed; CNN accuracy 0.84→0.52; fix: fcoefs[i] not fcoefs.T[i] • Northfield Gammatone Ltd. (bird call classification; 20,000 clips/month; 180 species; 4 weeks; 2.0h retainer engagement)

Northfield Gammatone Ltd. built a bird call classification system processing 20,000 audio clips per month for a biodiversity monitoring platform serving 85 field stations across three continents. The system used gammatone (0.0.4) auditory filterbanks for frequency-selective feature extraction before feeding features to a CNN classifier. The developer called gammatone.fir.make_erb_filters(fs=44100, num_taps=441, low_freq=50) to get FIR filter coefficients and iterated over the result to filter the input signal, one channel at a time. The function returns a 2D NumPy array of shape (nfilts, num_taps) — in this configuration (64, 441): 64 rows (one per frequency channel) each containing the 441-sample FIR impulse response of one band-pass filter. The developer, reasoning that the “inner dimension” (441 samples) should be the per-filter dimension and the “outer dimension” (64 channels) should be the iteration dimension, transposed the array: fcoefs_t = fcoefs.T (shape (441, 64)). They then iterated np.array([np.convolve(signal, fcoefs_t[i], mode='same') for i in range(64)]). The index i in fcoefs_t[i] now selects the i-th row of the transposed matrix, which is the i-th column of the original fcoefs matrix: a 64-element array representing one sample of the impulse response from each of the 64 filters. This 64-element kernel is not a band-pass filter; it is a snapshot of all 64 filters’ amplitudes at time step i. Applied via np.convolve, it produces a 64-tap FIR filter with no frequency selectivity. The resulting 64 “channel” outputs all have similar broadband spectral content, and bird call classification accuracy dropped from 0.84 to 0.52 over 4 weeks of investigation.

The core mechanism: fcoefs from make_erb_filters stores filters as rows. fcoefs[0] is the 441-sample impulse response of the lowest-frequency channel (centered near 50 Hz, the low_freq parameter). fcoefs[63] is the impulse response of the highest-frequency channel (centered near 20,000 Hz). Each impulse response is a band-pass filter: a gammatone function that selects a specific frequency band and attenuates all others. After transposing, fcoefs.T[0] is a 64-element vector [fcoefs[0][0], fcoefs[1][0], ..., fcoefs[63][0]]: the first sample of every filter’s impulse response. At time step 0, all gammatone impulse responses begin with near-zero amplitude (gammatone filters start at zero and build to a peak at their center time). The resulting 64-element kernel is 64 near-zero values — a nearly-silent filter. fcoefs.T[220] (near the impulse response peak for a 441-sample filter) is a 64-element vector of the peak amplitudes of all 64 channels: a broad-spectrum weighting kernel that passes all frequencies roughly equally. When all 64 “channels” are computed this way, each produces a broadband filtered output with the same spectral content as the input, differing only in the specific 64-tap kernel shape at time step i. The CNN received 64 channels of near-identical broadband output for every bird call; the frequency-band-specific patterns that distinguish species (the particular frequency range of each song, the harmonic intervals, the temporal modulation in specific bands) were completely absent. The diagnostic was plotting the power spectral density of fcoefs[0] applied to a 1 kHz test tone (should produce near-zero output since channel 0 is a 50 Hz filter) versus fcoefs.T[0] applied to the same tone (produced a small but nonzero output because the near-zero impulse-start values pass some broadband energy). Comparing the band-pass behavior of a few channels immediately revealed that the transposed filters had no frequency selectivity.

The annotated buggy and fixed filterbank application, with frequency selectivity validation:

# Northfield Gammatone Ltd. — gammatone 0.0.4 FIR coefficient orientation fix
# gammatone 0.0.4; Python 3.9; NumPy 1.24; scipy 1.10
# Bird call classification; 20,000 clips/month; 180 species
#
# Problem: make_erb_filters(fs, num_taps, low_freq) returns (nfilts, num_taps)
#          Each ROW is one filter's impulse response: fcoefs[i] = filter i
#          Developer assumed (num_taps, nfilts) orientation, transposed
#          fcoefs.T[i] = i-th column of fcoefs = cross-frequency snapshot at time i
#          np.convolve(signal, fcoefs.T[i]) applies cross-section as FIR filter
#          All 64 channels: broadband output, no frequency selectivity
#          Bird call features: all channels identical → accuracy 0.84→0.52
# Fix:     Use fcoefs[i] (i-th row) not fcoefs.T[i] (i-th row of transpose)

import gammatone.fir
import gammatone.filters
import numpy as np
import scipy.signal
import soundfile as sf


SAMPLE_RATE = 44100
NUM_TAPS = 441      # FIR impulse response length in samples (10ms at 44100 Hz)
LOW_FREQ = 50.0     # minimum center frequency in Hz


# ── BUGGY filterbank application ─────────────────────────────────────────────

def apply_filterbank_buggy(signal: np.ndarray, fcoefs: np.ndarray) -> np.ndarray:
    """
    BUGGY: transposes coefficient matrix and iterates over transposed rows.
    fcoefs.T[i] is a cross-frequency snapshot, not a filter's impulse response.
    """
    nfilts = fcoefs.shape[0]   # 64 channels (correct)
    # BUG: developer transposes, reasoning that "impulse response" dimension should
    # be innermost when iterating over channels
    fcoefs_transposed = fcoefs.T  # shape (441, 64) — WRONG orientation for iteration

    output = np.array([
        np.convolve(signal, fcoefs_transposed[i], mode='same')
        for i in range(nfilts)
        # BUG: fcoefs_transposed[i] is column i of fcoefs (time step i of all filters)
        # NOT the impulse response of filter i
        # Result: 64 broadband outputs, all with similar spectral content
    ])
    return output  # shape: (64, len(signal)) — shape looks correct, values are wrong


# ── FIXED filterbank application ─────────────────────────────────────────────

def apply_filterbank(signal: np.ndarray, fcoefs: np.ndarray) -> np.ndarray:
    """
    FIXED: iterates over rows of fcoefs directly.
    fcoefs[i] is the i-th filter's complete 441-sample impulse response.
    """
    nfilts, num_taps = fcoefs.shape  # (64, 441)

    # Orientation check: for sensible parameters, nfilts < num_taps
    # make_erb_filters(44100, 441, 50) gives 64 channels, 441 taps
    assert nfilts < num_taps, (
        f"make_erb_filters returned shape ({nfilts}, {num_taps}). "
        f"Expected (nfilts, num_taps) where nfilts < num_taps. "
        f"If you have transposed the array, the row orientation is wrong — "
        f"use the matrix directly from make_erb_filters, do NOT transpose."
    )

    output = np.array([
        np.convolve(signal, fcoefs[i], mode='same')
        # CORRECT: fcoefs[i] is the i-th row = i-th filter's impulse response
        # Channel 0: low-frequency band-pass (~50 Hz center)
        # Channel 63: high-frequency band-pass (~20000 Hz center)
        for i in range(nfilts)
    ])
    return output  # shape: (64, len(signal)) — same shape, correct spectral content


def compute_gammatone_features(audio_path: str) -> np.ndarray:
    """Extract gammatone filterbank energy features from an audio clip."""
    signal, sr = sf.read(audio_path, dtype='float32')
    if signal.ndim > 1:
        signal = signal[:, 0]
    if sr != SAMPLE_RATE:
        raise ValueError(
            f"{audio_path}: sample rate {sr} Hz, expected {SAMPLE_RATE} Hz. "
            "Resample to 44100 Hz before gammatone feature extraction."
        )

    fcoefs = gammatone.fir.make_erb_filters(SAMPLE_RATE, NUM_TAPS, LOW_FREQ)
    # fcoefs.shape is (nfilts, num_taps) = (64, 441)
    # Row i is filter i's impulse response (nfilts rows, each num_taps long)

    filtered = apply_filterbank(signal, fcoefs)  # (64, signal_length)

    # Compute energy in each channel using short-time windows
    hop = int(SAMPLE_RATE * 0.010)   # 10ms hop
    win = int(SAMPLE_RATE * 0.025)   # 25ms window
    n_frames = 1 + (filtered.shape[1] - win) // hop

    energy = np.zeros((fcoefs.shape[0], n_frames), dtype=np.float32)
    for frame in range(n_frames):
        start = frame * hop
        end = start + win
        # RMS energy in each channel for this frame
        energy[:, frame] = np.sqrt(np.mean(filtered[:, start:end] ** 2, axis=1))

    return energy  # shape: (64, n_frames) — log-compress before model input


# ── Frequency selectivity validation ─────────────────────────────────────────

def validate_filterbank_orientation(fcoefs: np.ndarray, fs: int) -> None:
    """
    Validate that make_erb_filters rows are frequency-selective filters.
    Tests that channel 0 passes low frequencies and rejects high frequencies.
    Call once at pipeline startup.
    """
    nfilts, num_taps = fcoefs.shape

    # Generate pure tones for validation
    duration_s = 0.5
    n_samples = int(fs * duration_s)
    t = np.linspace(0, duration_s, n_samples)

    low_tone = np.sin(2 * np.pi * 100 * t).astype(np.float32)   # 100 Hz
    high_tone = np.sin(2 * np.pi * 8000 * t).astype(np.float32) # 8000 Hz

    # Channel 0 should respond more to low than high
    ch0_response_low = np.sqrt(np.mean(np.convolve(low_tone, fcoefs[0], mode='same') ** 2))
    ch0_response_high = np.sqrt(np.mean(np.convolve(high_tone, fcoefs[0], mode='same') ** 2))

    # Channel N-1 should respond more to high than low
    chn_response_low = np.sqrt(np.mean(np.convolve(low_tone, fcoefs[-1], mode='same') ** 2))
    chn_response_high = np.sqrt(np.mean(np.convolve(high_tone, fcoefs[-1], mode='same') ** 2))

    if ch0_response_low <= ch0_response_high:
        raise ValueError(
            f"Channel 0 filter FAILED frequency selectivity test: "
            f"100 Hz response ({ch0_response_low:.6f}) should be greater than "
            f"8000 Hz response ({ch0_response_high:.6f}). "
            f"This suggests fcoefs is transposed — use fcoefs[i] not fcoefs.T[i]. "
            f"fcoefs.shape = {fcoefs.shape}: expect (nfilts, num_taps) where nfilts < num_taps."
        )
    if chn_response_high <= chn_response_low:
        raise ValueError(
            f"Channel {nfilts-1} filter FAILED frequency selectivity test: "
            f"8000 Hz response ({chn_response_high:.6f}) should be greater than "
            f"100 Hz response ({chn_response_low:.6f}). "
            f"Check fcoefs orientation and low_freq / fs parameters."
        )

    print(
        f"[gammatone startup OK] Filterbank orientation validated: "
        f"ch0 100Hz={ch0_response_low:.6f} > 8kHz={ch0_response_high:.6f}; "
        f"ch{nfilts-1} 8kHz={chn_response_high:.6f} > 100Hz={chn_response_low:.6f}. "
        f"fcoefs.shape={fcoefs.shape} = ({nfilts} filters × {num_taps} taps)."
    )

Why iterating fcoefs.T[i] destroys all frequency selectivity in the gammatone filterbank — and the two-tone test that reveals the transposition in under five minutes

The failure combines three factors. First, the row-major storage convention of NumPy filterbank matrices is not obvious from first principles. A developer building a filterbank from scratch might store filters as columns (a (num_taps, nfilts) matrix where each column is a filter, matching the mathematical convention of filter coefficient vectors in textbooks). The gammatone library stores filters as rows, which is the more common NumPy convention (each row is one observation/filter), but requires the developer to know this to iterate correctly. The function signature make_erb_filters(fs, num_taps, low_freq) does not indicate which dimension of the return value corresponds to which semantic concept; the documentation is terse. Second, the transposition produces an output with the correct shape: for fcoefs.shape = (64, 441), iterating fcoefs.T[i] for i in range(64) produces 64 arrays each of length 441 — the same shape as the correct application. np.convolve(signal, fcoefs.T[i], mode='same') produces an output of len(signal) samples, identical in shape to the correct np.convolve(signal, fcoefs[i], mode='same'). The final filterbank output has shape (64, len(signal)) in both cases. The CNN expects this shape and receives it without error. Only the values are wrong. Third, the resulting broadband outputs are not obviously wrong to visual inspection. The filtered signals look like attenuated, slightly-smoothed versions of the input signal — not like silence or noise that would immediately indicate a failure. The 4-week investigation explored data augmentation, CNN architecture, and training hyperparameters, all of which produced <1% improvement on a problem that required fixing the feature representation. The two-tone test that isolated the bug: generate a 100 Hz pure tone and an 8000 Hz pure tone; apply fcoefs[0] and fcoefs.T[0] to both; fcoefs[0] (the lowest-frequency channel) should produce near-zero response to 8000 Hz and meaningful response to 100 Hz; fcoefs.T[0] produces near-zero response to both (since it is the first sample of all 64 filters’ impulse responses, which are all near-zero at their onset). This two-tone comparison took five minutes and immediately confirmed the transposition. The fix is removing the .T: fcoefs[i] instead of fcoefs.T[i]. After retraining the CNN on correct gammatone features, accuracy recovered to 0.83 (slightly below the 0.84 baseline; the 0.01 gap was attributed to a random seed difference). The retainer engagement was 2.0h: 0.5h triage (two-tone selectivity test on fcoefs[0] vs fcoefs.T[0]; shape assertion nfilts < num_taps reveals orientation; root cause confirmed as transposition); 0.5h root cause (make_erb_filters returns (nfilts, num_taps); row i = filter i; .T[i] = time cross-section i; no frequency selectivity); 0.5h fix (remove .T; add orientation assertion; add frequency selectivity validator); 0.5h validation (20,000-clip sample; channel spectral content confirmed band-pass; accuracy 0.52→0.83; retrain on corrected features; 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 →