AI Wiki中文/EN

Mel spectrograms: frequency coordinates and lossy pooling

Mel 频谱

Compare HTK and Slaney maps, build triangular banks and construct distinct spectra with identical features.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

What disappears when 65 frequency bins become six numbers?

The one-sided FFT of a 128-sample real signal contains 65 frequency bins. Retaining only six weighted broad-band values per frame reduces a model’s input size, but different spectra can also collapse to the same numbers. We construct that counterexample to make “retaining the main information” a claim with inspectable limits.

A Mel spectrogram organizes frequency-band features over successive frames. Mel is an auditory-inspired frequency coordinate used to arrange nonuniform bands, not a complete model of hearing or a recognizer. A common pipeline frames and windows a waveform, computes an FFT, takes magnitude or power, and applies a filter bank, optionally followed by logarithms. Implementations do not automatically share a Mel definition, normalization or power scale. Mel-coordinate conventions

We specify HTK and the piecewise mapping called Slaney in librosa 0.11.0, then define triangular filters and numerical scales. The program demonstrates one complete segment and its filter bank. Applying the same operation frame by frame produces a two-dimensional Mel spectrogram; STFT covers temporal framing.

Mel conventions yield different frequency boundaries. Area-normalized pooling can erase a supported change in the spectrum, so all pooled bands still do not identify one unique input.
Mel conventions yield different frequency boundaries. Area-normalized pooling can erase a supported change in the spectrum, so all pooled bands still do not identify one unique input.

Coordinate conversion and weighted pooling are separate steps

Frequency ff is in hertz, and mm is a coordinate under the chosen Mel convention. The HTK formula and its inverse are:

mHTK(f)=2595log⁡10(1+f/700),fHTK(m)=700(10m/2595−1).m_{\mathrm{HTK}}(f)=2595\log_{10}(1+f/700),\qquad f_{\mathrm{HTK}}(m)=700(10^{m/2595}-1).

The default Slaney conversion in librosa 0.11.0 is linear below 1,000 Hz and logarithmic above it. With s=ln⁡(6.4)/27s=\ln(6.4)/27:

