smoother.models.reduction._spanvi
Attributes
Classes
Spatial loss. |
|
Add spatial loss to the latent representation in the SCANVAE model. |
|
Spatially-aware ANnotation Variational Inference model. |
Functions
|
Utility for the semi-supervised setting. |
|
Compute a heuristic for the default number of maximum epochs. |
|
Freeze parts of network for scArches. |
Module Contents
- class smoother.models.reduction._spanvi.SpatialLoss(prior, spatial_weights: List[smoother.weights.SpatialWeightMatrix] = None, rho=1, use_sparse=True, standardize_cov=False)
Bases:
torch.nn.ModuleSpatial loss.
The spatial smoothing loss on a spatial random variable (num_group x num_spot).
- spatial_weights
Spatial weight matrix collection of length num_group or 1. If 1 then all groups will be subject to the same covariance.
- Type:
List[SpatialWeightMatrix]
- standardize_cov
Whether to standardize the covariance matrix to have same variance (1) across locations. Only proper covariance can be standardized.
- Type:
- inv_cov
Inverse covariance (precision) matrix of spatial variables of each group, (num_group or 1) x n x n. If the first dimension has length 1, all groups will have the same covariance structure.
- Type:
3D tensor
- inv_cov_2d_sp
Sparse block diagonal inverse covariance (precision) matrix.
- Type:
2D sparse tensor
- confidences
Relative prior confidence of each group. The higher the confidence, the stronger the smoothing will be. If float, all groups will have the same confidence.
- Type:
1D tensor or float
- estimate_confidence(ref_exp, st_exp, method='lr') None
Estimate the relative confidence for each group.
The covariance matrix will be scaled accordingly.
- Parameters:
ref_exp (2D tensor) – Bulk expression signiture matrix, num_gene x num_group.
st_exp (2D tensor) – Spatial expression matrix, num_gene x num_spot.
method (str) – Method used to estimate variance.
- forward(coefs, normalize=True)
Calculate spatial loss.
- Parameters:
coefs (2D tensor) – Columns of regression coefficients, num_group x num_spot.
- calc_corr_decay_stats(coords, min_k=0, max_k=50, cov_ind=0, return_var=False)
Calculate spatial covariance decay over degree of neighborhoods.
Covariance measured between k-nearest neighbors. If the number of covariance matrices (i.e. self.inv_cov.shape[0]) is larger than 1, use ‘cov_ind’ to select the covariance matrix to use.
- Parameters:
- Returns:
Correlation decay quantiles. var_quantiles_df (pd.DataFrame): Per-spot variance quantiles.
- Return type:
corr_decay_quantiles_df (pd.DataFrame)
- smoother.models.reduction._spanvi.broadcast_labels(y, *o, n_broadcast=-1)
Utility for the semi-supervised setting.
If y is defined(labelled batch) then one-hot encode the labels (no broadcasting needed) If y is undefined (unlabelled batch) then generate all possible labels (and broadcast other arguments if not None)
- smoother.models.reduction._spanvi.get_max_epochs_heuristic(n_obs: int, epochs_cap: int = 400, decay_at_n_obs: int = 20000) int
Compute a heuristic for the default number of maximum epochs.
If n_obs <= decay_at_n_obs, the number of maximum epochs is set to epochs_cap. Otherwise, the number of maximum epochs decays according to (decay_at_n_obs / n_obs) * epochs_cap, with a minimum of 1.
- Parameters:
n_obs – The number of observations in the dataset.
epochs_cap – The maximum number of epochs for the heuristic.
decay_at_n_obs – The number of observations at which the heuristic starts decaying.
- Returns:
A heuristic for the default number of maximum epochs.
- Return type:
int
- smoother.models.reduction._spanvi.set_params_online_update(module, unfrozen, freeze_decoder_first_layer, freeze_batchnorm_encoder, freeze_batchnorm_decoder, freeze_dropout, freeze_expression, freeze_classifier)
Freeze parts of network for scArches.
- smoother.models.reduction._spanvi.logger
- class smoother.models.reduction._spanvi.SPANVAE(n_input: int, spatial_loss: smoother.SpatialLoss | None = None, lambda_spatial_loss=0.1, sp_loss_on: Literal['z', 'mean_z'] = 'mean_z', n_batch: int = 0, n_labels: int = 0, n_hidden: scvi._types.Tunable[int] = 128, n_latent: scvi._types.Tunable[int] = 10, n_layers: scvi._types.Tunable[int] = 1, n_continuous_cov: int = 0, n_cats_per_cov: Iterable[int] | None = None, dropout_rate: scvi._types.Tunable[float] = 0.1, dispersion: scvi._types.Tunable[Literal['gene', 'gene-batch', 'gene-label', 'gene-cell']] = 'gene', log_variational: scvi._types.Tunable[bool] = True, gene_likelihood: scvi._types.Tunable[Literal['zinb', 'nb']] = 'zinb', y_prior=None, labels_groups: Sequence[int] = None, use_labels_groups: bool = False, linear_classifier: bool = False, classifier_parameters: dict | None = None, use_batch_norm: scvi._types.Tunable[Literal['encoder', 'decoder', 'none', 'both']] = 'both', use_layer_norm: scvi._types.Tunable[Literal['encoder', 'decoder', 'none', 'both']] = 'none', **vae_kwargs)
Bases:
scvi.module.SCANVAEAdd spatial loss to the latent representation in the SCANVAE model.
- Parameters:
spatial_loss – Spatial loss to apply on the latent representation. If None, no spatial loss.
lambda_spatial_loss – Weight of the spatial loss.
sp_loss_on – Whether to apply the spatial loss on the sampled latent representation (‘z’) or on the encoded mean of the latent distribution (‘mean_z’).
- loss(tensors, inference_outputs, generative_ouputs, feed_labels=False, kl_weight=1, labelled_tensors=None, classification_ratio=None)
Compute the loss.
- classmethod from_vae(vae_module: scvi.module.SCANVAE, spatial_loss: smoother.SpatialLoss | None = None, lambda_spatial_loss=0.1, sp_loss_on: Literal['z', 'mean_z'] = 'mean_z')
- class smoother.models.reduction._spanvi.SpatialANVI(st_adata: anndata.AnnData, spatial_loss: smoother.SpatialLoss | None = None, lambda_spatial_loss=0.1, sp_loss_on: Literal['z', 'mean_z'] = 'mean_z', n_hidden: int = 128, n_latent: int = 10, n_layers: int = 1, dropout_rate: float = 0.1, dispersion: Literal['gene', 'gene-batch', 'gene-label', 'gene-cell'] = 'gene', gene_likelihood: Literal['zinb', 'nb', 'poisson'] = 'nb', latent_distribution: Literal['normal', 'ln'] = 'normal', **model_kwargs)
Bases:
scvi.model.SCANVISpatially-aware ANnotation Variational Inference model.
- _data_splitter_cls
- _module_cls
- _training_plan_cls
- _train_runner_cls
- train(max_epochs: int | None = None, accelerator: str = 'auto', devices: int | List[int] | str = 'auto', plan_kwargs: dict | None = None, **trainer_kwargs)
Unsupervised training of the spatial model without minibatches.
- classmethod from_rna_model(st_adata: anndata.AnnData, sc_model: scvi.model.SCANVI, spatial_loss: smoother.SpatialLoss | None = None, lambda_spatial_loss=0.1, sp_loss_on: Literal['z', 'mean_z'] = 'mean_z', unfrozen: bool = False, freeze_dropout: bool = False, freeze_expression: bool = True, freeze_decoder_first_layer: bool = True, freeze_batchnorm_encoder: bool = True, freeze_batchnorm_decoder: bool = False, freeze_classifier: bool = True, **spanvae_kwargs)
Alternate constructor for exploiting a pre-trained model on RNA-seq data.
Note that because of the dropout layer, even though the new instance is initialized with the same parameters as the pre-trained model, new_instance.get_latent_representation() may not return the same latent representation as the pre-trained model.
- Parameters:
st_adata – registed anndata object
sc_model – pretrained SCANVI model