# SpectralClustering

### *class* cuml.cluster.SpectralClustering(n_clusters=8, , n_components=None, random_state=None, n_neighbors=10, n_init=10, eigen_tol='auto', affinity='nearest_neighbors', verbose=False, output_type=None)

Apply spectral clustering from the normalized Laplacian.

In practice spectral clustering is very useful when the structure of
the individual clusters is highly non-convex, or when a measure of
the center and spread of the cluster is not a suitable description
of the complete cluster, such as when clusters are nested circles on
the 2D plane.

If the affinity matrix is the adjacency matrix of a graph, this method
can be used to find normalized graph cuts.

When calling `fit`, an affinity matrix is constructed using a
k-nearest neighbors connectivity matrix.

Alternatively, a user-provided affinity matrix can be specified by
setting `affinity='precomputed'`.

* **Parameters:**
  **n_clusters**
  : The number of clusters to form.

  **n_components**
  : Number of eigenvectors to use for the spectral embedding. If None,
    defaults to n_clusters.

  **random_state**
  : A pseudo random number generator used for the initialization of the
    k-means clustering and the eigendecomposition. Use an int to make the
    results deterministic across calls.

  **n_neighbors**
  : Number of neighbors to use when constructing the affinity matrix using
    the nearest neighbors method. Ignored for `affinity='precomputed'`.

  **n_init**
  : Number of time the k-means algorithm will be run with different
    centroid seeds. The final results will be the best output of n_init
    consecutive runs in terms of inertia. Only used for the k-means step.

  **eigen_tol**
  : Tolerance for the eigensolver. If ‘auto’, a tolerance values of
    0.0 is used.

  **affinity**
  : How to construct the affinity matrix.
    : - ‘nearest_neighbors’ : construct the affinity matrix by computing a
        graph of nearest neighbors from the input data.
      - ‘precomputed’ : interpret X as a precomputed affinity matrix,
        where larger values indicate greater similarity between instances.

  **verbose**
  : Sets logging level. It must be one of `cuml.common.logger.level_*`.
    See [Verbosity Levels](../../cuml/index.html.md#verbosity-levels) for more info.

  **output_type**
  : Return results and set estimator attributes to the indicated output
    type. If None, the output type set at the module level
    (`cuml.global_settings.output_type`) will be used.
    See [Output Data Type Configuration](../../cuml/index.html.md#output-data-type-configuration) for more info.
* **Attributes:**
  **labels_**
  : Cluster labels for each sample.

### Methods

| [`fit`](#cuml.cluster.SpectralClustering.fit)(self, X[, y])         | Perform spectral clustering on `X`.                           |
|----------------------------------------------------------------------------|---------------------------------------------------------------|
| [`fit_predict`](#cuml.cluster.SpectralClustering.fit_predict)(self, X[, y]) | Perform spectral clustering on `X` and return cluster labels. |

### Notes

The eigensolver uses the Lanczos approach from the raft implementation
[https://docs.nvidia.com/raft/latest/pylibraft_api/sparse/#pylibraft.sparse.linalg.eigsh](https://docs.nvidia.com/raft/latest/pylibraft_api/sparse/#pylibraft.sparse.linalg.eigsh).

Kmeans is used for assigning labels.

### References

- Normalized cuts and image segmentation, 2000
  Jianbo Shi, Jitendra Malik
  [https://ieeexplore.ieee.org/document/868688](https://ieeexplore.ieee.org/document/868688)
- A Tutorial on Spectral Clustering, 2007
  Ulrike von Luxburg
  [https://arxiv.org/pdf/0711.0189](https://arxiv.org/pdf/0711.0189)
- Multiclass spectral clustering, 2003
  Stella X. Yu, Jianbo Shi
  [https://ieeexplore.ieee.org/document/1238361](https://ieeexplore.ieee.org/document/1238361)

### Examples

```pycon
>>> import cupy as cp
>>> from sklearn.datasets import make_blobs
>>> from cuml.cluster import SpectralClustering
>>> X, y = make_blobs(n_samples=100, centers=3, n_features=10,
...                   cluster_std=0.5, random_state=42)
>>> X = cp.asarray(X, dtype=cp.float32)
>>> sc = SpectralClustering(n_clusters=3, affinity='nearest_neighbors',
...                         n_neighbors=10, random_state=42)
>>> sc.fit(X)
SpectralClustering()
>>> sc.labels_[:10]
array([2, 0, 1, 1, 2, 2, 1, 0, 2, 0])
```

<!-- !! processed by numpydoc !! -->

#### as_sklearn()[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/interop.py#L206)

Convert this estimator into an equivalent scikit-learn (or scikit-learn
extension) estimator.

* **Returns:**
  sklearn.base.BaseEstimator
  : A scikit-learn compatible estimator instance that mirrors the trained
    state of the current estimator.

<!-- !! processed by numpydoc !! -->

#### fit(self, X, y=None) → 'SpectralClustering'[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/cluster/spectral_clustering.pyx#L262)

Perform spectral clustering on `X`.

* **Parameters:**
  **X**
  : Training vector, where `n_samples` is the number of samples
    and `n_features` is the number of features. If affinity is
    ‘precomputed’, X is the affinity matrix. Supported formats for
    precomputed affinity: scipy sparse (CSR, CSC, COO), cupy sparse
    (CSR, CSC, COO), dense numpy arrays, or dense cupy arrays.

  **y**
  : Not used, present here for API consistency by convention.
* **Returns:**
  **self**
  : Returns the instance itself.

<!-- !! processed by numpydoc !! -->

#### fit_predict(self, X, y=None)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/cluster/spectral_clustering.pyx#L238)

Perform spectral clustering on `X` and return cluster labels.

* **Parameters:**
  **X**
  : Training vector, where `n_samples` is the number of samples
    and `n_features` is the number of features. If affinity is
    ‘precomputed’, X is the affinity matrix. Supported formats for
    precomputed affinity: scipy sparse (CSR, CSC, COO), cupy sparse
    (CSR, CSC, COO), dense numpy arrays, or dense cupy arrays.

  **y**
  : Not used, present here for API consistency by convention.
* **Returns:**
  **labels**
  : Cluster labels.

<!-- !! processed by numpydoc !! -->

#### *classmethod* from_sklearn(model)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/interop.py#L222)

Create a cuml estimator from a scikit-learn estimator.

* **Parameters:**
  **model**
  : A compatible scikit-learn (or scikit-learn extension) estimator.
* **Returns:**
  cls
  : A new instance of this cuml estimator class that mirrors the
    state of the input estimator.

### Notes

`output_type` of the estimator is set to “numpy” by default, as these
cannot be inferred from training arguments. If something different is
required, then please use cuml’s output_type configuration utilities.

<!-- !! processed by numpydoc !! -->

#### get_params(deep=True)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/base.py#L191)

Returns a dict of all params owned by this class. If the child class
has appropriately overridden the `_get_param_names` method and does not
need anything other than what is there in this method, then it doesn’t
have to override this method

<!-- !! processed by numpydoc !! -->

#### set_params(\*\*params)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/base.py#L200)

Accepts a dict of params and updates the corresponding ones owned by
this class. If the child class has appropriately overridden the
`_get_param_names` method and does not need anything other than what is,
there in this method, then it doesn’t have to override this method

<!-- !! processed by numpydoc !! -->
