librosa.decompose.pitch_nmf#

librosa.decompose.pitch_nmf(S, *, sr=22050, n_fft=None, freq_in=None, n_pitches=84, fmin=None, intervals='equal', bins_per_octave=12, tuning=0.0, window='triangle', harmonics=None, harmonic_weights=None, offset=0.0001, n_residual=5, residual=None, norm=2, fit=True, solver='mu', beta_loss='frobenius', max_iter=200, **kwargs)[source]#

Perform pitch-informed Non-negative Matrix Factorization (NMF).

This function constructs a pitch template basis matrix via pitch_basis and applies Non-negative Matrix Factorization to decompose the input spectrogram S ~= components.dot(activations).

By default, it uses multiplicative updates (solver='mu') initialized with harmonic comb templates (decaying as \(1/m\)) and 5 DCT-based residual templates (broadband, low shelf, high shelf, mid-scoop, and mid-hump) to capture non-pitched transients and noise.

Parameters:
Snp.ndarray [shape=(…, n_features, n_samples)]

Input spectrogram (e.g., magnitude spectrogram).

srnumber > 0 [scalar], default=22050

Audio sampling rate.

n_fftint > 0 [scalar, optional]

FFT window length. If not provided and freq_in is not given, it is inferred from S.shape[-2] as 2 * (S.shape[-2] - 1).

freq_innp.ndarray, optional

Frequencies of the spectrogram rows.

n_pitchesint > 0, default=84

Number of pitch bands to generate. Default 84 covers 7 octaves.

fminfloat > 0, str, or None, optional

Minimum pitch center frequency (in Hz) or note name in SPN format (e.g. ‘C1’). Defaults to ‘C1’ (~32.7 Hz).

intervalsstr or collection of float, default=’equal’

Interval system to use (‘equal’, ‘pythagorean’, ‘ji5’, etc.).

bins_per_octaveint > 0, default=12

Number of bins per octave in the interval system.

tuningfloat, default=0.0

Tuning deviation from A440 in fractions of a bin.

windowstr or callable, default=’triangle’

Filter shape for each pitch / harmonic peak.

harmonicssequence of float, optional

Harmonics to include in each pitch template. If None, includes all harmonics up to Nyquist with \(1/m\) decay. Pass harmonics=[1] for fundamental-only templates.

harmonic_weightssequence of float, optional

Weights for each harmonic. If None, defaults to \(1/m\).

offsetfloat >= 0, default=1e-4

Small additive offset applied to all template values to ensure well-posed multiplicative updates.

n_residualint >= 0, default=5

Number of DCT-based residual templates (for broadband transients/noise). Odd numbers (e.g., 1, 3, 5) produce symmetric shelf/hump pairs.

residualnp.ndarray, optional

Custom residual basis templates to append instead of DCT basis.

norm{None, number}, default=2

Column normalization for basis templates.

fitbool, default=True

If True, estimates components and activations via NMF starting from the pitch template basis. If False, uses the pitch template basis as fixed components and estimates only activations.

solver{‘mu’, ‘cd’}, default=’mu’

NMF solver. Multiplicative updates ('mu') is the standard in music audio decomposition.

beta_loss{‘frobenius’, ‘kullback-leibler’, ‘itakura-saito’} or float, default=’frobenius’

Beta divergence loss to minimize.

max_iterint, default=200

Maximum number of iterations.

**kwargsadditional keyword arguments

Additional arguments to sklearn.decomposition.NMF or decompose.

Returns:
componentsnp.ndarray [shape=(…, n_features, n_components)]

Learned or fixed basis components, where n_components = n_pitches + n_residual. Pitch components are in components[..., :n_pitches], and residual components are in components[..., n_pitches:].

activationsnp.ndarray [shape=(n_components, n_samples)]

Temporal activations for each component.

Notes

This function caches at level 30.

Examples

Decompose a trumpet spectrogram into pitch and residual components:

>>> y, sr = librosa.loadx("trumpet", duration=3)
>>> S = np.abs(librosa.stft(y))
>>> comps, acts = librosa.decompose.pitch_nmf(S, sr=sr, n_pitches=72, fmin="C2")
>>> import matplotlib.pyplot as plt
>>> layout = [list(".AAAA"), list("BCCCC"), list(".DDDD")]
>>> fig, ax = plt.subplot_mosaic(layout, constrained_layout=True)
>>> librosa.display.specshow(
...     S, vscale="dBFS", y_axis="log", x_axis="time", ax=ax["A"]
... )
>>> ax["A"].set(title="Input spectrogram")
>>> ax["A"].label_outer()
>>> librosa.display.specshow(comps, vscale="dBFS", y_axis="log", ax=ax["B"])
>>> ax["B"].set(title="Components")
>>> ax["B"].label_outer()
>>> ax["B"].sharey(ax["A"])
>>> librosa.display.specshow(acts, x_axis="time", ax=ax["C"], cmap="gray_r")
>>> ax["C"].set(ylabel="Components", title="Activations")
>>> ax["C"].sharex(ax["A"])
>>> ax["C"].label_outer()
>>> S_approx = comps.dot(acts)
>>> img = librosa.display.specshow(
...     S_approx, vscale="dBFS", y_axis="log", x_axis="time", ax=ax["D"]
... )
>>> ax["D"].set(title="Reconstructed spectrogram")
>>> ax["D"].sharex(ax["A"])
>>> ax["D"].sharey(ax["A"])
>>> ax["D"].label_outer()
>>> librosa.display.colorbar_db(img, ax=list(ax.values()))
../../_images/librosa-decompose-pitch_nmf-1.png