milia.cluster.models.spectral#

Spectral clustering on a k-nearest-neighbour graph, with an eigengap estimate of k.

Functions

eigengap(affinity[, candidates])

Number of clusters suggested by the largest gap in the Laplacian spectrum.

Classes

Spectral([n_clusters, n_neighbors, ...])

Normalised spectral clustering (Ng, Jordan and Weiss, 2001).

SpectralConfig(*[, name, kind, space, ...])

Validated hyperparameters of the spectral clusterer.

milia.cluster.models.spectral.eigengap(affinity, candidates=15)#

Number of clusters suggested by the largest gap in the Laplacian spectrum.

Uses the unnormalised graph Laplacian D - W of an affinity matrix W; the k with the largest jump between consecutive smallest eigenvalues is the eigengap heuristic’s read of the number of clusters (von Luxburg, 2007).

Parameters:
  • affinity (ndarray | spmatrix) – Symmetric affinity matrix, dense or sparse.

  • candidates (int) – How many of the smallest eigenvalues to inspect.

Return type:

int

Returns:

The suggested number of clusters, at least 1.

Examples

>>> import numpy as np
>>> blocks = np.kron(np.eye(3), np.ones((4, 4)))
>>> eigengap(blocks)
3
class milia.cluster.models.spectral.Spectral(n_clusters=3, n_neighbors=10, candidates=15, random_state=0)#

Bases: BaseClusterer

Normalised spectral clustering (Ng, Jordan and Weiss, 2001).

The neighbour count is capped below the sample count so small populations do not fail. After fitting, eigengap_ holds the eigengap heuristic’s independent estimate of the number of clusters.

Parameters:
  • n_clusters (int) – Number of clusters.

  • n_neighbors (int) – Neighbours in the affinity graph.

  • candidates (int) – Eigenvalues inspected for eigengap_.

  • random_state (int | None) – Seed for the eigensolver and the label assignment.

Examples

>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> X = np.repeat(np.array([[0.0, 0.0], [6.0, 6.0], [0.0, 6.0]]), 20, axis=0) + rng.normal(
...     scale=0.4, size=(60, 2)
... )
>>> Spectral(n_clusters=3).fit(X).n_clusters_
3
class milia.cluster.models.spectral.SpectralConfig(*, name='spectral', kind='clusterer', space=SearchSpace(n_clusters=(2, 12), n_neighbors=(5, 30)), n_clusters=3, n_neighbors=10, candidates=15, random_state=0)#

Bases: BaseModelConfig

Validated hyperparameters of the spectral clusterer.

Fields mirror Spectral’s constructor; space is the default Optuna search space. Build the clusterer with make("clusterer", "spectral", ...) or Spectral(**config.params()).

Examples

>>> SpectralConfig().name
'spectral'