scanpy.pp.pca#
- scanpy.pp.pca(data, n_comps=None, *, use=None, zero_center=True, svd_solver=None, chunked=False, chunk_size=None, rng=None, return_info=False, mask=adata.var.get('highly_variable'), dtype='float32', out=False, key_added=None, copy=False, layer=None, obsm=None, mask_var=None)[source]#
Principal component analysis [Pedregosa et al., 2011].
Computes PCA coordinates, loadings and variance decomposition. Uses the following implementations (and defaults for
svd_solver):chunked=False,zero_center=Truesklearn
PCA('arpack')chunked=False,zero_center=Falsesklearn
TruncatedSVD('randomized')dask-ml
TruncatedSVD[2] ('tsqr')chunked=True(zero_centerignored)sklearn
IncrementalPCA('auto')dask-ml
IncrementalPCA[3] ('auto')Array type support# Array type
supported
… experimentally in dask
Array✅
✅
✅
✅
✅
❌
- Parameters:
- data
AnnData|ndarray|csr_array|csc_array|csr_matrix|csc_matrix The (annotated) data matrix of shape
n_obs×n_vars. Rows correspond to cells and columns to genes.- n_comps
int|None(default:None) Number of principal components to compute. Defaults to 50, or 1 - minimum dimension size of selected representation.
- use
LayerAcc|MultiAcc|str|None(default:None) Which matrix to run PCA on. Given by an accessor, e.g.
A.X,A.layers['counts']orA.obsm['pca'].strs areanndata.acc.AdAcc.resolve()d, e.g.'layers.counts'.- layer
str|None(default:None) Deprecated since version 1.13.0: Use
useinstead.A key of
layers, i.e.layer='k'isuse=A.layers['k'].- obsm
str|None(default:None) Deprecated since version 1.13.0: Use
useinstead.A key of
obsm, i.e.obsm='k'isuse=A.obsm['k'].- zero_center
bool(default:True) If
True, compute (or approximate) PCA from covariance matrix. IfFalse, performa a truncated SVD instead of PCA.Our default PCA algorithms (see
svd_solver) support implicit zero-centering, and therefore efficiently operating on sparse data.- svd_solver
Literal['auto','full','tsqr','randomized'] |Literal['tsqr','randomized'] |Literal['auto','full','randomized'] |Literal['arpack','covariance_eigh'] |Literal['arpack','covariance_eigh'] |Literal['arpack','randomized'] |Literal['covariance_eigh'] |None(default:None) SVD solver to use. See table above to see which solver class is used based on
chunkedandzero_center, as well as the default solver for each class whensvd_solver=None.Efficient computation of the principal components of a sparse matrix currently only works with the
'arpack’ or'covariance_eigh’ solver.NoneChoose automatically based on solver class (see table above).
'arpack'ARPACK wrapper in SciPy (
svds()). Not available for dask arrays.'covariance_eigh'Classic eigendecomposition of the covariance matrix, suited for tall-and-skinny matrices. With dask, array must be CSR or dense and chunked as
(N, adata.shape[1]).'randomized'Randomized algorithm from Halko et al. [2009]. For dask arrays, this will use
svd_compressed().'auto'Choose automatically depending on the size of the problem: Will use
'full'for small shapes and'randomized'for large shapes.'tsqr'“tall-and-skinny QR” algorithm from Benson et al. [2013]. Only available for dense dask arrays.
Changed in version 1.9.3: Default value changed from
'arpack'to None.Changed in version 1.4.5: Default value changed from
'auto'to'arpack'.- chunked
bool(default:False) If
True, perform an incremental PCA on segments ofchunk_size. Automatically zero centers and ignores settings ofzero_center,random_seedandsvd_solver. IfFalse, perform a full PCA/truncated SVD (seesvd_solverandzero_center). See table above for which solver class is used.- chunk_size
int|None(default:None) Number of observations to include in each chunk. Required if
chunked=Truewas passed.- 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.- return_info
bool(default:False) Only relevant when not passing an
AnnData: see “Returns”.- mask
NDArray[bool] |AdRef[Idx2D|int,AnnData] |str|Default|None(default:adata.var.get('highly_variable')) To run only on a certain set of genes. Given by a boolean array or a reference to one, e.g.
A.var['selected'].strs areanndata.acc.AdAcc.resolve()d, e.g.'var.selected'. By default, uses.var['highly_variable']if available, else everything.- mask_var
NDArray[bool] |AdRef[Idx2D|int,AnnData] |str|None(default:None) Deprecated since version 1.13.0: Use
maskinstead.A boolean array, or a column of
varnamed by astr, i.e.mask_var='selected'ismask=A.var['selected'].- dtype
DTypeLike(default:'float32') Numpy data type string to which to convert the result.
- out
MultiAcc|str|PcaOut|bool(default:False) Where to write the outputs. A single accessor writes
embeddingto 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.{'embedding': A.obsm['pca']}.strs areanndata.acc.AdAcc.resolve()d. Theunsentry is named afterembedding’s key, so a mapping has to includeembedding. IfTrue, they are returned as aPcaResultinstead of written. IfFalse, they are written to their default locations. The outputs are:embeddingThe PCA representation. By default written to
A.obsm['X_pca'](A.obsm['pca']ifscanpy.settings.presetisScanpyV2Preview).loadingsThe principal components containing the loadings. By default written to
A.varm['PCs'](A.varm['pca']ifscanpy.settings.presetisScanpyV2Preview). Ifusepoints to.obsm, stored in the.unsentry instead.
- key_added
str|None(default:None) Deprecated since version 1.13.0: Use
outinstead.key_added='k'isout={'embedding': A.obsm['k'], 'loadings': A.varm['k']}.Only valid if
datais anAnnData. Without=True, the.unsentry (including the variance) is neither written nor returned, use array input withreturn_info=Trueto get it.- copy
bool(default:False) Deprecated since version 1.13.0: Copy
adatabefore calling this function instead.If an
AnnDatais passed, determines whether a copy is returned. Is ignored otherwise.
- data
- Return type:
AnnData|PcaResult|ndarray|csr_array|csc_array|csr_matrix|csc_matrix|None- Returns:
- If
datais array-like andreturn_info=Falsewas passed, this function returns the PCA representation of
dataas an array of the same type as the input array. Ifreturn_info=Truewas passed, it returns a tuple of the PCA representation, components, variance ratio and variance.
Otherwise, it returns the outputs as a
PcaResultifout=True, elseNone. By default sets the following fields (seeoutfor others):.obsm['X_pca']csr_matrix|csc_matrix|ndarray(shape(adata.n_obs, n_comps))PCA representation of data.
.varm['PCs']ndarray(shape(adata.n_vars, n_comps))The principal components containing the loadings unless `use` points to `.obsm`.
.uns['pca']['components']ndarray(shape(adata.obsm[...].shape[1], n_comps))The principal components containing the loadings when `use` points to `.obsm`.
.uns['pca']['variance_ratio']ndarray(shape(n_comps,))Ratio of explained variance.
.uns['pca']['variance']ndarray(shape(n_comps,))Explained variance, equivalent to the eigenvalues of the covariance matrix.
- If