Laplacian segmentation#

State detection by spectral clustering of a recurrence graph of windows.

Description#

McFee & Ellis (2014) find the repeated sections of a song (verse, chorus) with a graph whose nodes are short frames of the recording. LaplacianDetector applies their structural decomposition to windows of a time series:

  1. The series, standardised per channel, is cut into frames of window_size points every step points. Each frame is described by the log-magnitude spectrum of each channel (feature="spec", \(\log(1 + |\mathrm{FFT}|)\) with the signed log of the window sum, the DC term), which does not depend on the phase of a periodic pattern, or by the window itself (feature="raw").

  2. Recurrence: frames \(i\) and \(j\) are linked when each is among the \(k = 2\lceil\sqrt{N - 2e + 1}\rceil\) nearest neighbours of the other (cosine distance; \(N\) frames; links between frames closer than \(e = \lceil w / (2 s) \rceil\) frames in time are ignored), with weight \(\exp(-d_{ij} / \tilde d)\), where \(\tilde d\) is the median distance of a frame to its farthest link. A median filter of rec_smooth frames along the diagonals favours sequences of frames that repeat in the same order.

  3. Path: consecutive frames are linked with weight \(\exp(-\|f_i - f_{i+1}\|^2 / \tilde\delta)\), where \(\tilde\delta\) is the median of these squared distances.

  4. The graph \(A = \mu R + (1 - \mu) P\) balances the two kinds of edges: \(\mu\) is the least-squares fit, frame by frame, of the degrees of \(\mu R\) and \((1 - \mu) P\) (McFee & Ellis, Eqs. 6-7).

  5. The smallest eigenvectors of the normalised Laplacian of \(A\), median filtered over evec_smooth frames and divided row-wise by their cumulative norm, are clustered by k-means into \(k\) states. Each point takes the state of the frame whose centre is nearest.

A state is thus a set of frames that look alike wherever they occur in the series (recurrence edges) and that stay together in time (path edges).

Number of states. Guided, \(k\) is n_states. Unsupervised, the paper keeps, among \(m = 2, \dots, 10\), the partition of largest label entropy whose mean segment lasts at least 10 s (Sec. 3.3), a threshold in seconds without a counterpart for an arbitrary series; msaf and the librosa example fix \(k\). tsseg uses \(k = \mathrm{round}(\sqrt{k_L k_S})\), the geometric mean of two estimates that err in opposite directions: \(k_L\), the number of Louvain communities (modularity, resolution 1) of the recurrence graph with \(2\lceil\sqrt N\rceil\) neighbours, without the diagonal filter and without path edges, which tends to over-segment, and \(k_S\), the \(k \le\) max_states whose k-means labels have the best cosine silhouette in the space of the frame features, which tends to under-segment. Both are kept in k_louvain_ and k_silhouette_.

Symmetric recurrence. The diagonal median filter of librosa does not keep the recurrence matrix symmetric (its zero padding enters near the ends of the diagonals). The librosa example and msaf decompose the resulting matrix with scipy.linalg.eigh, which reads a single triangle, so the matrix they decompose is not a graph Laplacian: its smallest eigenvalue can be negative, and the solver can break down when a frame is almost isolated. tsseg symmetrises the filtered matrix, \((R_f + R_f^\top) / 2\), and checks that the spectrum lies in \([0, 2]\).

Departures from the paper. tsseg follows the librosa example and msaf where they differ from the paper: cosine distance and \(\exp(-d / \tilde d)\) instead of a Gaussian kernel on the Euclidean distance, \(2\lceil\sqrt{N - 2e + 1}\rceil\) neighbours instead of \(1 + \lceil 2 \log_2 N \rceil\), a median filter of the weighted affinity instead of a majority vote over 17 frames on the binary graph, path weights on the same features as the recurrence, and median-filtered eigenvectors. The cosine ignores scale: with feature="raw", states that differ only by their amplitude look alike, and with "spec" nearly constant frames are dominated by their DC term, so that two levels of the same sign look alike.

Duplicate frames and zero bandwidths. Exact-zero distances retain their mutual-neighbour links with weight 1. If the recurrence or path bandwidth is zero, weights use the limit as a positive bandwidth tends to zero: zero distances have weight 1 and positive distances have weight 0. The inherited recurrence dropped exact-zero links, and the inherited path gave even nonzero jumps weight 1 whenever its median squared distance was zero. The corrected graph can be disconnected. These limits do not change cosine distances, positive-bandwidth formulas or the state-count selector; outputs on series with duplicate frames or median-zero paths can change.

Defaults. feature="spec", window_size=128, step=16 were declared before an evaluation on the 592 series of TSB-SEG. Guided, the mean state matching score (SMS) is 0.717 per series, against 0.692 for CLaP, the best state detector of TSB-SEG. It is above CLaP on five of the six multivariate datasets and below it on the two univariate ones (TSSB: 0.697 against 0.898). Unsupervised, it is close to CLaP on the mean over datasets and below it per series. The step is fixed in points, so that the median filters span the same duration on every series; there is no cap on the number of frames.