mS(f)={f/(200/3),f<1000,15+ln⁡(f/1000)/s,f≥1000,fS(m)={(200/3)m,m<15,1000es(m−15),m≥15.m_{\mathrm{S}}(f)=\begin{cases}f/(200/3),&f<1000,\\15+\ln(f/1000)/s,&f\ge1000,\end{cases}\qquad f_{\mathrm{S}}(m)=\begin{cases}(200/3)m,&m<15,\\1000e^{s(m-15)},&m\ge15.\end{cases}

The value is continuous at the transition. An HTK forward conversion cannot be paired with a Slaney inverse. At the same frequency, their coordinates differ; inspect the resulting hertz edges and filter banks rather than comparing the magnitudes of numbers both named “Mel.”Two definitions Pinned conversion formulas

For MM filters, choose M+2M+2 equally spaced Mel points between the coordinates of fmin⁡f_{\min} and fmax⁡f_{\max}, then convert them back to hertz. Filter bb takes neighboring left, center and right edges ℓb,cb,rb\ell_b,c_b,r_b, evaluated at actual FFT frequencies fkf_k:

Bbkpeak=max⁡ ⁣(0,min⁡ ⁣(fk−ℓbcb−ℓb,rb−fkrb−cb)),Bbkarea=2Bbkpeakrb−ℓb.B^{\mathrm{peak}}_{bk}=\max\!\left(0,\min\!\left(\frac{f_k-\ell_b}{c_b-\ell_b},\frac{r_b-f_k}{r_b-c_b}\right)\right),\qquad B^{\mathrm{area}}_{bk}=\frac{2B^{\mathrm{peak}}_{bk}}{r_b-\ell_b}.

A continuous triangle of height 1 has area half its base width, explaining the factor 2/(rb−ℓb)2/(r_b-\ell_b). Discrete bins may miss the center, so the matrix maximum need not equal 1. Continuous area normalization also does not make the discrete weight sum exactly 1. Area normalization gives wider bands smaller weights; its outputs are not directly comparable to peak normalization. Filter normalization Triangles in the pinned implementation

To define our input precisely, let X[k]X[k] be the raw, unnormalized FFT of an even-length NN-sample signal. There are F=N/2+1F=N/2+1 one-sided bins. We define discrete energy per bin PkP_k, not power spectral density per hertz:

Pk=ak∣X[k]∣2N,ak={1,k=0 or k=N/2,2,otherwise,∑kPk=∑nx[n]2.P_k=\frac{a_k|X[k]|^2}{N},\qquad a_k=\begin{cases}1,&k=0\ \text{or}\ k=N/2,\\2,&\text{otherwise},\end{cases}\qquad \sum_kP_k=\sum_nx[n]^2.

The interior factor accounts for conjugate negative frequencies. For STFT, interpret xx as the actual windowed segment and keep FFT padding, window and scale conventions consistent. A library’s magnitude spectrum is not automatically this energy. With PP from successive frames arranged as an F×TF\times T matrix, an M×FM\times F bank produces M×TM\times T features:

Ebt=∑k=0F−1BbkPkt,Dbt=10log⁡10 ⁣(max⁡(Ebt,ε)Eref).E_{bt}=\sum_{k=0}^{F-1}B_{bk}P_{kt},\qquad D_{bt}=10\log_{10}\!\left(\frac{\max(E_{bt},\varepsilon)}{E_{\mathrm{ref}}}\right).

The reference Eref>0E_{\mathrm{ref}}>0 must use the same feature scale; ε>0\varepsilon>0 is a floor. We fix them at 1 and 10−1210^{-12}, giving −120 for silence. This is the defined logarithmic feature, not sound-pressure level. Referencing each frame to its own maximum would remove part of amplitude changes and yield different features.

Mapping 65 bins into six numbers is generally noninvertible. Choose three equally spaced, supported bins lying on the same linear pieces of all filters. Set direction vv to [0.5, −1,0.5] there and zero elsewhere. A linear function has zero second difference, so:

Bv=0,P(1)=1,P(2)=1+0.25v≠P(1),BP(1)=BP(2).Bv=0,\qquad P^{(1)}=\mathbf1,\quad P^{(2)}=\mathbf1+0.25v\ne P^{(1)},\qquad BP^{(1)}=BP^{(2)}.

Both spectra are nonnegative and the changed bins are actually covered by the bank; this does not merely alter unsupported endpoints. Pooling itself loses information, before logarithmic flooring or phase removal adds further restrictions.

Inspect coordinates, filters and lost information together

The complete Python 3.12/NumPy 1.26.4 program computes in float64. Frequency conversion is bounded to 0–48 kHz. Bank sample rates are at most 48 kHz, even FFT lengths range from 4 to 1,024, there are 1–16 filters, and the upper edge cannot exceed Nyquist. An all-zero discrete filter is rejected with advice to add FFT bins or use fewer, wider bands.

"""Explicit HTK/librosa-Slaney maps and triangular pooling of one-sided energy.

Float64 teaching implementation: no librosa import or recognition benchmark.
"""
import json
import numpy as np


def convert(values,scale='slaney',inverse=False):
    if np.iscomplexobj(values):raise ValueError('Real nonnegative values required')
    x=np.asarray(values,dtype=float)
    if scale not in ('htk','slaney') or type(inverse) is not bool or not np.isfinite(x).all() or (x<0).any():raise ValueError('Use nonnegative finite frequencies and a named scale')
    limit=2595*np.log10(1+48000/700) if scale=='htk' else 15+np.log(48)/(np.log(6.4)/27)
    if (x>(limit if inverse else 48000)).any():raise ValueError('Frequency conversion outside teaching bounds')
    if scale=='htk':return 700*np.expm1(x*np.log(10)/2595) if inverse else 2595*np.log10(1+x/700)
    transition=15.;step=np.log(6.4)/27
    # Maximum prevents evaluating log(0) in the unselected branch of np.where.
    return np.where(x<transition,(200/3)*x,1000*np.exp(step*(x-transition))) if inverse else np.where(x<1000,x/(200/3),transition+np.log(np.maximum(x,1000)/1000)/step)


def bank(rate=8000,nfft=128,bands=6,scale='slaney',normalization='area',fmin=0.,fmax=None):
    fmax=rate/2 if fmax is None else fmax
    if type(rate) is not int or not 2<=rate<=48000 or type(nfft) is not int or not 4<=nfft<=1024 or nfft%2 or type(bands) is not int or not 1<=bands<=16 or normalization not in ('peak','area') or not np.isfinite([fmin,fmax]).all() or not 0<=fmin<fmax<=rate/2:raise ValueError('Invalid filter-bank configuration')
    edges=convert(np.linspace(float(convert(fmin,scale)),float(convert(fmax,scale)),bands+2),scale,inverse=True);bins=np.fft.rfftfreq(nfft,1/rate)
    if not (np.diff(edges)>0).all():raise ValueError('Distinct frequency edges required')
    matrix=[]
    for left,center,right in zip(edges,edges[1:],edges[2:]):
        row=np.maximum(0,np.minimum((bins-left)/(center-left),(right-bins)/(right-center)))
        if normalization=='area':row=row*(2/(right-left))
        matrix.append(row)
    b=np.array(matrix)
    if not (b.sum(axis=1)>0).all():raise ValueError('An empty discrete filter needs more FFT bins or fewer/wider bands')
    return dict(matrix=b,edges=edges,bins=bins,normalization=normalization,scale=scale)


def one_sided_energy(values):
    x=np.asarray(values)
    if np.iscomplexobj(x):raise ValueError('Real samples required')
    x=np.asarray(x,dtype=float)
    if x.ndim!=1 or not 4<=len(x)<=1024 or len(x)%2 or not np.isfinite(x).all() or np.max(abs(x))>8:raise ValueError('Use bounded real even-length samples')
    power=abs(np.fft.rfft(x))**2/len(x);power[1:-1]*=2
    return power


def log_power(values,reference=1.,floor=1e-12):
    if np.iscomplexobj(values):raise ValueError('Real nonnegative values required')
    x=np.asarray(values,dtype=float)
    if not np.isfinite(x).all() or (x<0).any() or not np.isfinite([reference,floor]).all() or not 1e-12<=reference<=1e12 or not 1e-12<=floor<=1:raise ValueError('Finite nonnegative powers, positive reference and bounded floor required')
    return 10*np.log10(np.maximum(x,floor)/reference)


def demo():
    rate=8000;nfft=128;t=np.arange(nfft)/rate;x=.5*np.cos(2*np.pi*500*t)+.25*np.cos(2*np.pi*2000*t);power=one_sided_energy(x)
    slaney=bank();htk=bank(scale='htk');peak=bank(normalization='peak');b=slaney['matrix'];energy=b@power
    # Three supported equally spaced bins on the same linear filter pieces.
    # A fixed second-difference null direction avoids arbitrary SVD basis choices.
    active=np.flatnonzero(b.sum(axis=0)>0)
    j=next(j for j in range(1,len(power)-2) if (b[:,j:j+3].sum(axis=0)>0).all() and np.max(abs(b[:,j]-2*b[:,j+1]+b[:,j+2]))<1e-12)
    v=np.zeros(len(power));v[j:j+3]=[.5,-1,.5];p1=np.ones(len(power));p2=p1+.25*v
    return dict(rate=rate,nfft=nfft,samples=x.tolist(),power=power.tolist(),time_energy=float(np.sum(x*x)),spectral_energy=float(power.sum()),
                hz=[0,500,1000,2000,4000],mel_slaney=convert([0,500,1000,2000,4000]).tolist(),mel_htk=convert([0,500,1000,2000,4000],'htk').tolist(),
                edges_slaney=slaney['edges'].tolist(),edges_htk=htk['edges'].tolist(),filters=b.tolist(),bins=slaney['bins'].tolist(),
                area_features=energy.tolist(),peak_features=(peak['matrix']@power).tolist(),log_features=log_power(energy).tolist(),
                collision=dict(first=p1.tolist(),second=p2.tolist(),feature_difference=float(np.max(abs(b@p1-b@p2))),spectrum_difference=float(np.max(abs(p1-p2))),active_bins=active.tolist()),
                silence_db=log_power(np.zeros(6)).tolist(),scope='Area-normalized triangular features are not an energy-conserving partition, and phase is absent.')


if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))

The 128-sample waveform at 8 kHz combines a 500 Hz cosine of amplitude 0.5 and a 2 kHz cosine of amplitude 0.25. Both frequencies align with bins; time-domain and one-sided spectral energies equal 20. area_features and peak_features expose normalization differences, while the HTK and Slaney hertz edges expose coordinate choices.

collision uses a fixed second-difference direction over three adjacent bins. The spectra differ by up to 0.25, while the largest feature difference is 0 in this example. A deterministic construction helps cross-platform reproduction. The conclusion follows from matrix linearity and does not depend on treating an arbitrary SVD null-space basis as the unique counterexample.

With MM bands, FF bins and TT frames, bank construction takes O(MF)O(MF), pooling takes O(MFT)O(MFT), and storing bank, input and output takes O(MF+FT+MT)O(MF+FT+MT). FFT computation is additional. We do not import librosa or claim output identity with its default float32 or every spectral scaling convention.

Equal array shapes can represent different quantities

Comparing Mel front ends requires sample rate, window, hop, FFT length, Mel definition, band count and range, peak/area normalization, magnitude/power choice, and logarithm base and reference. Omitting a parameter can make “the same Mel features” an incomplete specification.

Area-normalized bands do not form an energy-conserving partition. Summing their values does not recover record energy. More bands can retain finer structure, but too few bins can produce empty filters. Padding refines a grid without creating new observation information. Whether these features outperform linear spectra for recognition requires experiments with the same data and evaluation conditions; we neither train a recognizer nor measure hearing here.

Separate coordinates, scale and recoverability

  1. Understanding. Since both HTK and Slaney produce Mel coordinates, can their forward and inverse functions be mixed?

    Answer: No. The coordinates and curves differ. Our Slaney convention maps 1,000 Hz to 15; only its matching inverse returns the original hertz value.

  2. Calculation. A triangle has left, center and right edges of 0,100 and 300 Hz. What is its continuous area and area-normalization factor?

    Answer: Its area is 150 Hz and the multiplier is 1/1501/150. This does not ensure a discrete FFT-bin weight sum of 1; discrete summation and continuous integration differ.

  3. Counterexample. Two nonnegative spectra differ by up to 0.25 but have identical Mel features. Can all the Mel features recover a unique original spectrum?

    Answer: No. Since Bv=0Bv=0, adding that direction leaves the output unchanged. Even retaining all six bands cannot distinguish those spectra.

  4. Transfer. A filter is zero at every FFT bin. Should you narrow it further or change the bin/band configuration?

    Answer: Add bins or use fewer, wider bands, and inspect the frequency range. Narrowing may make discrete coverage harder. Increasing FFT length through padding still does not add time-domain information.

Pin definitions as well as names

librosa 0.11.0 documentation and two public source pages check the Mel maps, triangles and area factor. Reading was scoped to those formulas and parameters. Exposition and implementation are independent, without copying upstream code. Our one-sided energy, fixed reference and matrix counterexample are explicit teaching choices; the name “Slaney” does not claim reproduction of an entire historical toolbox.

Make a prediction, then check

Why can different nonnegative spectra have the same Mel features?

Choose one answer

Learning objectives

  • Pair each Mel coordinate with its matching inverse.
  • Distinguish peak, area and discrete normalization.
  • Specify one-sided energy, logarithm floor and reference.
  • Demonstrate information loss with supported frequency bins.

Prerequisites & connections

Explore related knowledge →

References

  1. librosa 0.11.0: mel_frequencies
    librosa contributors · 2025
  2. librosa 0.11.0: core.convert source, hz_to_mel and mel_to_hz
    librosa contributors · 2025
  3. librosa 0.11.0: filters.mel
    librosa contributors · 2025
  4. librosa 0.11.0: filters source, mel triangle construction
    librosa contributors · 2025

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-13 · Single AI author checked HTK and librosa0.11.0 Slaney maps/inverses, triangular peak/continuous-area normalization, one-sided energy, fixed-reference logarithmic flooring and a supported three-bin null direction against scoped official documentation and formula excerpts. Six paired equations and four explained exercises. Original float64 pooling, not a complete auditory or recognition model.

  • Checked named-coordinate round trips/limits, continuous triangle area factor, empty discrete filters, energy20, silence−120 and distinct nonnegative spectra with equal features on supported bins.
  • Four computed SVGs bind exact bilingual MDX. The five-topic group passed eleven numeric/encoding checks and 30 isolated language/width cases with four fallback fonts; ten actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.