MFCCs: cosine coordinates of log-Mel features
MFCC 特征
Derive orthonormal DCT coefficients, projection error and gain effects, then test floor and lifter boundaries.
mfccCan a small set of frequency bands become smaller?
Mel pooling already turns many frequency bins into fewer bands. When neighboring log-band energies rise and fall together, another coordinate system can describe their variation with a few cosine shapes. Keeping only the early coefficients then discards the other directions explicitly. Mel-frequency cepstral coefficients (MFCCs) use this kind of pipeline.
The cosine transform acts along the frequency-band axis; it is not another search for pitch in a time waveform. Coefficient 0 summarizes the overall level of log-band values, while higher orders describe faster variation across band indices. MFCCs are features, not transcripts, speaker identities or music labels. Those outputs require additional models and task evaluation.
Specify the configuration. Page 29 of Slaney’s 1998 Auditory Toolbox describes FFT magnitude, a fixed 40-filter bank, common logarithms and a cosine transform. The librosa 0.11.0 interface explicitly lists log-power input, DCT type, normalization and liftering. Historical toolbox pipeline MFCC configuration We use supplied Mel power, natural logarithms and an orthonormal DCT-II, retaining coefficient 0. These choices are not a unique universal standard.
Take logarithms, then change coordinates across bands
Let nonnegative Mel power be an matrix, with bands in rows and frames in columns. A floor prevents logarithms of zero. Input values are understood to have an established fixed reference scale:
This clips small values to a common lower bound rather than adding . Distinct powers below the floor become indistinguishable. Natural and common logarithms differ by a constant factor only when other choices agree. Changing power versus magnitude, floor or reference can prevent a single scale factor from converting the whole front end.
Row of the orthonormal DCT-II matrix is a cosine basis function over bands. Write the coefficient matrix as :
Row 0 is constant, so equals mean log-band value times , not original waveform energy. Other rows have positive and negative weights summing to zero, responding to differences between bands. With two bands, becomes , directly checkable by hand.
Orthogonality follows by converting cosine products into sums. Products of different orders sum to zero; squared nonzero-order cosines sum to , while the constant order sums to . The factors normalize these values. With all coefficients, transpose gives the inverse. Keeping only the first rows, denoted , gives a projection back into log-band space:
Projection retains the first basis directions and removes the remaining orthogonal ones. Since orthonormal coordinates preserve squared length, reconstruction-error energy equals discarded-coefficient energy:
The squared Frobenius norm sums squared matrix entries. For our four-band, three-frame example retaining two coefficients, both calculations give approximately 3.9343592168. Keeping all four leaves only floating-point reconstruction error. This is a log-Mel-domain result, not recovery of the original waveform.
Amplitude gain has a direct derivation too. Multiplying the original waveform by nonzero multiplies power by . With no floor intervention and an unchanged reference, every log-band value increases by . A constant vector affects only coefficient 0:
For , coefficient 0 increases by . If the floor pins some entries, changes are no longer a common constant and higher-order coefficients can change. “Removing coefficient 0 removes all volume dependence” therefore needs conditions.
An optional lifter weights coefficients by index. We use the sinusoidal form from the inspected interface. It operates on the cepstral axis, not as a time-domain filter on the original waveform:
Here is the lifter parameter, separate from band count . For and four coefficients, weights are [2,1,0,1]. One coefficient is erased, so division cannot restore it. librosa documents the parameter form; we deliberately inspect the zero-weight boundary of invertibility. Lifter and DCT options
Return coefficients and projection error together
The complete program uses Python 3.12 and NumPy 1.26.4. Input has 2–16 bands and 1–64 frames of nonnegative Mel power, capped at , with a floor between and 1. By default it computes and retains every coefficient; coefficients selects the number of leading rows to keep. The example directly constructs four bands by three frames of log values, then exponentiates them to positive power so intermediate steps are inspectable. It does not reimplement waveform framing or train a recognizer.
"""Orthonormal DCT-II of supplied Mel power, with truncation and optional lifter.
Natural log, absolute floor, coefficient zero retained, no learned recognizer.
"""
import json
import numpy as np
def basis(bands):
if type(bands) is not int or not 2<=bands<=16:raise ValueError('Use 2–16 Mel bands')
k=np.arange(bands)[:,None];j=np.arange(bands)[None,:];a=np.full((bands,1),np.sqrt(2/bands));a[0]=1/np.sqrt(bands)
return a*np.cos(np.pi*(j+.5)*k/bands)
def lifter_weights(count,lifter):
if not np.isfinite(lifter) or isinstance(lifter,bool) or not 0<=lifter<=100:raise ValueError('Lifter must be finite in [0,100]')
return np.ones(count) if lifter==0 else 1+.5*lifter*np.sin(np.pi*(np.arange(count)+1)/lifter)
def transform(power,coefficients=None,lifter=0.,floor=1e-12):
x=np.asarray(power)
if np.iscomplexobj(x):raise ValueError('Real Mel power required')
x=np.asarray(x,dtype=float)
if x.ndim!=2 or not 2<=x.shape[0]<=16 or not 1<=x.shape[1]<=64 or not np.isfinite(x).all() or (x<0).any() or (x>1e12).any():raise ValueError('Use bounded nonnegative Mel-band by frame powers')
if not np.isfinite(floor) or not 1e-12<=floor<=1:raise ValueError('Floor must be in [1e-12,1]')
bands=x.shape[0];count=bands if coefficients is None else coefficients
if type(count) is not int or not 1<=count<=bands:raise ValueError('Invalid coefficient count')
z=np.log(np.maximum(x,floor));full=basis(bands)@z;weights=lifter_weights(count,lifter)
return dict(features=weights[:,None]*full[:count],full=full,log_power=z,weights=weights,floor=floor)
def inverse_log(features,bands,lifter=0.):
c=basis(bands);a=np.asarray(features,dtype=float)
if a.ndim!=2 or not 1<=a.shape[0]<=bands or not 1<=a.shape[1]<=64 or not np.isfinite(a).all() or np.max(abs(a))>1e6:raise ValueError('Invalid finite coefficient matrix')
weights=lifter_weights(a.shape[0],lifter)
if (abs(weights)<1e-12).any():raise ValueError('A zero lifter weight prevents inversion')
return c[:a.shape[0]].T@(a/weights[:,None])
def center(features):
x=np.asarray(features,dtype=float)
if x.ndim!=2 or not x.size or not np.isfinite(x).all():raise ValueError('A finite coefficient-by-frame matrix is required')
return x-x.mean(axis=1,keepdims=True)
def demo():
z=np.array([[0,1,2],[1,1.5,2],[2,1,0],[.5,1,1.5]],float);energy=np.exp(z);full=transform(energy);short=transform(energy,2);back=inverse_log(short['features'],4)
gained=transform(4*energy);floor_case=transform([[0.,1e-12],[1e-10,1.]])
covariance=np.cov(full['features'],bias=True);off=covariance-np.diag(np.diag(covariance))
return dict(mel_power=energy.tolist(),basis=basis(4).tolist(),full=full['features'].tolist(),truncated=short['features'].tolist(),reconstructed_log=back.tolist(),
full_inverse_error=float(np.max(abs(inverse_log(full['features'],4)-z))),
truncation_error_energy=float(np.sum((back-z)**2)),discarded_coefficient_energy=float(np.sum(full['full'][2:]**2)),
gain_shift=(gained['features']-full['features']).tolist(),expected_c0_shift=float(2*np.log(4)),
centered=center(full['features']).tolist(),covariance=covariance.tolist(),max_offdiagonal_covariance=float(np.max(abs(off))),
floor_log=floor_case['log_power'].tolist(),lifter6=lifter_weights(4,6).tolist(),lifter2=lifter_weights(4,2).tolist(),
scope='A full DCT inverts floored log-Mel values, not phase or audio; truncated coefficients are a projection, not a lossless representation.')
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
Full-coefficient log-domain reconstruction has maximum error about . Truncating to two makes projection error equal the squared sum of discarded coefficients. gain_shift verifies that multiplying power by 4 changes only coefficient 0; floor_log exposes clipping of zero and tiny powers. inverse_log rejects lifter weights with magnitude below rather than masking information loss with infinities.
center subtracts each coefficient’s temporal mean, making its mean over these frames zero. This deletes components constant across the entire segment. Streaming or train/test use must separately specify which available frames supply the statistics; future frames cannot be assumed available. Whether to retain that information depends on the task.
An orthogonal matrix does not guarantee statistical independence for arbitrary data. Our coefficient covariance has maximum absolute off-diagonal value about 0.563082, already refuting guaranteed decorrelation merely by applying a DCT. Even actual uncorrelatedness would not establish independence without additional distributional conditions.
The program builds the full matrix and computes all coefficients before slicing. Time is therefore and space . Computing only needed rows could reduce multiplication to , but that is not the current implementation’s operation count.
An invertible DCT does not invert the whole pipeline
All coefficients plus an invertible lifter recover only floored log-Mel values. Details lost during band pooling, phase and distinctions below the floor remain absent. Truncation then removes another representable subspace. MFCCs are not lossless sound encoding.
Lower-order coefficients favor slowly varying spectral envelopes, but task-relevant detail may lie in discarded directions. Comparing MFCCs, log-Mel and linear spectra requires fixed data splits and back-end models; compactness alone does not determine performance. This program does not implement pre-emphasis, temporal-difference coefficients, audio decoding or real recognition evaluation. Log base, bank definition, replacement of coefficient 0 and normalization should be recorded alongside the model.
Infer what the coefficients retain
-
Understanding. Does this DCT-II vary along time or frequency bands? Is coefficient 0 the original waveform energy?
Answer: It varies across band indices within each frame. Coefficient 0 is mean log-band value times , not original waveform energy.
-
Calculation. Two log-band values are [0,1]. What are the full orthonormal DCT coefficients, and what reconstruction and error energy remain when only coefficient 0 is kept?
Answer: Coefficients are . Retaining coefficient 0 reconstructs [0.5,0.5], with error energy 0.5, exactly the square of the discarded coefficient.
-
Boundary. Four coefficients use lifter . Does retaining every coefficient unconditionally recover log-Mel values?
Answer: No. Weights [2,1,0,1] erase coefficient 2 under zero-based indexing. Division by zero cannot recover its previous value. The program must report this noninvertibility.
-
Transfer. If powers in four bands all increase by factor 4, must higher-order MFCCs remain unchanged?
Answer: Only under conditions including a fixed reference and no floor intervention. Coefficient 0 then increases by . If some values remain pinned to the floor, changes vary across bands and higher orders can change too. Front-end settings must accompany the claim.
Historical implementations do not guarantee every configuration
Pages 29–30 of Slaney’s 1998 technical report establish the processing order and intermediate outputs. Its fixed bank, magnitude and common logarithms differ from our power, natural logarithms and configurable bands. We neither reproduce it item by item nor use its speech samples or performance results. librosa 0.11.0 documentation checks DCT-II, orthonormal scaling and the lifter formula. Projection, gain and counterexamples are independent derivations and synthetic calculations. These sources are not sufficient to establish who first invented MFCCs, and we make no such claim.
Make a prediction, then check
What can all coefficients recover with an invertible lifter?
Learning objectives
- Derive orthonormal DCT-II along frequency bands.
- Match truncation error to discarded coefficient energy.
- State the conditions for gain affecting only coefficient 0.
- Identify floor, lifter and upstream information losses.
Prerequisites & connections
Explore related knowledge →References
- Auditory Toolbox, Version 2, Technical Report 1998-010
Malcolm Slaney · 1998 - librosa 0.11.0: feature.mfcc
librosa contributors · 2025
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked natural-log flooring, orthonormal DCT-II, full inverse versus truncated projection energy, conditional gain invariance, zero-lifter inversion failure and nonzero off-diagonal covariance against scoped Slaney1998 pages29–30 and librosa0.11.0 parameters. Six paired equations and four explained exercises. Full M coefficients computed before truncation: O(M²T). No first-invention, listening or recognition claim.
- Checked orthogonality, two-band hand calculation, projection/discarded energy equality, gain-only coefficient0 conditions and floor counterexample, zero lifter and arbitrary-data covariance limits.
- 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:
- Auditory Toolbox, Version 2, Technical Report 1998-010 · Read opening purpose/MFCC classification, visually inspected page29 processing sequence and fixed40-filter description, then page30 intermediate outputs. The report uses FFT magnitude/log10; our variable-band power/natural-log example is different. No TIMIT results or first-invention attribution claimed.
- librosa 0.11.0: feature.mfcc · Read log-power input, DCT-II, orthonormal scaling, lifter formula and multichannel peak-reference caveat. This original example accepts supplied Mel powers and does not execute or reproduce the multichannel pipeline.
Related topics