scviva.module.nicheVAE#
- class scviva.module.nicheVAE(n_input, n_output_niche, n_batch=0, n_labels=0, n_hidden=128, n_latent=10, n_layers=1, n_layers_niche=1, n_layers_compo=1, n_hidden_niche=128, n_hidden_compo=128, n_continuous_cov=0, n_cats_per_cov=None, dropout_rate=0.1, dispersion='gene', log_variational=True, gene_likelihood='poisson', latent_distribution='normal', niche_likelihood='gaussian', cell_rec_weight=1.0, latent_kl_weight=1.0, spatial_weight=10, prior_mixture=False, prior_mixture_k=20, semisupervised=True, linear_classifier=True, inpute_covariates_niche_decoder=True, encode_covariates=False, deeply_inject_covariates=True, batch_representation='one-hot', use_batch_norm='none', use_layer_norm='both', use_size_factor_key=False, use_observed_lib_size=True, library_log_means=None, library_log_vars=None, batch_embedding_kwargs=None, extra_decoder_kwargs=None, extra_encoder_kwargs=None, **vae_kwargs)[source]#
Variational auto-encoder with niche decoders [Levy et al., 2025].
- Parameters:
- n_input
int Number of input features.
- n_output_niche
int Dimensionality of the niche state (per cell type) predicted by the niche state decoder (
NicheDecoder).- n_batch
int Number of batches. If
0, no batch correction is performed.- n_labels
int Number of labels.
- n_hidden
int Number of nodes per hidden layer. Passed into
EncoderandDecoderSCVI.- n_latent
int Dimensionality of the latent space.
- n_layers
int Number of hidden layers. Passed into
EncoderandDecoderSCVI.- n_layers_niche
int Number of hidden layers in the niche state decoder.
- n_layers_compo
int Number of hidden layers in the composition decoder.
- n_hidden_niche
int Number of nodes per hidden layer in the niche state decoder.
- n_hidden_compo
int Number of nodes per hidden layer in the composition decoder.
- n_continuous_cov
int Number of continuous covariates.
- n_cats_per_cov
list[int] |None A list of integers containing the number of categories for each categorical covariate.
- dropout_rate
float Dropout rate. Passed into
Encoderbut notDecoderSCVI.- dispersion
Literal['gene','gene-batch','gene-label','gene-cell'] Flexibility of the dispersion parameter when
gene_likelihoodis either"nb"or"zinb". One of the following:"gene": parameter is constant per gene across cells."gene-batch": parameter is constant per gene per batch."gene-label": parameter is constant per gene per label."gene-cell": parameter is constant per gene per cell.
- log_variational
bool If
True, uselog1p()on input data before encoding for numerical stability (not normalization).- gene_likelihood
Literal['zinb','nb','poisson'] Distribution to use for reconstruction in the generative process. One of the following:
"nb":NegativeBinomial."zinb":ZeroInflatedNegativeBinomial."poisson":Poisson.
- latent_distribution
Literal['normal','ln'] Distribution to use for the latent space. One of the following:
"normal": isotropic normal."ln": logistic normal with normal params N(0, 1).
- niche_likelihood
Literal['poisson','gaussian'] Distribution to use for the niche state. One of the following:
"poisson":Poisson."gaussian":Normal.
Default is
"gaussian"and Poisson should be used if the niche state is count data.- cell_rec_weight
float Weight of the cell reconstruction loss.
- latent_kl_weight
float Weight of the latent KL divergence.
- spatial_weight
float Weight of the spatial losses
- prior_mixture
bool If
True, use a mixture of Gaussians for the latent space. Else, use unimodal Gaussian.- prior_mixture_k
int Number of components in the Gaussian mixture.
- semisupervised
bool If
True, use a classifier to predict cell type labels from the latent space.- linear_classifier
bool If
True, use a linear classifier. Else, use a neural network.- inpute_covariates_niche_decoder
bool If
True, covariates are concatenated to the input of the niche state decoder.- encode_covariates
bool If
True, covariates are concatenated to gene expression prior to passing through the encoder(s). Else, only gene expression is used.- deeply_inject_covariates
bool If
Trueandn_layers > 1, covariates are concatenated to the outputs of hidden layers in the encoder(s) (ifencoder_covariatesisTrue) and the decoder prior to passing through the next layer.- batch_representation
Literal['one-hot','embedding'] EXPERIMENTALMethod for encoding batch information. One of the following:"one-hot": represent batches with one-hot encodings."embedding": represent batches with continuously-valued embeddings usingEmbedding.
Note that batch representations are only passed into the encoder(s) if
encode_covariatesisTrue.- use_batch_norm
Literal['encoder','decoder','none','both'] Specifies where to use
BatchNorm1din the model. One of the following:"none": don’t use batch norm in either encoder(s) or decoder."encoder": use batch norm only in the encoder(s)."decoder": use batch norm only in the decoder."both": use batch norm in both encoder(s) and decoder.
Note: if
use_layer_normis also specified, both will be applied (firstBatchNorm1d, thenLayerNorm).- use_layer_norm
Literal['encoder','decoder','none','both'] Specifies where to use
LayerNormin the model. One of the following:"none": don’t use layer norm in either encoder(s) or decoder."encoder": use layer norm only in the encoder(s)."decoder": use layer norm only in the decoder."both": use layer norm in both encoder(s) and decoder.
Note: if
use_batch_normis also specified, both will be applied (firstBatchNorm1d, thenLayerNorm).- use_size_factor_key
bool If
True, use theobscolumn as defined by thesize_factor_keyparameter in the model’ssetup_anndatamethod as the scaling factor in the mean of the conditional distribution. Takes priority overuse_observed_lib_size.- use_observed_lib_size
bool If
True, use the observed library size for RNA as the scaling factor in the mean of the conditional distribution.- library_log_means
ndarray|None ndarrayof shape(1, n_batch)of means of the log library sizes that parameterize the prior on library size ifuse_size_factor_keyisFalseanduse_observed_lib_sizeisFalse.- library_log_vars
ndarray|None ndarrayof shape(1, n_batch)of variances of the log library sizes that parameterize the prior on library size ifuse_size_factor_keyisFalseanduse_observed_lib_sizeisFalse.- extra_decoder_kwargs
dict|None Additional keyword arguments passed into
DecoderSCVI.- batch_embedding_kwargs
dict|None Keyword arguments passed into
Embeddingifbatch_representationis set to"embedding".- extra_encoder_kwargs
dict|None Additional keyword arguments passed into
Encoder.- **vae_kwargs
Keyword args for
VAE.
- n_input
Notes
Lifecycle: argument
batch_representationis experimental in v1.2.
Attributes table
Dictionary of embeddings. |
|
The type of minified data associated with this module, if applicable. |
|
Methods table
|
Add an embedding to the module. |
|
Forward pass for an embedding. |
|
Forward pass through the network. |
|
Run the generative process. |
|
Get an embedding from the module. |
|
Main inference call site. |
|
Initialize an embedding in the module. |
|
Compute the loss. |
|
Compute the marginal log-likelihood of the data under the model. |
|
Callback function run in |
|
Remove an embedding from the module. |
|
Generate predictive samples from the posterior predictive distribution. |
Attributes
- nicheVAE.device#
- nicheVAE.embeddings_dict#
Dictionary of embeddings.
- nicheVAE.minified_data_type#
The type of minified data associated with this module, if applicable.
Methods
- nicheVAE.add_embedding(key, embedding, overwrite=False)[source]#
Add an embedding to the module.
- Return type:
- nicheVAE.forward(tensors, get_inference_input_kwargs=None, get_generative_input_kwargs=None, inference_kwargs=None, generative_kwargs=None, loss_kwargs=None, compute_loss=True)[source]#
Forward pass through the network.
- Parameters:
- tensors
tensors to pass through
- get_inference_input_kwargs
dict|None Keyword args for
_get_inference_input()- get_generative_input_kwargs
dict|None Keyword args for
_get_generative_input()- inference_kwargs
dict|None Keyword args for
inference()- generative_kwargs
dict|None Keyword args for
generative()- loss_kwargs
dict|None Keyword args for
loss()- compute_loss
Whether to compute loss on forward pass. This adds another return value.
- Return type:
- nicheVAE.generative(z, library, batch_index, cont_covs=None, cat_covs=None, size_factor=None, y=None, transform_batch=None)[source]#
Run the generative process.
- Parameters:
- z
Tensor Latent values with shape
(n_cells, n_latent)(or with a leading sample dimension).- library
Tensor Log library size of each cell. Used as the size factor unless
use_size_factor_key=True.- batch_index
Tensor Batch index of each cell, with shape
(n_cells, 1).- cont_covs
Tensor|None Continuous covariates, concatenated to
zas decoder input.Noneif no continuous covariates are registered.- cat_covs
Tensor|None Categorical covariates, with one column per covariate, passed to the decoders.
Noneif no categorical covariates are registered.- size_factor
Tensor|None Log size factor of each cell. Only used when
use_size_factor_key=True; otherwiselibraryis used.- y
Tensor|None Label of each cell, with shape
(n_cells, 1). Passed to the expression decoder, used to select the dispersion whendispersion="gene-label"and, for a semi-supervised mixture prior, to bias the prior mixture weights toward the cell’s label.- transform_batch
Tensor|None If not
None, replace the batch index of every cell with this value before decoding.
- z
- Return type:
dict[str,Distribution|None]- Returns:
Dictionary with the expression likelihood (
px), the library-size prior (pl,Nonewhenuse_observed_lib_size=True), the latent prior (pz), the niche state mean and variance, the niche state likelihood and the niche compositionDirichletdistribution.
- nicheVAE.inference(*args, **kwargs)[source]#
Main inference call site.
Branches off to regular or cached inference depending on whether we have a minified adata that contains the latent posterior parameters.
- nicheVAE.init_embedding(key, num_embeddings, embedding_dim=5, **kwargs)[source]#
Initialize an embedding in the module.
- Return type:
- nicheVAE.loss(tensors, inference_outputs, generative_outputs, kl_weight=1.0, classification_ratio=50, epsilon=1e-06, n_samples_mixture=10)[source]#
Compute the loss.
- Parameters:
- tensors
dict[str,Tensor] Dictionary of minibatch tensors; uses the registered counts, labels (if semi-supervised), niche composition and per-cell-type niche embeddings.
- inference_outputs
dict[str,Tensor|Distribution|None] Output of
inference().- generative_outputs
dict[str,Tensor|Distribution|None] Output of
generative().- kl_weight
float Weight of the KL divergence on
z(used for KL warmup). The library-size KL term is not scaled by it.- classification_ratio
Weight of the cell-type classification loss added to the per-cell reconstruction loss. Only used when the model is semi-supervised.
- epsilon
float Pseudocount added to the observed niche composition before renormalizing it, so that its Dirichlet log-likelihood is finite.
- n_samples_mixture
int Number of posterior samples used for the Monte Carlo estimate of the KL divergence on
zwhen a mixture prior is used (prior_mixture=True).
- tensors
- Return type:
NicheLossOutput- Returns:
NicheLossOutputwith the total loss and its expression, niche state, niche composition, KL and (if semi-supervised) classification components.
- nicheVAE.marginal_ll(tensors, n_mc_samples, return_mean=False, n_mc_samples_per_pass=1)[source]#
Compute the marginal log-likelihood of the data under the model.
- Parameters:
- tensors
dict[str,Tensor] Dictionary of tensors passed into
VAE.forward.- n_mc_samples
int Number of Monte Carlo samples to use for the estimation of the marginal log-likelihood.
- return_mean
bool Whether to return the mean of marginal likelihoods over cells.
- n_mc_samples_per_pass
int Number of Monte Carlo samples to use per pass. This is useful to avoid memory issues.
- tensors
- nicheVAE.sample(tensors, n_samples=1, max_poisson_rate=100000000.0, generative_kwargs=None)[source]#
Generate predictive samples from the posterior predictive distribution.
The posterior predictive distribution is denoted as \(p(\hat{x} \mid x)\), where \(x\) is the input data and \(\hat{x}\) is the sampled data.
We sample from this distribution by first sampling
n_samplestimes from the posterior distribution \(q(z \mid x)\) for a given observation, and then sampling from the likelihood \(p(\hat{x} \mid z)\) for each of these.- Parameters:
- tensors
dict[str,Tensor] Dictionary of tensors passed into
VAE.forward.- n_samples
int Number of Monte Carlo samples to draw from the distribution for each observation.
- max_poisson_rate
float The maximum value to which to clip the
rateparameter ofPoisson. Avoids numerical sampling issues when the parameter is very large due to the variance of the distribution.- generative_kwargs
dict|None Keyword args for
generative()in fwd pass
- tensors
- Return type:
- Returns:
Tensor on CPU with shape
(n_obs, n_vars)ifn_samples == 1, else(n_obs, n_vars,).