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 viamethod. The two stages are controlled by independent parameters:transformerselects the kNN search backend,methodselects the connectivity kernel.Array type support# Array type
supported
… experimentally in dask
Array✅
❌
✅
❌
- 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
knnisTrue, number of nearest neighbors to be searched. IfknnisFalse, a Gaussian kernel width is set to the distance of then_neighborsneighbor.ignored if
transformeris an instance.- n_pcs
int|None(default:None) Use this many PCs. If
n_pcs==0use.Xifuse is None.- use
LayerAcc|MultiAcc|str|None(default:None) Use the indicated representation: a
LayerAcc(e.g.A.X,A.layers[...]) orMultiAcc(e.g.A.obsm[...]).strs areresolve()d, e.g.'obsm.pca'.If
None, the representation is chosen automatically: For.n_vars<N_PCS(default: 50),.Xis used, otherwise the PCA representation (.obsm['X_pca'], or.obsm['pca']if it was computed underScanpyV2Preview). If it is not present, it’s computed with default parameters orn_pcsif present.- use_rep
str|None(default:None) Deprecated since version 1.13.0: Use
useinstead.'X'or a key ofobsm, i.e.use_rep='k'isuse=A.obsm['k']anduse_rep='X'isuse=A.X.- knn
bool(default:True) If
True, use a hard threshold to restrict the number of neighbors ton_neighbors, that is, consider a knn graph. Otherwise, use a Gaussian Kernel to assign low weights to neighbors more distant than then_neighborsnearest 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'
- 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
distancesis given, this parameter is simply stored in.uns(see below), otherwise defaults to'euclidean'.ignored if
transformeris an instance.- metric_kwds
Mapping[str,Any] (default:mappingproxy({})) Options for the metric.
ignored if
transformeris an instance.- rng
int|integer|Sequence[int] |SeedSequence|Generator|BitGenerator|None(default:None) Random number generation to control stochasticity.
If a type:
SeedLikevalue, it’s used to seed a new random number generator; If anumpy.random.Generator,rng’s state will be directly advanced; IfNone, a non-reproducible random number generator is used. Seenumpy.random.default_rng()for more details.The default value matches legacy scanpy behavior and will change to
Nonein scanpy 2.0.ignored if
transformeris an instance.- out
GraphAcc|str|NeighborsOut|bool(default:False) Where to write the outputs. A single accessor writes
connectivitiesto it and names the others after its keyk:kin kinds of places no other output goes to, elsek_{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 areanndata.acc.AdAcc.resolve()d. Theunsentry is named afterconnectivities’s key, so a mapping has to includeconnectivities. IfTrue, they are returned as aNeighborsResultinstead of written. IfFalse, they are written to their default locations. The outputs are:connectivitiesThe weighted adjacency matrix. By default written to
A.obsp['connectivities'].distancesThe distance matrix. By default written to
A.obsp['distances'].
- key_added
str|None(default:None) Deprecated since version 1.13.0: Use
outinstead.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
adatabefore calling this function instead.Return a copy instead of writing to adata.
- adata
- Return type:
- Returns:
Returns the outputs if
out=True, elseNone. By default sets the following fields (seeoutfor others):adata.obsp['connectivities']scipy.sparse.csr_matrix(dtypefloat)Weighted adjacency matrix of the neighborhood graph of data points. Weights should be interpreted as connectivities.
adata.obsp['distances']scipy.sparse.csr_matrix(dtypefloat)Distance matrix of the nearest neighbors search. Each row (cell) has
n_neighbors-1 non-zero entries. These are the distances to theirn_neighbors-1 nearest neighbors (excluding the cell itself).adata.uns['neighbors']dictneighbors parameters, and the
.obspkeys 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`
See also