Type: state detection
Supervision: unsupervised or guided (n_states)
Scope: univariate and multivariate
Complexity: \(O(N^2 d w + N^3)\) for \(N \approx n / s\) frames of \(w\) points and \(d\) channels, \(O(N^2)\) memory (dense graph); about 16 s and 0.9 GB for 56,000 points (3,500 frames, unsupervised, two threads)
Requires: nothing beyond the core dependencies

Parameters#

Name

Type

Default

Description

n_states

int / None

None

Number of states; None estimates it (see above).

window_size

int

128

Frame length \(w\) in points; on a series shorter than \(4w\), frames of \(\max(8, \lfloor n / 4 \rfloor)\) points.

step

int

16

Points \(s\) between consecutive frames. Cost grows as the cube of \(n / s\).

feature

str

"spec"

"spec" (log-magnitude spectrum per channel) or "raw" (the window).

rec_smooth

int

9

Median filter along the diagonals of the recurrence matrix, in frames (msaf default; 1: none).

evec_smooth

int

9

Median filter of the eigenvectors along time, in frames (msaf default; 1: none).

max_states

int

20

Largest number of states of the unsupervised rule.

random_state

int / None

None

Seed of k-means, of the Louvain node order and of the frames sampled for the silhouette (at most 2,000).

axis

int

0

Time axis.

Usage#

from tsseg import load_mocap
from tsseg.algorithms import LaplacianDetector

X, y = load_mocap(trial=0)
labels = LaplacianDetector(n_states=4, random_state=0).fit_predict(X)

detector = LaplacianDetector(random_state=0)  # unsupervised
labels = detector.fit_predict(X)
detector.n_states_, detector.k_louvain_, detector.k_silhouette_  # (4, 6, 3)

Implementation: the recipe of the librosa example and of msaf scluster, written for tsseg. The mutual k-NN recurrence and the diagonal median filter are ported from librosa (ISC), and Louvain from NetworkX (BSD-3): tsseg depends on neither. Positive-distance recurrence, diagonal filtering and Louvain are checked against librosa 0.11 and NetworkX 3.5; the graph limits above are deliberate differences. On the nine MoCap trials of load_mocap, the reproduction test recovers the scores of the TSB-SEG evaluation to the sixth decimal (mean SMS 0.839 guided, 0.822 unsupervised). The paper’s own results, on songs, are not reproduced: they need the audio and its constant-Q features.

Reference: McFee & Ellis (2014), Analyzing song structure with spectral clustering, ISMIR; Blondel et al. (2008), Fast unfolding of communities in large networks, J. Stat. Mech. (Louvain).

API reference#

Laplacian segmentation detector (McFee & Ellis, ISMIR 2014).

class LaplacianDetector(*, n_states=None, window_size=128, step=16, feature='spec', rec_smooth=9, evec_smooth=9, max_states=20, random_state=None, axis=0)[source]#

Bases: BaseSegmenter

State detection by spectral clustering of a recurrence graph of windows.

The Laplacian structural decomposition of McFee & Ellis [1], designed for the repeated sections of songs, applied to windows of a time series. The series is cut into frames; each frame is linked to the frames that look like it (mutual nearest neighbours, anywhere in the series) and to its two neighbours in time. The frames are clustered by k-means on the smallest eigenvectors of the normalised Laplacian of this graph, so that a state is a set of frames that recur together and stay together in time.

