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):

ndarray, spmatrix, or sparray

dask.array.Array

chunked=False, zero_center=True

sklearn PCA ('arpack')

  • dense: dask-ml PCA[1] ('auto')

  • sparse or svd_solver='covariance_eigh': custom implementation ('covariance_eigh')

chunked=False, zero_center=False

sklearn TruncatedSVD ('randomized')

dask-ml TruncatedSVD[2] ('tsqr')

chunked=True (zero_center ignored)

sklearn IncrementalPCA ('auto')

dask-ml IncrementalPCA[3] ('auto')

Array type support#

Array type

supported

… experimentally in dask Array

numpy.ndarray

✅

✅

scipy.sparse.csr_array / csr_matrix

✅

✅

scipy.sparse.csc_array / csc_matrix

✅

❌

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'] or A.obsm['pca']. strs are anndata.acc.AdAcc.resolve()d, e.g. 'layers.counts'.

layer str | None (default: None)

Deprecated since version 1.13.0: Use use instead.

A key of layers, i.e. layer='k' is use=A.layers['k'].

obsm str | None (default: None)

Deprecated since version 1.13.0: Use use instead.

A key of obsm, i.e. obsm='k' is use=A.obsm['k'].

zero_center bool (default: True)

If True, compute (or approximate) PCA from covariance matrix. If False, 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 chunked and zero_center, as well as the default solver for each class when svd_solver=None.

Efficient computation of the principal components of a sparse matrix currently only works with the 'arpack’ or 'covariance_eigh’ solver.

None

Choose 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 of chunk_size. Automatically zero centers and ignores settings of zero_center, random_seed and svd_solver. If False, perform a full PCA/truncated SVD (see svd_solver and zero_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=True was passed.

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.

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 are anndata.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 mask instead.

A boolean array, or a column of var named by a str, i.e. mask_var='selected' is mask=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 embedding 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. {'embedding': A.obsm['pca']}. strs are anndata.acc.AdAcc.resolve()d. The uns entry is named after embedding’s key, so a mapping has to include embedding. If True, they are returned as a PcaResult instead of written. If False, they are written to their default locations. The outputs are:

embedding

The PCA representation. By default written to A.obsm['X_pca'] (A.obsm['pca'] if scanpy.settings.preset is ScanpyV2Preview).

loadings

The principal components containing the loadings. By default written to A.varm['PCs'] (A.varm['pca'] if scanpy.settings.preset is ScanpyV2Preview). If use points to .obsm, stored in the .uns entry instead.

key_added str | None (default: None)

Deprecated since version 1.13.0: Use out instead.

key_added='k' is out={'embedding': A.obsm['k'], 'loadings': A.varm['k']}.

Only valid if data is an AnnData. With out=True, the .uns entry (including the variance) is neither written nor returned, use array input with return_info=True to get it.

copy bool (default: False)

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

If an AnnData is passed, determines whether a copy is returned. Is ignored otherwise.

Return type:

AnnData | PcaResult | ndarray | csr_array | csc_array | csr_matrix | csc_matrix | None

Returns:

If data is array-like and return_info=False was passed,

this function returns the PCA representation of data as an array of the same type as the input array. If return_info=True was passed, it returns a tuple of the PCA representation, components, variance ratio and variance.

Otherwise, it returns the outputs as a PcaResult if out=True, else None. By default sets the following fields (see out for 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.