Music information retrieval: choosing which differences to ignore
音乐信息检索
Compute chroma from synthetic audio, retrieve transposed fragments with DTW and test rhythm and ranking ambiguities.
music-information-retrievalIs a transposed melody still the same melody?
Imagine remembering a melody but finding a performance transposed upward and played more slowly. You want its pitch relationships and order, not identical waveform samples. If the task instead identifies a particular master recording, those recording details may be exactly what matters. Two tasks called “find similar music” can require different distance functions.
Music information retrieval, or MIR, extracts structures that can be searched and analyzed. Audio identification, fragment matching, version retrieval, chord analysis and beat analysis have different targets. Invariance to a change usually discards information about that change. The FMP materials organize features and algorithms around these tasks instead of treating one score as a universal music distance. Course and task organization
Our original example starts with four synthetic notes: MIDI pitches 60, 64, 67 and 60. Transpose them two semitones upward, repeat every note twice and insert them into a longer sequence. The program actually generates waveforms, computes spectra and chroma, and searches transpositions and time paths. It finds a close match while exposing why unconstrained time alignment need not recover complete boundaries.
STFT supplies local spectra. This article asks what follows: how to turn spectra into musical features, which differences to ignore, and how to evaluate retrieved fragments.
Features specify what you are willing to ignore
Pitch and chroma: retain pitch class, discard octave
Under twelve-tone equal temperament with A4 referenced to 440 Hz, MIDI pitch has frequency . The inverse takes a logarithm and rounds to the nearest semitone:
Here . “Nearest” refers to logarithmic frequency, not linear distance in hertz. Semitone boundaries fall at and . Detuning, glides and music outside this temperament require different treatment. Frequency and pitch pooling
Let be the complex STFT coefficient of frame and bin , whose frequency is . Pool power by nearest MIDI pitch, fold pitches separated by whole octaves into twelve classes, then normalize each frame:
The set includes only positive-frequency bins whose mapped pitch lies from 0 to 127 and whose pitch modulo twelve equals . Class zero is C and class nine is A. The normalized vector exists only for nonzero norm. Silence is flagged separately rather than assigned an invented direction that could become a “perfect match.”
Ideal power concentrated at either 440 or 880 Hz falls into class A. Chroma cannot distinguish A4 from A5 from that information. Actual short-window spectra also contain leakage; instrument harmonics can land in other pitch classes. Octave folding does not guarantee numerically identical features for arbitrary audio transposed by an octave. Chroma and harmonics
From local distances to a time path
For nonsilent chroma vectors, compare query frame and document frame using cosine distance:
Nonnegative features have theoretical distances between zero and one. The program clips numerical results to zero through two to guard floating-point boundaries; this is not a new similarity definition. Normalization removes global amplitude scaling while retaining the arrangement of pitch classes.
A query contains frames and a document contains . Subsequence dynamic time warping, or subsequence DTW, matches every query frame to some document segment. With zero-based indices, initialize and update accumulated cost matrix as follows:
The first column accumulates costs, but the first row does not: the query may start anywhere in the document without paying for its skipped prefix. Interior steps advance diagonally, vertically or horizontally. The path never reverses or skips query frames. Choose a minimum in the last row instead of forcing the path to the document’s end. Subsequence DTW
Backtracking from to the first row recovers the start. Path includes every visited cell, and the objective minimizes total cost. Dividing the result by the fixed query length for display differs from dividing by a variable path length. Our tie order is diagonal, vertical, horizontal; tied endpoints select the lowest index. Pinned implementation for comparison
Permitting time warping does not identify true rhythm. If three query frames all have zero cost against one document frame, vertical steps can collapse them onto that frame. Sustained tones may permit this feature match, but it does not establish matching note boundaries. Slope constraints or duration costs change the problem. They should not be silently introduced only when an answer looks inconvenient.
Search transpositions by trying all twelve circular shifts of the document’s chroma and minimizing total cost. An upward shift of ten classes is equivalent to a downward shift of two, canceling the example’s two-semitone transposition. This preserves pitch-class relationships while removing absolute key. If an application cares about the original key, that invariance is inappropriate.
Rhythmic evidence: spectral changes and recurring periods
Chroma emphasizes pitch class and may not clearly locate percussion or weak onsets. Spectral novelty first compresses magnitudes, then sums positive changes between successive frames:
We use and set frame zero to zero. The difference is assigned to the current frame . The FMP example assigns a forward difference to the preceding frame and appends a final zero, so implementation comparisons must account for a one-frame offset. We omit local-average subtraction and peak picking. This is a novelty component, not a complete onset detector. Spectral novelty
For a finite novelty sequence sampled at , global autocorrelation, overlap normalization and a candidate tempo are:
Here is sequence length and positive counts lag samples. A separate synthetic example places a pulse every eight samples at 16 Hz over 64 samples. Lag eight gives 120 BPM; lag sixteen gives 60 BPM. Raw correlation sums are seven and six, but normalization by overlap makes both 0.125. Both periodicities come from the same pulse train. These values alone cannot decide the level at which a person should clap. Autocorrelation and metrical levels
The 16 Hz pulse input and the preceding audio features at four frames per second are different time axes. Local tempo analysis can introduce a sliding window. Our example computes only whole-sequence correlation; it neither recognizes meter nor guarantees a perceptual beat estimate.
Define relevance before evaluating retrieval
Given a complete ranking of candidate documents, let indicate whether rank is relevant and let count all relevant documents. Here counts documents, whereas in the earlier DTW equations it counted frames within one document. Average precision, or AP, accumulates precision only at relevant hits:
Our example requires unique document identifiers and a complete candidate list, with the relevant set contained in that list. It returns None for . MAP across queries must also specify how such undefined queries are handled. Silently excluding them does not justify claiming coverage of the whole test set. Relevance depends on the task: the same recording, another performance of the same composition and the same style are different labels. AP and relevance
Retrieve a transposed fragment from synthetic waveforms
The complete program uses Python 3.12 and NumPy 1.26.4. Sampling rate is 4,096 Hz; each note contains 1,024 samples at amplitude 0.8 and restarts phase. Analysis uses nonoverlapping 1,024-sample symmetric Hann windows and orthonormal real FFTs. No human performance, audio dataset or upstream program is used. Fixed tuning, clean monophonic notes and a known fragment make algorithm checks easy compared with real retrieval.
"""Original tiny MIR pipeline: synthetic audio, chroma, subsequence DTW and AP.
Fixed fs=4096, nonoverlapping 1024-sample symmetric-Hann frames; not librosa
settings or an audio fingerprint system. Chroma deliberately discards octave.
"""
import json
import numpy as np
def bounded(value,lo,hi,maximum=32768):
x=np.asarray(value)
if x.dtype.kind not in 'fiu' or not 1<=x.size<=maximum or not np.isfinite(x).all() or np.any((x<lo)|(x>hi)):raise ValueError('Invalid bounded real array')
return x.astype(float)
def synth(pitches):
p=np.asarray(pitches)
if p.dtype.kind not in 'iu' or p.ndim!=1 or not 1<=len(p)<=32 or np.any((p<48)|(p>84)):raise ValueError('Use 1 to 32 MIDI pitches from 48 to 84')
f=440*2**((p.astype(float)-69)/12);t=np.arange(1024)/4096
return (.8*np.sin(2*np.pi*f[:,None]*t)).ravel()
def pool_power(power,frequencies):
a=bounded(power,0,1e6);f=bounded(frequencies,0,2048)
if a.ndim!=2 or f.ndim!=1 or a.shape[1]!=len(f) or len(a)>64:raise ValueError('Expected frame x bin power')
pitch=np.full(len(f),-999,int);positive=f>0
pitch[positive]=np.floor(69+12*np.log2(f[positive]/440)+.5).astype(int)
out=np.zeros((len(a),12))
for c in range(12):out[:,c]=a[:,(pitch>=0)&(pitch<=127)&(pitch%12==c)].sum(axis=1)
return out
def features(signal):
x=bounded(signal,-1,1)
if x.ndim!=1 or len(x)%1024:raise ValueError('Use complete 1024-sample frames')
frames=x.reshape(-1,1024);s=np.fft.rfft(frames*np.hanning(1024),axis=1,norm='ortho');power=abs(s)**2
chroma=pool_power(power,np.fft.rfftfreq(1024,1/4096));norm=np.linalg.norm(chroma,axis=1)
normalized=np.divide(chroma,norm[:,None],out=np.zeros_like(chroma),where=norm[:,None]>1e-12)
compressed=np.log1p(10*abs(s));flux=np.r_[0.,np.maximum(np.diff(compressed,axis=0),0).sum(axis=1)]
return dict(chroma=normalized,power=chroma,non_silent=norm>1e-12,flux=flux,frame_rate=4)
def cost_matrix(query,document):
x=bounded(query,0,1,1536);y=bounded(document,0,1,1536)
if x.ndim!=2 or y.ndim!=2 or x.shape[1]!=12 or y.shape[1]!=12 or len(x)>64 or len(y)>128:raise ValueError('Use frame x 12 chroma')
xn=np.linalg.norm(x,axis=1);yn=np.linalg.norm(y,axis=1)
if np.any(xn<1e-12) or np.any(yn<1e-12):raise ValueError('Silent chroma requires a separate policy')
return np.clip(1-(x/xn[:,None])@(y/yn[:,None]).T,0,2)
def subsequence(cost):
c=bounded(cost,0,2,8192)
if c.ndim!=2 or c.shape[0]>64 or c.shape[1]>128:raise ValueError('Invalid cost matrix')
n,m=c.shape;d=np.empty_like(c);d[:,0]=np.cumsum(c[:,0]);d[0]=c[0];back={}
for i in range(1,n):
for j in range(1,m):
value,_,prev=min((d[i-1,j-1],0,(i-1,j-1)),(d[i-1,j],1,(i-1,j)),(d[i,j-1],2,(i,j-1)))
d[i,j]=c[i,j]+value;back[i,j]=prev
j=int(np.argmin(d[-1]));end=j;i=n-1;path=[(i,j)]
while i:
i,j=(i-1,0) if j==0 else back[i,j];path.append((i,j))
path.reverse()
return dict(cost=float(d[-1,end]),cost_per_query_frame=float(d[-1,end]/n),start=j,end=end,path=path,accumulated=d)
def match(query,document,transpose=True):
if type(transpose) is not bool:raise ValueError('transpose must be boolean')
candidates=[]
for shift in range(12 if transpose else 1):
c=cost_matrix(query,np.roll(document,shift,axis=1));r=subsequence(c);candidates.append((r['cost'],shift,r,c))
_,shift,r,c=min(candidates,key=lambda t:(t[0],t[1]))
return dict(shift=shift,**r,local=c)
def average_precision(ranked,relevant):
if not isinstance(ranked,list) or not 1<=len(ranked)<=32 or any(type(x) is not str for x in ranked) or len(set(ranked))!=len(ranked) or not isinstance(relevant,set) or not relevant<=set(ranked):raise ValueError('Use unique full ranking and known relevant IDs')
hits=0;precision=[];total=0
for rank,name in enumerate(ranked,1):
hit=name in relevant;hits+=hit;p=hits/rank;precision.append(p)
if hit:total+=p
return dict(ap=total/len(relevant) if relevant else None,precision=precision,relevant_count=len(relevant))
def periodicity(novelty,frame_rate):
x=bounded(novelty,0,100,256)
if x.ndim!=1 or len(x)<8 or type(frame_rate) not in (int,float) or not 1<=frame_rate<=100:raise ValueError('Invalid novelty/rate')
lags=np.arange(1,len(x)//2+1);raw=np.array([x[k:]@x[:-k] for k in lags]);normalized=raw/(len(x)-lags)
return dict(lags=lags,bpm=60*frame_rate/lags,raw=raw,overlap_normalized=normalized)
def clean(x):
if isinstance(x,dict):return {k:clean(v) for k,v in x.items()}
if isinstance(x,(list,tuple)):return [clean(v) for v in x]
if isinstance(x,np.ndarray):return x.tolist()
if isinstance(x,np.generic):return x.item()
return x
def demo():
query=[60,64,67,60];a=features(synth(query));octave=features(synth([p+12 for p in query]));doc=[65,65,62,62,66,66,69,69,62,62,65];b=features(synth(doc));aligned=match(a['chroma'],b['chroma']);plain=match(a['chroma'],b['chroma'],False)
distractors={'changed_order':[60,67,64,60],'wrong_intervals':[60,62,65,60]};scores={'transposed_stretched':aligned['cost_per_query_frame']}
for name,pitches in distractors.items():scores[name]=match(a['chroma'],features(synth(pitches))['chroma'])['cost_per_query_frame']
ranking=sorted(scores,key=lambda k:(scores[k],k));pulses=np.zeros(64);pulses[::8]=1;tempo=periodicity(pulses,16)
exact=pool_power([[1,0],[0,1]],[440,880])
return clean(dict(query_pitches=query,document_pitches=doc,query_chroma=a['chroma'],document_chroma=b['chroma'],query_flux=a['flux'],query_wave=synth(query)[:64],aligned=aligned,without_transposition=plain['cost_per_query_frame'],ranking=ranking,scores=scores,evaluation=average_precision(ranking,{'transposed_stretched'}),octave_chroma_distance=float(np.linalg.norm(a['chroma']-octave['chroma'])),exact_octave_pooling=exact,tempo=tempo,scope='Synthetic tones and supplied periodic novelty, no real recording retrieval benchmark; free DTW may collapse durations.'))
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
The default query is [60,64,67,60] and the document is [65,65,62,62,66,66,69,69,62,62,65]. The best circular shift is ten. The actual path runs from document frame three through eight, using zero-based indices. Total cost is about , or per query frame.
Do not replace that path with the supposedly complete segment from two through nine. Every note repeats twice, so free DTW can compress repeated boundary frames, and finite spectra contain small differences. These are the boundaries actually returned. The transposed, stretched version ranks first among three candidates, giving AP one. That is a result for this synthetic three-document example, not a music-retrieval accuracy benchmark.
Ideal 440/880 Hz power pools are identical. The actual query and its octave-raised counterpart have chroma-matrix distance about 0.00105736, showing residual finite-window effects. Silent chroma explicitly fails matching rather than passing through division as an apparently ordinary score.
Naive spectral analysis costs roughly for frames and FFT width . Binning and normalization scan linearly with twelve fixed classes. One DTW uses time and space; twelve shifts multiply the cost by twelve. The example permits at most 64 query and 128 document frames and builds no index for a large music library. Direct autocorrelation enumerates lags in time.
Let the task decide what information to retain
A baseline without a learned model can fix chroma features and perform same-tempo diagonal matching, then compare the result with DTW. Our program trains no network; it is itself a reproducible signal-processing and dynamic-programming baseline. More complex methods should show which data conditions improve retrieval rather than merely adding layers.
Chroma can confuse octave-separated melodies and changes under harmonics, tuning, noise and overlapping instruments. Time warping absorbs tempo variation but can give implausible duration deformations low cost. Removing absolute key or timbre entirely may hurt identification of a particular recording. Specify the object being retrieved before choosing the changes to ignore.
Real tests should avoid overstating generalization when slices of one recording appear in both query and training material. Versions of the same composition also need splits suited to the task. Tie-breaking between nearly identical candidates, rejecting queries without matches, and weighting long versus short excerpts all affect conclusions. This article supplies a complete runnable example, not real-library performance figures.
What distinction does an invariance erase?
- Calculate an octave. Which MIDI pitches and pitch classes correspond to 440 and 880 Hz? Can octave be recovered from chroma alone?
Answer: They are MIDI 69 and 81, both class nine modulo twelve, or A. Folding discards the octave difference, so chroma alone cannot recover it uniquely. Small numerical discrepancies in finite-window spectra are not a reliable octave encoding.
- Inspect a free path. For an all-zero 3×4 cost matrix, what endpoint and path does our tie policy return, and what does this show?
Answer: The lowest-index endpoint in the last row is column zero. Backtracking gives (0,0), (1,0), (2,0), with zero total cost. All query frames collapse onto one document frame through valid vertical steps. Low DTW cost does not establish equal duration or true boundaries.
- Distinguish metrical levels. For 64 samples at 16 Hz with a unit pulse every eight samples, what BPM values correspond to lags eight and sixteen? Why can normalized scores tie?
Answer: They are 60 × 16 / 8 = 120 and 60 × 16 / 16 = 60 BPM. There are seven and six overlapping pulse pairs over 56 and 48 positions, giving 7/56 = 6/48 = 0.125. Both one- and two-pulse intervals recur. Choose a level using the task and musical structure instead of presenting tied peaks as a unique answer.
- Evaluate a ranking. Only a and c are relevant in [a,b,c,d]. What is AP, and what happens if there are no relevant items?
Answer: Hits occur at ranks one and three, giving AP = (1+2/3)/2 = 5/6. This is not the mean of precision at every rank. With no relevant items, the denominator is zero and our example returns None. Specify that query type’s scoring policy before aggregating across queries.
Read features through tasks and code through boundaries
FMP’s chroma, subsequence DTW, spectral novelty, autocorrelation and retrieval-evaluation notebooks provide the main technical entry points. We use the scoped definitions and algorithm passages actually read, without reusing their compositions, recordings or figures. Tutorial text and figures, libfmp code and audio have separate licensing conditions; the code’s MIT license does not cover the entire collection. Material description Chroma DTW Novelty Autocorrelation Evaluation
The accumulated-cost and traceback routines in libfmp commit ed057ba7f884e0fb267809707b2657ca034359a6 ground the boundary and tie-policy comparison. Our implementation is original, with its frame direction and input limits stated separately. No upstream program was copied or executed. A pinned implementation is inspectable evidence, not proof that its parameters suit every MIR task. Pinned matching implementation
Make a prediction, then check
Does zero DTW cost guarantee the correct duration and fragment boundaries?
Learning objectives
- Explain which pitch and octave information chroma preserves or removes.
- Derive subsequence DTW boundaries and inspect an implausible low-cost path.
- Distinguish novelty sample rate, periodicity and perceptual beat level.
- Compute AP under an explicit relevance and empty-query policy.
Prerequisites & connections
Explore related knowledge →References
- FMP Notebooks: overview and material licensing
Meinard Müller and contributors - Log-Frequency Spectrogram and Chromagram
Meinard Müller and contributors - Subsequence Dynamic Time Warping
Meinard Müller and contributors - Spectral-Based Novelty
Meinard Müller and contributors - Autocorrelation Tempogram
Meinard Müller and contributors - Evaluation Measures for Music Retrieval
Meinard Müller and contributors - libfmp subsequence accumulation and traceback at ed057ba
libfmp contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked scoped FMP definitions and fixed libfmp code: pitch-class power pooling, subsequence DTW, novelty conventions, periodicity and AP. Eight paired equations, four explained exercises; actual synthetic-audio pipeline, independent path oracle, duration collapse and octave/tempo ambiguity. No music-corpus benchmark.
- Verified actual shift10/path3..8, twelve independent small path oracles, zero-cost duration collapse, finite FFT octave difference,16Hz pulse120/60BPM ambiguity andAP5/6/None policies. Integer pitch bounds reviewed.
- Four computed SVGs bind exact bilingual MDX. The two-topic group passed11 numeric/encoding checks and12 isolated language/width cases with four fallback fonts; four representative final screenshots inspected by the AI author. Condition-prefix labeling corrected against actual shifted-input code with original figures preserved. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
Source locations checked:
- FMP Notebooks: overview and material licensing · Read overview, task directory and text/figure versus package/audio license declarations. Current page version does not establish a historical snapshot. No tutorial media reused.
- Log-Frequency Spectrogram and Chromagram · Read pitch frequencies, logarithmic pooling and chroma definitions, harmonic and finite-window limitations; no embedded figures or recordings inspected.
- Subsequence Dynamic Time Warping · Read formalization, initialization, recurrence and endpoint/backtracking explanation, extracted lines 5–44. Full variant and recording examples not reviewed.
- Spectral-Based Novelty · Read log compression, positive temporal differences, accumulation and local-average discussion. Our current-frame convention and no-average version differ; no onset benchmark.
- Autocorrelation Tempogram · Read autocorrelation, local-window definitions, implementation opening and interpretation of metrical levels. No embedded media inspected; prototype uses global synthetic pulses.
- Evaluation Measures for Music Retrieval · Read relevance, precision/recall and AP/MAP definitions; identified early rounding in the rank-eight/nine swap example. No real retrieval benchmark run.
- libfmp subsequence accumulation and traceback at ed057ba · Read lines 231–291 for free-start accumulation and diagonal-first traceback. MIT package license read; no copied or executed upstream code.
Related topics