librosa.segment.recurrence_matrix¶
- librosa.segment.recurrence_matrix(data, k=None, width=1, metric='sqeuclidean', sym=False, axis=-1)[source]¶
Compute the binary recurrence matrix from a time-series.
rec[i,j] == True if (and only if) (data[:,i], data[:,j]) are k-nearest-neighbors and |i-j| >= width
Parameters: data : np.ndarray
A feature matrix
k : int > 0 [scalar] or None
the number of nearest-neighbors for each sample
Default: k = 2 * ceil(sqrt(t - 2 * width + 1)), or k = 2 if t <= 2 * width + 1
width : int >= 1 [scalar]
only link neighbors (data[:, i], data[:, j]) if |i-j| >= width
metric : str
Distance metric to use for nearest-neighbor calculation.
See scipy.spatial.distance.cdist for details.
sym : bool [scalar]
set sym=True to only link mutual nearest-neighbors
axis : int
The axis along which to compute recurrence. By default, the last index (-1) is taken.
Returns: rec : np.ndarray [shape=(t,t), dtype=bool]
Binary recurrence matrix
See also
scipy.spatial.distance.cdist, librosa.feature.stack_memory, structure_feature
Examples
Find nearest neighbors in MFCC space
>>> y, sr = librosa.load(librosa.util.example_audio_file()) >>> mfcc = librosa.feature.mfcc(y=y, sr=sr) >>> R = librosa.segment.recurrence_matrix(mfcc)
Or fix the number of nearest neighbors to 5
>>> R = librosa.segment.recurrence_matrix(mfcc, k=5)
Suppress neighbors within +- 7 samples
>>> R = librosa.segment.recurrence_matrix(mfcc, width=7)
Use cosine similarity instead of Euclidean distance
>>> R = librosa.segment.recurrence_matrix(mfcc, metric='cosine')
Require mutual nearest neighbors
>>> R = librosa.segment.recurrence_matrix(mfcc, sym=True)
Plot the feature and recurrence matrices
>>> import matplotlib.pyplot as plt >>> plt.figure(figsize=(10, 6)) >>> plt.subplot(1, 2, 1) >>> librosa.display.specshow(mfcc, x_axis='time') >>> plt.title('MFCC') >>> plt.subplot(1, 2, 2) >>> librosa.display.specshow(R, x_axis='time', y_axis='time', ... aspect='equal') >>> plt.title('MFCC recurrence (symmetric)') >>> plt.tight_layout()