scanpy.pp.neighbors#

scanpy.pp.neighbors(adata, n_neighbors=15, n_pcs=None, *, distances=None, use=None, use_rep=None, knn=True, method='umap', transformer=None, metric=None, metric_kwds=mappingproxy({}), rng=None, out=False, key_added=None, copy=False)[source]#

Compute the nearest neighbors distance matrix and a neighborhood graph of observations [McInnes et al., 2018].

The computation proceeds in two independent stages. First, a k-nearest neighbor (kNN) search produces the distance matrix via the estimator passed as transformer. Second, connectivities are derived from the kNN search output by the kernel selected via method. The two stages are controlled by independent parameters: transformer selects the kNN search backend, method selects the connectivity kernel.

Array type support#

Array type

supported

… experimentally in dask Array

numpy.ndarray

✅

❌

scipy.sparse.{csr,csc}_{array,matrix}

✅

❌

Parameters:
adata AnnData

Annotated data matrix.

n_neighbors int (default: 15)

The size of local neighborhood (in terms of number of neighboring data points) used for manifold approximation. Larger values result in more global views of the manifold, while smaller values result in more local data being preserved. In general values should be in the range 2 to 100. If knn is True, number of nearest neighbors to be searched. If knn is False, a Gaussian kernel width is set to the distance of the n_neighbors neighbor.

ignored if transformer is an instance.

n_pcs int | None (default: None)

Use this many PCs. If n_pcs==0 use .X if use is None.

use LayerAcc | MultiAcc | str | None (default: None)

Use the indicated representation: a LayerAcc (e.g. A.X, A.layers[...]) or MultiAcc (e.g. A.obsm[...]). strs are resolve()d, e.g. 'obsm.pca'.

If None, the representation is chosen automatically: For .n_vars < N_PCS (default: 50), .X is used, otherwise the PCA representation (.obsm['X_pca'], or .obsm['pca'] if it was computed under ScanpyV2Preview). If it is not present, it’s computed with default parameters or n_pcs if present.

use_rep str | None (default: None)

Deprecated since version 1.13.0: Use use instead.

'X' or a key of obsm, i.e. use_rep='k' is use=A.obsm['k'] and use_rep='X' is use=A.X.

knn bool (default: True)

If True, use a hard threshold to restrict the number of neighbors to n_neighbors, that is, consider a knn graph. Otherwise, use a Gaussian Kernel to assign low weights to neighbors more distant than the n_neighbors nearest neighbor.

method Literal['umap', 'gauss', 'jaccard'] (default: 'umap')

Kernel that derives connectivities from the kNN search output. The choice is independent of the kNN search backend, which is controlled by transformer. Use ‘umap’ [McInnes et al., 2018], ‘gauss’ (Gauss kernel following Coifman et al. [2005] with adaptive width Haghverdi et al. [2016]), or ‘jaccard’ (Jaccard kernel as in PhenoGraph, Levine et al. [2015]).

transformer KnnTransformerLike | Literal['pynndescent', 'sklearn'] | None (default: None)

kNN search backend following the API of KNeighborsTransformer. See Using other kNN libraries in Scanpy for more details. Also accepts the following known options:

None (the default)

Behavior depends on data size. For small data, we will calculate exact kNN, otherwise we use PyNNDescentTransformer

'pynndescent'

PyNNDescentTransformer

metric Literal['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan'] | Literal['braycurtis', 'canberra', 'chebyshev', 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] | Callable[[ndarray, ndarray], float] | None (default: None)

A known metric’s name or a callable that returns a distance. If distances is given, this parameter is simply stored in .uns (see below), otherwise defaults to 'euclidean'.

ignored if transformer is an instance.

metric_kwds Mapping[str, Any] (default: mappingproxy({}))

Options for the metric.

ignored if transformer is an instance.

rng int | integer | Sequence[int] | SeedSequence | Generator | BitGenerator | None (default: None)

Random number generation to control stochasticity.

If a type:SeedLike value, it’s used to seed a new random number generator; If a numpy.random.Generator, rng’s state will be directly advanced; If None, a non-reproducible random number generator is used. See numpy.random.default_rng() for more details.

The default value matches legacy scanpy behavior and will change to None in scanpy 2.0.

ignored if transformer is an instance.

out GraphAcc | str | NeighborsOut | bool (default: False)

Where to write the outputs. A single accessor writes connectivities to it and names the others after its key k: k in kinds of places no other output goes to, else k_{name}, e.g. .obsp['k_distances'] next to .obsp['k']. Outputs that aren’t written by default stay unwritten. A mapping from output names to accessors writes only the outputs it names, each to a different place, e.g. {'connectivities': A.obsp['conns']}. strs are anndata.acc.AdAcc.resolve()d. The uns entry is named after connectivities’s key, so a mapping has to include connectivities. If True, they are returned as a NeighborsResult instead of written. If False, they are written to their default locations. The outputs are:

connectivities

The weighted adjacency matrix. By default written to A.obsp['connectivities'].

distances

The distance matrix. By default written to A.obsp['distances'].

key_added str | None (default: None)

Deprecated since version 1.13.0: Use out instead.

key_added='k' wrote .obsp['k_connectivities'], .obsp['k_distances'], and .uns['k']. out=A.obsp['k'] writes .obsp['k'], .obsp['k_distances'], and .uns['k'] instead.

copy bool (default: False)

Deprecated since version 1.13.0: Copy adata before calling this function instead.

Return a copy instead of writing to adata.

Return type:

AnnData | NeighborsResult | None

Returns:

Returns the outputs if out=True, else None. By default sets the following fields (see out for others):

adata.obsp['connectivities']scipy.sparse.csr_matrix (dtype float)

Weighted adjacency matrix of the neighborhood graph of data points. Weights should be interpreted as connectivities.

adata.obsp['distances']scipy.sparse.csr_matrix (dtype float)

Distance matrix of the nearest neighbors search. Each row (cell) has n_neighbors-1 non-zero entries. These are the distances to their n_neighbors-1 nearest neighbors (excluding the cell itself).

adata.uns['neighbors']dict

neighbors parameters, and the .obsp keys the matrices were written to.

Examples

>>> import scanpy as sc
>>> adata = sc.datasets.pbmc68k_reduced()
>>> # Basic usage
>>> sc.pp.neighbors(adata, 20, metric="cosine")
>>> # Provide your own transformer for more control and flexibility
>>> from sklearn.neighbors import KNeighborsTransformer
>>> transformer = KNeighborsTransformer(
...     n_neighbors=10, metric="manhattan", algorithm="kd_tree"
... )
>>> sc.pp.neighbors(adata, transformer=transformer)
>>> # now you can e.g. access the index: `transformer._tree`