Skip to content

cluster_spectral

cluster_spectral

cluster_spectral(info: DataFrame, *, k: int, n_neighbors: int = 10) -> DataFrame

Topological clustering: geographic kNN affinity → Laplacian spectrum → k-means.

Returns info with a spectral_cluster column. Groups by network significance rather than raw distance (e.g. a bridge or a corridor).

See Also

cluster_spatial : Density-based proximity zones. cluster_diurnal_profiles : Behavioural instead of spatial clusters.

Examples:

>>> import pandas as pd
>>> info = pd.DataFrame({
...     "station_id": list("abcdef"),
...     "lat": [48.85, 48.8501, 48.8502, 48.95, 48.9501, 48.9502],
...     "lon": [2.35, 2.3501, 2.3502, 2.45, 2.4501, 2.4502],
... })
>>> int(cluster_spectral(info, k=2)["spectral_cluster"].nunique())
2
Source code in src/gbfs_toolkit/analytics/clustering.py
def cluster_spectral(info: pd.DataFrame, *, k: int, n_neighbors: int = 10) -> pd.DataFrame:
    """Topological clustering: geographic kNN affinity → Laplacian spectrum → k-means.

    Returns ``info`` with a ``spectral_cluster`` column. Groups by network significance
    rather than raw distance (e.g. a bridge or a corridor).

    See Also
    --------
    [`cluster_spatial`][gbfs_toolkit.cluster_spatial] : Density-based proximity zones.
    [`cluster_diurnal_profiles`][gbfs_toolkit.cluster_diurnal_profiles] : Behavioural instead of spatial clusters.

    Examples
    --------
    >>> import pandas as pd
    >>> info = pd.DataFrame({
    ...     "station_id": list("abcdef"),
    ...     "lat": [48.85, 48.8501, 48.8502, 48.95, 48.9501, 48.9502],
    ...     "lon": [2.35, 2.3501, 2.3502, 2.45, 2.4501, 2.4502],
    ... })
    >>> int(cluster_spectral(info, k=2)["spectral_cluster"].nunique())
    2
    """
    _require_sklearn()
    out = info.reset_index(drop=True).copy()
    n = len(out)
    if n == 0:
        out["spectral_cluster"] = pd.Series(dtype="int64")
        return out
    from sklearn.cluster import SpectralClustering

    xy = _project_xy(out["lat"], out["lon"])
    sc = SpectralClustering(
        n_clusters=min(k, n),
        affinity="nearest_neighbors",
        n_neighbors=min(n_neighbors, max(1, n - 1)),
        assign_labels="kmeans",
        random_state=0,
    )
    out["spectral_cluster"] = sc.fit_predict(xy).astype("int64")
    return out