Parameters:
  • n_states (int | None) – Number of states. None (unsupervised): k = round(sqrt(k_L * k_S)), the geometric mean of the number of Louvain communities of the recurrence graph (k_L, tends to over-segment) and of the k with the best silhouette in the feature space (k_S, tends to under-segment).

  • window_size (int) – Frame length in points; on a series shorter than 4 * window_size, frames of max(8, n_timepoints // 4) points instead.

  • step (int) – Points between consecutive frames. The cost is quadratic (memory) and cubic (eigensolver) in the number of frames, about n_timepoints / step.

  • feature (str) – Frame features: "spec" is the log-magnitude spectrum of each channel (log(1 + |FFT|), with the signed log DC term), invariant to the phase of periodic patterns, with the signed log of the window sum (DC term); "raw" is the window itself.

  • rec_smooth (int) – Size, in frames, of the median filter along the diagonals of the recurrence matrix (1: no filter).

  • evec_smooth (int) – Size, in frames, of the median filter of the eigenvectors along time (1: no filter).

  • max_states (int) – Largest number of states considered when n_states=None.

  • random_state (int | None) – Seed of k-means, of the Louvain node order and of the frames sampled for the silhouette.

  • axis (int) – Time axis of the input.

n_states_#

Number of states used for the last prediction (given or estimated).

Type:

int

k_louvain_, k_silhouette_

The two estimates combined when n_states=None (None otherwise, or when the series has fewer than 6 frames or only identical ones).

Type:

int or None

eigenvalues_#

Smallest eigenvalues of the normalised Laplacian.

Type:

np.ndarray or None

Notes

Steps (librosa example “Laplacian segmentation” [2], msaf scluster defaults [3]): per-channel standardisation; frames of window_size points every step points; mutual k-NN recurrence affinity between frames (cosine distance, 2 ceil(sqrt(N - 2 e + 1)) neighbours, links within e = ceil(window_size / (2 step)) frames excluded), exp(-d / b) with b the median distance of a frame to its farthest link; diagonal median filter of rec_smooth frames; path affinity between consecutive frames, exp(-||f_i - f_{i+1}||^2 / median); A = mu R + (1 - mu) P with mu the least-squares balance of the degrees ([1], Eqs. 6-7); smallest eigenvectors of the normalised Laplacian of A ([1], Eq. 10), median filtered over evec_smooth frames, rows normalised by their cumulative norm; k-means (10 initialisations) on the first k. Each point takes the label of the frame whose centre is nearest.

Departures from the paper (following the librosa example and msaf unless a tsseg choice is noted):

  • recurrence: cosine distance and exp(-d / b) instead of the Gaussian kernel exp(-||x_i - x_j||^2 / (2 sigma^2)) ([1], Sec. 2.3); 2 ceil(sqrt(N - 2 e + 1)) neighbours instead of 1 + ceil(2 log2 N), and an exclusion of e frames instead of 3 beats ([1], Sec. 4.2); median filter of the weighted affinity along the diagonals instead of a majority vote over 17 frames on the binary graph, weighted afterwards ([1], Eqs. 2 and 8). The cosine ignores scale: with feature="raw", two states that differ only by their amplitude look alike, and with "spec" frames that are nearly constant are dominated by their DC term, so that two levels of the same sign look alike;

  • path: weights on the same features as the recurrence, with the median squared distance as bandwidth, instead of a Gaussian kernel on MFCC ([1], Eq. 9);

  • eigenvectors median filtered over evec_smooth frames (not in the paper);

  • frame features: a spectrum per window instead of beat-synchronous constant-Q and MFCC features of audio;

  • symmetrised recurrence (tsseg): the diagonal median filter breaks the symmetry of the recurrence matrix, and the librosa example and msaf decompose the resulting non-symmetric matrix with eigh, which reads a single triangle. tsseg uses (Rf + Rf.T) / 2 and checks that the spectrum lies in [0, 2], with a fallback to other LAPACK drivers;

  • graph limits (tsseg): exact-zero mutual-neighbour distances retain affinity 1. When a recurrence or path bandwidth is zero, the positive-bandwidth limit gives weight 1 to zero distances and 0 to positive distances, instead of dropping duplicate recurrence links or setting every path weight to 1;

  • fixed step in points (tsseg), so that the smoothing lengths mean the same duration on every series (no cap on the number of frames);

  • unknown number of states (tsseg): the paper keeps, among m = 2..10, the partition of largest label entropy whose mean segment lasts at least 10 s ([1], Sec. 3.3), a threshold in seconds that has no counterpart for an arbitrary series; msaf and the librosa example fix k. The rule above was selected on held-out TSB-SEG series (Louvain graph with 2 ceil(sqrt(N)) neighbours, no diagonal filter, no path edges; silhouette with cosine distance, on at most 2000 frames);

  • degenerate inputs: a single state when there are fewer than 6 frames or all frames are identical (constant series); the path graph alone when no pair of frames is a recurrence link.

Defaults feature="spec", window_size=128, step=16 were declared before an evaluation on the 592 series of TSB-SEG; with them, guided (true n_states) SMS 0.717 per series against 0.692 for CLaP. The method is weaker on univariate series (TSSB) than CLaP.

The recurrence, the median filters and the Louvain step are ported from librosa (ISC) and NetworkX (BSD-3), without these dependencies (notices in the sub-package LICENSE). The recurrence retains exact-zero links and defines a zero-bandwidth limit, as described above.

References

Examples

>>> import numpy as np
>>> from tsseg.algorithms import LaplacianDetector
>>> t = np.arange(3000)
>>> X = np.where((t // 500) % 2 == 0, np.sin(2 * np.pi * t / 50),
...              np.sin(2 * np.pi * t / 12))
>>> labels = LaplacianDetector(n_states=2, random_state=0).fit_predict(X)
>>> labels.shape
(3000,)
set_fit_request(*, axis='$UNCHANGED$')#

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

axis (Union[bool, None, str]) – Metadata routing for axis parameter in fit.

Returns:

self – The updated object.

Return type:

LaplacianDetector

set_predict_request(*, axis='$UNCHANGED$')#

Configure whether metadata should be requested to be passed to the predict method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to predict.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

axis (Union[bool, None, str]) – Metadata routing for axis parameter in predict.

Returns:

self – The updated object.

Return type:

LaplacianDetector