code
stringlengths 114
1.05M
| path
stringlengths 3
312
| quality_prob
float64 0.5
0.99
| learning_prob
float64 0.2
1
| filename
stringlengths 3
168
| kind
stringclasses 1
value |
---|---|---|---|---|---|
import collections.abc as container_abcs
import numpy as np
import re
import sys
import torch
from ...dataset import MultiConditionAnnotatedDataset
def print_progress(epoch, logs, n_epochs=10000, only_val_losses=True):
"""Creates Message for '_print_progress_bar'.
Parameters
----------
epoch: Integer
Current epoch iteration.
logs: Dict
Dictionary of all current losses.
n_epochs: Integer
Maximum value of epochs.
only_val_losses: Boolean
If 'True' only the validation dataset losses are displayed, if 'False' additionally the training dataset
losses are displayed.
Returns
-------
"""
message = ""
for key in logs:
if only_val_losses:
if "val_" in key and "unweighted" not in key:
message += f" - {key:s}: {logs[key][-1]:7.2f}"
else:
if "unweighted" not in key:
message += f" - {key:s}: {logs[key][-1]:7.2f}"
_print_progress_bar(epoch + 1, n_epochs, prefix='', suffix=message, decimals=1, length=20)
def _print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'):
"""Prints out message with a progress bar.
Parameters
----------
iteration: Integer
Current epoch.
total: Integer
Maximum value of epochs.
prefix: String
String before the progress bar.
suffix: String
String after the progress bar.
decimals: Integer
Digits after comma for all the losses.
length: Integer
Length of the progress bar.
fill: String
Symbol for filling the bar.
Returns
-------
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filled_len = int(length * iteration // total)
bar = fill * filled_len + '-' * (length - filled_len)
sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percent, '%', suffix)),
if iteration == total:
sys.stdout.write('\n')
sys.stdout.flush()
def custom_collate(batch):
r"""Puts each data field into a tensor with outer dimension batch size"""
np_str_obj_array_pattern = re.compile(r'[SaUO]')
default_collate_err_msg_format = (
"default_collate: batch must contain tensors, numpy arrays, numbers, "
"dicts or lists; found {}")
elem = batch[0]
elem_type = type(elem)
if isinstance(elem, torch.Tensor):
out = None
if torch.utils.data.get_worker_info() is not None:
# If we're in a background process, concatenate directly into a
# shared memory tensor to avoid an extra copy
numel = sum([x.numel() for x in batch])
storage = elem.storage()._new_shared(numel)
out = elem.new(storage)
return torch.stack(batch, 0, out=out)
elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' and elem_type.__name__ != 'string_':
elem = batch[0]
if elem_type.__name__ == 'ndarray' or elem_type.__name__ == 'memmap':
# array of string classes and object
if np_str_obj_array_pattern.search(elem.dtype.str) is not None:
raise TypeError(default_collate_err_msg_format.format(elem.dtype))
return custom_collate([torch.as_tensor(b) for b in batch])
elif elem.shape == (): # scalars
return torch.as_tensor(batch)
elif isinstance(elem, container_abcs.Mapping):
output = {key: custom_collate([d[key] for d in batch]) for key in elem}
return output
def train_test_split(adata, train_frac=0.85, condition_key=None, cell_type_key=None, labeled_array=None):
"""Splits 'Anndata' object into training and validation data.
Parameters
----------
adata: `~anndata.AnnData`
`AnnData` object for training the model.
train_frac: float
Train-test split fraction. the model will be trained with train_frac for training
and 1-train_frac for validation.
Returns
-------
Indices for training and validating the model.
"""
indices = np.arange(adata.shape[0])
if train_frac == 1:
return indices, None
if cell_type_key is not None:
labeled_array = np.zeros((len(adata), 1)) if labeled_array is None else labeled_array
labeled_array = np.ravel(labeled_array)
labeled_idx = indices[labeled_array == 1]
unlabeled_idx = indices[labeled_array == 0]
train_labeled_idx = []
val_labeled_idx = []
train_unlabeled_idx = []
val_unlabeled_idx = []
if len(labeled_idx) > 0:
cell_types = adata[labeled_idx].obs[cell_type_key].unique().tolist()
for cell_type in cell_types:
ct_idx = labeled_idx[adata[labeled_idx].obs[cell_type_key] == cell_type]
n_train_samples = int(np.ceil(train_frac * len(ct_idx)))
np.random.shuffle(ct_idx)
train_labeled_idx.append(ct_idx[:n_train_samples])
val_labeled_idx.append(ct_idx[n_train_samples:])
if len(unlabeled_idx) > 0:
n_train_samples = int(np.ceil(train_frac * len(unlabeled_idx)))
train_unlabeled_idx.append(unlabeled_idx[:n_train_samples])
val_unlabeled_idx.append(unlabeled_idx[n_train_samples:])
train_idx = train_labeled_idx + train_unlabeled_idx
val_idx = val_labeled_idx + val_unlabeled_idx
train_idx = np.concatenate(train_idx)
val_idx = np.concatenate(val_idx)
elif condition_keys is not None:
train_idx = []
val_idx = []
conditions = adata.obs['conditions_combined'].unique().tolist()
for condition in conditions:
cond_idx = indices[adata.obs['conditions_combined'] == condition]
n_train_samples = int(np.ceil(train_frac * len(cond_idx)))
np.random.shuffle(cond_idx)
train_idx.append(cond_idx[:n_train_samples])
val_idx.append(cond_idx[n_train_samples:])
train_idx = np.concatenate(train_idx)
val_idx = np.concatenate(val_idx)
else:
n_train_samples = int(np.ceil(train_frac * len(indices)))
np.random.shuffle(indices)
train_idx = indices[:n_train_samples]
val_idx = indices[n_train_samples:]
return train_idx, val_idx
def make_dataset(adata,
train_frac=0.9,
condition_keys=None,
cell_type_keys=None,
condition_encoders=None,
conditions_combined_encoder=None,
cell_type_encoder=None,
labeled_indices=None,
):
"""Splits 'adata' into train and validation data and converts them into 'CustomDatasetFromAdata' objects.
Parameters
----------
Returns
-------
Training 'CustomDatasetFromAdata' object, Validation 'CustomDatasetFromAdata' object
"""
# Preprare data for semisupervised learning
labeled_array = np.zeros((len(adata), 1))
if labeled_indices is not None:
labeled_array[labeled_indices] = 1
if cell_type_keys is not None:
finest_level = None
n_cts = 0
for cell_type_key in cell_type_keys:
if len(adata.obs[cell_type_key].unique().tolist()) >= n_cts:
n_cts = len(adata.obs[cell_type_key].unique().tolist())
finest_level = cell_type_key
train_idx, val_idx = train_test_split(adata, train_frac, cell_type_key=finest_level,
labeled_array=labeled_array)
elif condition_key is not None:
train_idx, val_idx = train_test_split(adata, train_frac, condition_key=condition_key)
else:
train_idx, val_idx = train_test_split(adata, train_frac)
data_set_train = MultiConditionAnnotatedDataset(
adata if train_frac == 1 else adata[train_idx],
condition_keys=condition_keys,
cell_type_keys=cell_type_keys,
condition_encoders=condition_encoders,
conditions_combined_encoder=conditions_combined_encoder,
cell_type_encoder=cell_type_encoder,
labeled_array=labeled_array[train_idx]
)
if train_frac == 1:
return data_set_train, None
else:
data_set_valid = MultiConditionAnnotatedDataset(
adata[val_idx],
condition_keys=condition_keys,
cell_type_keys=cell_type_keys,
condition_encoders=condition_encoders,
conditions_combined_encoder=conditions_combined_encoder,
cell_type_encoder=cell_type_encoder,
labeled_array=labeled_array[val_idx]
)
return data_set_train, data_set_valid
def cov(x, rowvar=False, bias=False, ddof=None, aweights=None):
"""Estimates covariance matrix like numpy.cov"""
# ensure at least 2D
if x.dim() == 1:
x = x.view(-1, 1)
# treat each column as a data point, each row as a variable
if rowvar and x.shape[0] != 1:
x = x.t()
if ddof is None:
if bias == 0:
ddof = 1
else:
ddof = 0
w = aweights
if w is not None:
if not torch.is_tensor(w):
w = torch.tensor(w, dtype=torch.float)
w_sum = torch.sum(w)
avg = torch.sum(x * (w / w_sum)[:, None], 0)
else:
avg = torch.mean(x, 0)
# Determine the normalization
if w is None:
fact = x.shape[0] - ddof
elif ddof == 0:
fact = w_sum
elif aweights is None:
fact = w_sum - ddof
else:
fact = w_sum - ddof * torch.sum(w * w) / w_sum
xm = x.sub(avg.expand_as(x))
if w is None:
X_T = xm.t()
else:
X_T = torch.mm(torch.diag(w), xm).t()
c = torch.mm(X_T, xm)
c = c / fact
return c.squeeze()
def t_dist(x, y, alpha):
"""student t-distribution, as same as used in t-SNE algorithm.
q_ij = 1/(1+dist(x_i, u_j)^2), then normalize it.
Arguments:
inputs: the variable containing data, shape=(n_samples, n_features)
Return:
q: student's t-distribution with degree alpha, or soft labels for each sample. shape=(n_samples, n_clusters)
"""
n = x.size(0)
m = y.size(0)
d = x.size(1)
if d != y.size(1):
raise Exception
x = x.unsqueeze(1).expand(n, m, d)
y = y.unsqueeze(0).expand(n, m, d)
distances = torch.pow(x - y, 2).sum(2) / alpha
q = 1.0 / (1.0 + distances)
q = torch.pow(q, (alpha + 1.0) / 2.0)
q = (q.T / q.sum(1)).T
return q
def target_distribution(q):
weight = torch.pow(q, 2) / q.sum(0)
return (weight.T / weight.sum(1)).T
def kl_loss(p, q):
return (p * torch.log(p / q)).sum(1).mean()
|
/scArches-0.5.9.tar.gz/scArches-0.5.9/scarches/trainers/scpoli/_utils.py
| 0.702122 | 0.358662 |
_utils.py
|
pypi
|
from .trainer import Trainer
import torch
class trVAETrainer(Trainer):
"""ScArches Unsupervised Trainer class. This class contains the implementation of the unsupervised CVAE/TRVAE
Trainer.
Parameters
----------
model: trVAE
Number of input features (i.e. gene in case of scRNA-seq).
adata: : `~anndata.AnnData`
Annotated data matrix. Has to be count data for 'nb' and 'zinb' loss and normalized log transformed data
for 'mse' loss.
condition_key: String
column name of conditions in `adata.obs` data frame.
cell_type_key: String
column name of celltypes in `adata.obs` data frame.
train_frac: Float
Defines the fraction of data that is used for training and data that is used for validation.
batch_size: Integer
Defines the batch size that is used during each Iteration
n_samples: Integer or None
Defines how many samples are being used during each epoch. This should only be used if hardware resources
are limited.
clip_value: Float
If the value is greater than 0, all gradients with an higher value will be clipped during training.
weight decay: Float
Defines the scaling factor for weight decay in the Adam optimizer.
alpha_iter_anneal: Integer or None
If not 'None', the KL Loss scaling factor will be annealed from 0 to 1 every iteration until the input
integer is reached.
alpha_epoch_anneal: Integer or None
If not 'None', the KL Loss scaling factor will be annealed from 0 to 1 every epoch until the input
integer is reached.
use_early_stopping: Boolean
If 'True' the EarlyStopping class is being used for training to prevent overfitting.
early_stopping_kwargs: Dict
Passes custom Earlystopping parameters.
use_stratified_sampling: Boolean
If 'True', the sampler tries to load equally distributed batches concerning the conditions in every
iteration.
use_stratified_split: Boolean
If `True`, the train and validation data will be constructed in such a way that both have same distribution
of conditions in the data.
monitor: Boolean
If `True', the progress of the training will be printed after each epoch.
n_workers: Integer
Passes the 'n_workers' parameter for the torch.utils.data.DataLoader class.
seed: Integer
Define a specific random seed to get reproducable results.
"""
def __init__(
self,
model,
adata,
**kwargs
):
super().__init__(model, adata, **kwargs)
def loss(self, total_batch=None):
recon_loss, kl_loss, mmd_loss = self.model(**total_batch)
loss = recon_loss + self.calc_alpha_coeff()*kl_loss + mmd_loss
self.iter_logs["loss"].append(loss.item())
self.iter_logs["unweighted_loss"].append(recon_loss.item() + kl_loss.item() + mmd_loss.item())
self.iter_logs["recon_loss"].append(recon_loss.item())
self.iter_logs["kl_loss"].append(kl_loss.item())
if self.model.use_mmd:
self.iter_logs["mmd_loss"].append(mmd_loss.item())
return loss
|
/scArches-0.5.9.tar.gz/scArches-0.5.9/scarches/trainers/trvae/unsupervised.py
| 0.92958 | 0.723041 |
unsupervised.py
|
pypi
|
import torch
import torch.nn as nn
from collections import defaultdict
import numpy as np
import time
from torch.utils.data import DataLoader
from torch.utils.data import WeightedRandomSampler
from ...utils.monitor import EarlyStopping
from ._utils import make_dataset, custom_collate, print_progress
class Trainer:
"""ScArches base Trainer class. This class contains the implementation of the base CVAE/TRVAE Trainer.
Parameters
----------
model: trVAE
Number of input features (i.e. gene in case of scRNA-seq).
adata: : `~anndata.AnnData`
Annotated data matrix. Has to be count data for 'nb' and 'zinb' loss and normalized log transformed data
for 'mse' loss.
condition_key: String
column name of conditions in `adata.obs` data frame.
cell_type_keys: List
List of column names of different celltype levels in `adata.obs` data frame.
batch_size: Integer
Defines the batch size that is used during each Iteration
alpha_epoch_anneal: Integer or None
If not 'None', the KL Loss scaling factor (alpha_kl) will be annealed from 0 to 1 every epoch until the input
integer is reached.
alpha_kl: Float
Multiplies the KL divergence part of the loss.
alpha_iter_anneal: Integer or None
If not 'None', the KL Loss scaling factor will be annealed from 0 to 1 every iteration until the input
integer is reached.
use_early_stopping: Boolean
If 'True' the EarlyStopping class is being used for training to prevent overfitting.
reload_best: Boolean
If 'True' the best state of the model during training concerning the early stopping criterion is reloaded
at the end of training.
early_stopping_kwargs: Dict
Passes custom Earlystopping parameters.
train_frac: Float
Defines the fraction of data that is used for training and data that is used for validation.
n_samples: Integer or None
Defines how many samples are being used during each epoch. This should only be used if hardware resources
are limited.
use_stratified_sampling: Boolean
If 'True', the sampler tries to load equally distributed batches concerning the conditions in every
iteration.
monitor: Boolean
If `True', the progress of the training will be printed after each epoch.
monitor_only_val: Boolean
If `True', only the progress of the validation datset is displayed.
clip_value: Float
If the value is greater than 0, all gradients with an higher value will be clipped during training.
weight decay: Float
Defines the scaling factor for weight decay in the Adam optimizer.
n_workers: Integer
Passes the 'n_workers' parameter for the torch.utils.data.DataLoader class.
seed: Integer
Define a specific random seed to get reproducable results.
"""
def __init__(self,
model,
adata,
condition_key: str = None,
cell_type_keys: str = None,
batch_size: int = 128,
alpha_epoch_anneal: int = None,
alpha_kl: float = 1.,
use_early_stopping: bool = True,
reload_best: bool = True,
early_stopping_kwargs: dict = None,
**kwargs):
self.adata = adata
self.model = model
self.condition_key = condition_key
self.cell_type_keys = cell_type_keys
self.batch_size = batch_size
self.alpha_epoch_anneal = alpha_epoch_anneal
self.alpha_iter_anneal = kwargs.pop("alpha_iter_anneal", None)
self.use_early_stopping = use_early_stopping
self.reload_best = reload_best
self.alpha_kl = alpha_kl
early_stopping_kwargs = (early_stopping_kwargs if early_stopping_kwargs else dict())
self.n_samples = kwargs.pop("n_samples", None)
self.train_frac = kwargs.pop("train_frac", 0.9)
self.use_stratified_sampling = kwargs.pop("use_stratified_sampling", True)
self.weight_decay = kwargs.pop("weight_decay", 0.04)
self.clip_value = kwargs.pop("clip_value", 0.0)
self.n_workers = kwargs.pop("n_workers", 0)
self.seed = kwargs.pop("seed", 2020)
self.monitor = kwargs.pop("monitor", True)
self.monitor_only_val = kwargs.pop("monitor_only_val", True)
self.early_stopping = EarlyStopping(**early_stopping_kwargs)
torch.manual_seed(self.seed)
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if torch.cuda.is_available():
torch.cuda.manual_seed(self.seed)
self.model.cuda()
self.epoch = -1
self.n_epochs = None
self.iter = 0
self.best_epoch = None
self.best_state_dict = None
self.current_loss = None
self.previous_loss_was_nan = False
self.nan_counter = 0
self.optimizer = None
self.training_time = 0
self.train_data = None
self.valid_data = None
self.sampler = None
self.dataloader_train = None
self.dataloader_valid = None
self.iters_per_epoch = None
self.val_iters_per_epoch = None
self.logs = defaultdict(list)
# Create Train/Valid AnnotatetDataset objects
self.train_data, self.valid_data = make_dataset(
self.adata,
train_frac=self.train_frac,
condition_key=self.condition_key,
cell_type_keys=self.cell_type_keys,
condition_encoder=self.model.condition_encoder,
cell_type_encoder=self.model.cell_type_encoder,
)
def initialize_loaders(self):
"""
Initializes Train-/Test Data and Dataloaders with custom_collate and WeightedRandomSampler for Trainloader.
Returns:
"""
if self.n_samples is None or self.n_samples > len(self.train_data):
self.n_samples = len(self.train_data)
self.iters_per_epoch = int(np.ceil(self.n_samples / self.batch_size))
if self.use_stratified_sampling:
# Create Sampler and Dataloaders
stratifier_weights = torch.tensor(self.train_data.stratifier_weights, device=self.device)
self.sampler = WeightedRandomSampler(stratifier_weights,
num_samples=self.n_samples,
replacement=True)
self.dataloader_train = torch.utils.data.DataLoader(dataset=self.train_data,
batch_size=self.batch_size,
sampler=self.sampler,
collate_fn=custom_collate,
num_workers=self.n_workers)
else:
self.dataloader_train = torch.utils.data.DataLoader(dataset=self.train_data,
batch_size=self.batch_size,
shuffle=True,
collate_fn=custom_collate,
num_workers=self.n_workers)
if self.valid_data is not None:
val_batch_size = self.batch_size
if self.batch_size > len(self.valid_data):
val_batch_size = len(self.valid_data)
self.val_iters_per_epoch = int(np.ceil(len(self.valid_data) / self.batch_size))
self.dataloader_valid = torch.utils.data.DataLoader(dataset=self.valid_data,
batch_size=val_batch_size,
shuffle=True,
collate_fn=custom_collate,
num_workers=self.n_workers)
def calc_alpha_coeff(self):
"""Calculates current alpha coefficient for alpha annealing.
Parameters
----------
Returns
-------
Current annealed alpha value
"""
if self.alpha_epoch_anneal is not None:
alpha_coeff = min(self.alpha_kl * self.epoch / self.alpha_epoch_anneal, self.alpha_kl)
elif self.alpha_iter_anneal is not None:
alpha_coeff = min((self.alpha_kl * (self.epoch * self.iters_per_epoch + self.iter) / self.alpha_iter_anneal), self.alpha_kl)
else:
alpha_coeff = self.alpha_kl
return alpha_coeff
def train(self,
n_epochs=400,
lr=1e-3,
eps=0.01):
self.initialize_loaders()
begin = time.time()
self.model.train()
self.n_epochs = n_epochs
params = filter(lambda p: p.requires_grad, self.model.parameters())
self.optimizer = torch.optim.Adam(params, lr=lr, eps=eps, weight_decay=self.weight_decay)
self.before_loop()
for self.epoch in range(n_epochs):
self.on_epoch_begin(lr, eps)
self.iter_logs = defaultdict(list)
for self.iter, batch_data in enumerate(self.dataloader_train):
for key, batch in batch_data.items():
batch_data[key] = batch.to(self.device)
# Loss Calculation
self.on_iteration(batch_data)
# Validation of Model, Monitoring, Early Stopping
self.on_epoch_end()
if self.use_early_stopping:
if not self.check_early_stop():
break
if self.best_state_dict is not None and self.reload_best:
print("Saving best state of network...")
print("Best State was in Epoch", self.best_epoch)
self.model.load_state_dict(self.best_state_dict)
self.model.eval()
self.after_loop()
self.training_time += (time.time() - begin)
def before_loop(self):
pass
def on_epoch_begin(self, lr, eps):
pass
def after_loop(self):
pass
def on_iteration(self, batch_data):
# Dont update any weight on first layers except condition weights
if self.model.freeze:
for name, module in self.model.named_modules():
if isinstance(module, nn.BatchNorm1d):
if not module.weight.requires_grad:
module.affine = False
module.track_running_stats = False
# Calculate Loss depending on Trainer/Model
self.current_loss = loss = self.loss(batch_data)
self.optimizer.zero_grad()
loss.backward()
# Gradient Clipping
if self.clip_value > 0:
torch.nn.utils.clip_grad_value_(self.model.parameters(), self.clip_value)
self.optimizer.step()
def on_epoch_end(self):
# Get Train Epoch Logs
for key in self.iter_logs:
self.logs["epoch_" + key].append(np.array(self.iter_logs[key]).mean())
# Validate Model
if self.valid_data is not None:
self.validate()
# Monitor Logs
if self.monitor:
print_progress(self.epoch, self.logs, self.n_epochs, self.monitor_only_val)
@torch.no_grad()
def validate(self):
self.model.eval()
self.iter_logs = defaultdict(list)
# Calculate Validation Losses
for val_iter, batch_data in enumerate(self.dataloader_valid):
for key, batch in batch_data.items():
batch_data[key] = batch.to(self.device)
val_loss = self.loss(batch_data)
# Get Validation Logs
for key in self.iter_logs:
self.logs["val_" + key].append(np.array(self.iter_logs[key]).mean())
self.model.train()
def check_early_stop(self):
# Calculate Early Stopping and best state
early_stopping_metric = self.early_stopping.early_stopping_metric
if self.early_stopping.update_state(self.logs[early_stopping_metric][-1]):
self.best_state_dict = self.model.state_dict()
self.best_epoch = self.epoch
continue_training, update_lr = self.early_stopping.step(self.logs[early_stopping_metric][-1])
if update_lr:
print(f'\nADJUSTED LR')
for param_group in self.optimizer.param_groups:
param_group["lr"] *= self.early_stopping.lr_factor
return continue_training
|
/scArches-0.5.9.tar.gz/scArches-0.5.9/scarches/trainers/trvae/trainer.py
| 0.92382 | 0.524943 |
trainer.py
|
pypi
|
import sys
import numpy as np
import re
import torch
import collections.abc as container_abcs
from torch.utils.data import DataLoader
from ...dataset import trVAEDataset
def print_progress(epoch, logs, n_epochs=10000, only_val_losses=True):
"""Creates Message for '_print_progress_bar'.
Parameters
----------
epoch: Integer
Current epoch iteration.
logs: Dict
Dictionary of all current losses.
n_epochs: Integer
Maximum value of epochs.
only_val_losses: Boolean
If 'True' only the validation dataset losses are displayed, if 'False' additionally the training dataset
losses are displayed.
Returns
-------
"""
message = ""
for key in logs:
if only_val_losses:
if "val_" in key and "unweighted" not in key:
message += f" - {key:s}: {logs[key][-1]:7.10f}"
else:
if "unweighted" not in key:
message += f" - {key:s}: {logs[key][-1]:7.10f}"
_print_progress_bar(epoch + 1, n_epochs, prefix='', suffix=message, decimals=1, length=20)
def _print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'):
"""Prints out message with a progress bar.
Parameters
----------
iteration: Integer
Current epoch.
total: Integer
Maximum value of epochs.
prefix: String
String before the progress bar.
suffix: String
String after the progress bar.
decimals: Integer
Digits after comma for all the losses.
length: Integer
Length of the progress bar.
fill: String
Symbol for filling the bar.
Returns
-------
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filled_len = int(length * iteration // total)
bar = fill * filled_len + '-' * (length - filled_len)
sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percent, '%', suffix)),
if iteration == total:
sys.stdout.write('\n')
sys.stdout.flush()
def train_test_split(adata, train_frac=0.85, condition_key=None, cell_type_key=None, labeled_array=None):
"""Splits 'Anndata' object into training and validation data.
Parameters
----------
adata: `~anndata.AnnData`
`AnnData` object for training the model.
train_frac: float
Train-test split fraction. the model will be trained with train_frac for training
and 1-train_frac for validation.
Returns
-------
Indices for training and validating the model.
"""
indices = np.arange(adata.shape[0])
if train_frac == 1:
return indices, None
if cell_type_key is not None:
labeled_array = np.zeros((len(adata), 1)) if labeled_array is None else labeled_array
labeled_array = np.ravel(labeled_array)
labeled_idx = indices[labeled_array == 1]
unlabeled_idx = indices[labeled_array == 0]
train_labeled_idx = []
val_labeled_idx = []
train_unlabeled_idx = []
val_unlabeled_idx = []
#TODO this is horribly inefficient
if len(labeled_idx) > 0:
cell_types = adata[labeled_idx].obs[cell_type_key].unique().tolist()
for cell_type in cell_types:
ct_idx = labeled_idx[adata[labeled_idx].obs[cell_type_key] == cell_type]
n_train_samples = int(np.ceil(train_frac * len(ct_idx)))
np.random.shuffle(ct_idx)
train_labeled_idx.append(ct_idx[:n_train_samples])
val_labeled_idx.append(ct_idx[n_train_samples:])
if len(unlabeled_idx) > 0:
n_train_samples = int(np.ceil(train_frac * len(unlabeled_idx)))
train_unlabeled_idx.append(unlabeled_idx[:n_train_samples])
val_unlabeled_idx.append(unlabeled_idx[n_train_samples:])
train_idx = train_labeled_idx + train_unlabeled_idx
val_idx = val_labeled_idx + val_unlabeled_idx
train_idx = np.concatenate(train_idx)
val_idx = np.concatenate(val_idx)
elif condition_key is not None:
train_idx = []
val_idx = []
conditions = adata.obs[condition_key].unique().tolist()
for condition in conditions:
cond_idx = indices[adata.obs[condition_key] == condition]
n_train_samples = int(np.ceil(train_frac * len(cond_idx)))
#np.random.shuffle(cond_idx)
train_idx.append(cond_idx[:n_train_samples])
val_idx.append(cond_idx[n_train_samples:])
train_idx = np.concatenate(train_idx)
val_idx = np.concatenate(val_idx)
else:
n_train_samples = int(np.ceil(train_frac * len(indices)))
np.random.shuffle(indices)
train_idx = indices[:n_train_samples]
val_idx = indices[n_train_samples:]
return train_idx, val_idx
def make_dataset(adata,
train_frac=0.9,
condition_key=None,
cell_type_keys=None,
condition_encoder=None,
cell_type_encoder=None,
labeled_indices=None,
):
"""Splits 'adata' into train and validation data and converts them into 'CustomDatasetFromAdata' objects.
Parameters
----------
Returns
-------
Training 'CustomDatasetFromAdata' object, Validation 'CustomDatasetFromAdata' object
"""
# Preprare data for semisupervised learning
print(f"Preparing {adata.shape}")
labeled_array = np.zeros((len(adata), 1))
if labeled_indices is not None:
labeled_array[labeled_indices] = 1
if cell_type_keys is not None:
finest_level = None
n_cts = 0
for cell_type_key in cell_type_keys:
if len(adata.obs[cell_type_key].unique().tolist()) >= n_cts:
n_cts = len(adata.obs[cell_type_key].unique().tolist())
finest_level = cell_type_key
print(f"Splitting data {adata.shape}")
train_idx, val_idx = train_test_split(adata, train_frac, cell_type_key=finest_level,
labeled_array=labeled_array)
elif condition_key is not None:
train_idx, val_idx = train_test_split(adata, train_frac, condition_key=condition_key)
else:
train_idx, val_idx = train_test_split(adata, train_frac)
print("Instantiating dataset")
data_set_train = trVAEDataset(
adata if train_frac == 1 else adata[train_idx],
condition_key=condition_key,
cell_type_keys=cell_type_keys,
condition_encoder=condition_encoder,
cell_type_encoder=cell_type_encoder,
labeled_array=labeled_array[train_idx]
)
if train_frac == 1:
return data_set_train, None
else:
data_set_valid = trVAEDataset(
adata[val_idx],
condition_key=condition_key,
cell_type_keys=cell_type_keys,
condition_encoder=condition_encoder,
cell_type_encoder=cell_type_encoder,
labeled_array=labeled_array[val_idx]
)
return data_set_train, data_set_valid
def custom_collate(batch):
r"""Puts each data field into a tensor with outer dimension batch size"""
np_str_obj_array_pattern = re.compile(r'[SaUO]')
default_collate_err_msg_format = (
"default_collate: batch must contain tensors, numpy arrays, numbers, "
"dicts or lists; found {}")
elem = batch[0]
elem_type = type(elem)
if isinstance(elem, torch.Tensor):
out = None
if torch.utils.data.get_worker_info() is not None:
# If we're in a background process, concatenate directly into a
# shared memory tensor to avoid an extra copy
numel = sum([x.numel() for x in batch])
storage = elem.storage()._new_shared(numel)
out = elem.new(storage)
return torch.stack(batch, 0, out=out)
elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' and elem_type.__name__ != 'string_':
elem = batch[0]
if elem_type.__name__ == 'ndarray' or elem_type.__name__ == 'memmap':
# array of string classes and object
if np_str_obj_array_pattern.search(elem.dtype.str) is not None:
raise TypeError(default_collate_err_msg_format.format(elem.dtype))
return custom_collate([torch.as_tensor(b) for b in batch])
elif elem.shape == (): # scalars
return torch.as_tensor(batch)
elif isinstance(elem, container_abcs.Mapping):
output = {key: custom_collate([d[key] for d in batch]) for key in elem}
return output
|
/scArches-0.5.9.tar.gz/scArches-0.5.9/scarches/trainers/trvae/_utils.py
| 0.716119 | 0.353233 |
_utils.py
|
pypi
|
from typing import Optional
import anndata
import logging
import torch
from torch.distributions import Normal
import numpy as np
from scvi import _CONSTANTS
from scarchest.dataset.scvi import ScviDataLoader
from scarchest.models.scvi import totalVI
logger = logging.getLogger(__name__)
def _unpack_tensors(tensors):
x = tensors[_CONSTANTS.X_KEY]
local_l_mean = tensors[_CONSTANTS.LOCAL_L_MEAN_KEY]
local_l_var = tensors[_CONSTANTS.LOCAL_L_VAR_KEY]
batch_index = tensors[_CONSTANTS.BATCH_KEY]
labels = tensors[_CONSTANTS.LABELS_KEY]
y = tensors[_CONSTANTS.PROTEIN_EXP_KEY]
return x, local_l_mean, local_l_var, batch_index, labels, y
class TotalDataLoader(ScviDataLoader):
"""
Extended data loader for totalVI.
Parameters
----------
model :
A model instance from class ``TOTALVI``
adata:
A registered AnnData object
shuffle :
Specifies if a `RandomSampler` or a `SequentialSampler` should be used
indices :
Specifies how the data should be split with regards to train/test or labelled/unlabelled
use_cuda :
Default: ``True``
data_loader_kwargs :
Keyword arguments to passed into the `DataLoader`
"""
def __init__(
self,
model: totalVI,
adata: anndata.AnnData,
shuffle: bool = False,
indices: Optional[np.ndarray] = None,
use_cuda: bool = True,
batch_size: int = 256,
data_loader_kwargs=dict(),
):
super().__init__(
model,
adata,
shuffle=shuffle,
indices=indices,
use_cuda=use_cuda,
batch_size=batch_size,
data_loader_kwargs=data_loader_kwargs,
)
@property
def _data_and_attributes(self):
return {
_CONSTANTS.X_KEY: np.float32,
_CONSTANTS.BATCH_KEY: np.int64,
_CONSTANTS.LOCAL_L_MEAN_KEY: np.float32,
_CONSTANTS.LOCAL_L_VAR_KEY: np.float32,
_CONSTANTS.LABELS_KEY: np.int64,
_CONSTANTS.PROTEIN_EXP_KEY: np.float32,
}
@torch.no_grad()
def elbo(self):
elbo = self.compute_elbo(self.model)
return elbo
elbo.mode = "min"
@torch.no_grad()
def reconstruction_error(self, mode="total"):
ll_gene, ll_protein = self.compute_reconstruction_error(self.model)
if mode == "total":
return ll_gene + ll_protein
elif mode == "gene":
return ll_gene
else:
return ll_protein
reconstruction_error.mode = "min"
@torch.no_grad()
def marginal_ll(self, n_mc_samples=1000):
ll = self.compute_marginal_log_likelihood()
return ll
@torch.no_grad()
def get_protein_background_mean(self):
background_mean = []
for tensors in self:
x, _, _, batch_index, label, y = _unpack_tensors(tensors)
outputs = self.model.inference(
x, y, batch_index=batch_index, label=label, n_samples=1
)
b_mean = outputs["py_"]["rate_back"]
background_mean += [np.array(b_mean.cpu())]
return np.concatenate(background_mean)
def compute_elbo(self, vae: totalVI, **kwargs):
"""
Computes the ELBO.
The ELBO is the reconstruction error + the KL divergences
between the variational distributions and the priors.
It differs from the marginal log likelihood.
Specifically, it is a lower bound on the marginal log likelihood
plus a term that is constant with respect to the variational distribution.
It still gives good insights on the modeling of the data, and is fast to compute.
Parameters
----------
vae
vae model
**kwargs
keyword args for forward
"""
# Iterate once over the data loader and computes the total log_likelihood
elbo = 0
for _, tensors in enumerate(self):
x, local_l_mean, local_l_var, batch_index, labels, y = _unpack_tensors(
tensors
)
(
reconst_loss_gene,
reconst_loss_protein,
kl_div_z,
kl_div_gene_l,
kl_div_back_pro,
) = vae(
x,
y,
local_l_mean,
local_l_var,
batch_index=batch_index,
label=labels,
**kwargs,
)
elbo += torch.sum(
reconst_loss_gene
+ reconst_loss_protein
+ kl_div_z
+ kl_div_gene_l
+ kl_div_back_pro
).item()
n_samples = len(self.indices)
return elbo / n_samples
def compute_reconstruction_error(self, vae: totalVI, **kwargs):
r"""
Computes log p(x/z), which is the reconstruction error.
Differs from the marginal log likelihood, but still gives good
insights on the modeling of the data, and is fast to compute
This is really a helper function to self.ll, self.ll_protein, etc.
"""
# Iterate once over the data loader and computes the total log_likelihood
log_lkl_gene = 0
log_lkl_protein = 0
for _, tensors in enumerate(self):
x, local_l_mean, local_l_var, batch_index, labels, y = _unpack_tensors(
tensors
)
(
reconst_loss_gene,
reconst_loss_protein,
kl_div_z,
kl_div_l_gene,
kl_div_back_pro,
) = vae(
x,
y,
local_l_mean,
local_l_var,
batch_index=batch_index,
label=labels,
**kwargs,
)
log_lkl_gene += torch.sum(reconst_loss_gene).item()
log_lkl_protein += torch.sum(reconst_loss_protein).item()
n_samples = len(self.indices)
return log_lkl_gene / n_samples, log_lkl_protein / n_samples
def compute_marginal_log_likelihood(
self, n_samples_mc: int = 100, batch_size: int = 96
):
"""
Computes a biased estimator for log p(x, y), which is the marginal log likelihood.
Despite its bias, the estimator still converges to the real value
of log p(x, y) when n_samples_mc (for Monte Carlo) goes to infinity
(a fairly high value like 100 should be enough). 5000 is the standard in machine learning publications.
Due to the Monte Carlo sampling, this method is not as computationally efficient
as computing only the reconstruction loss
Parameters
----------
n_samples_mc
(Default value = 100)
batch_size
(Default value = 96)
"""
# Uses MC sampling to compute a tighter lower bound on log p(x)
log_lkl = 0
for _, tensors in enumerate(self.update_batch_size(batch_size)):
x, local_l_mean, local_l_var, batch_index, labels, y = _unpack_tensors(
tensors
)
to_sum = torch.zeros(x.size()[0], n_samples_mc)
for i in range(n_samples_mc):
# Distribution parameters and sampled variables
outputs = self.model.inference(x, y, batch_index, labels)
qz_m = outputs["qz_m"]
qz_v = outputs["qz_v"]
ql_m = outputs["ql_m"]
ql_v = outputs["ql_v"]
px_ = outputs["px_"]
py_ = outputs["py_"]
log_library = outputs["untran_l"]
# really need not softmax transformed random variable
z = outputs["untran_z"]
log_pro_back_mean = outputs["log_pro_back_mean"]
# Reconstruction Loss
(
reconst_loss_gene,
reconst_loss_protein,
) = self.model.get_reconstruction_loss(x, y, px_, py_)
# Log-probabilities
p_l_gene = (
Normal(local_l_mean, local_l_var.sqrt())
.log_prob(log_library)
.sum(dim=-1)
)
p_z = Normal(0, 1).log_prob(z).sum(dim=-1)
p_mu_back = self.model.back_mean_prior.log_prob(log_pro_back_mean).sum(
dim=-1
)
p_xy_zl = -(reconst_loss_gene + reconst_loss_protein)
q_z_x = Normal(qz_m, qz_v.sqrt()).log_prob(z).sum(dim=-1)
q_l_x = Normal(ql_m, ql_v.sqrt()).log_prob(log_library).sum(dim=-1)
q_mu_back = (
Normal(py_["back_alpha"], py_["back_beta"])
.log_prob(log_pro_back_mean)
.sum(dim=-1)
)
to_sum[:, i] = (
p_z + p_l_gene + p_mu_back + p_xy_zl - q_z_x - q_l_x - q_mu_back
)
batch_log_lkl = torch.logsumexp(to_sum, dim=-1) - np.log(n_samples_mc)
log_lkl += torch.sum(batch_log_lkl).item()
n_samples = len(self.indices)
# The minus sign is there because we actually look at the negative log likelihood
return -log_lkl / n_samples
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/dataset/scvi/total_data_loader.py
| 0.958079 | 0.320476 |
total_data_loader.py
|
pypi
|
import numpy as np
import logging
from sklearn.neighbors import KNeighborsClassifier
import torch
from scvi.core import unsupervised_clustering_accuracy
from scvi import _CONSTANTS
from scarchest.dataset.scvi import ScviDataLoader
logger = logging.getLogger(__name__)
class AnnotationDataLoader(ScviDataLoader):
def __init__(self, *args, model_zl=False, **kwargs):
super().__init__(*args, **kwargs)
self.model_zl = model_zl
def accuracy(self):
model, cls = (
(self.sampling_model, self.model)
if hasattr(self, "sampling_model")
else (self.model, None)
)
acc = compute_accuracy(model, self, classifier=cls, model_zl=self.model_zl)
logger.debug("Acc: %.4f" % (acc))
return acc
accuracy.mode = "max"
@torch.no_grad()
def hierarchical_accuracy(self):
all_y, all_y_pred = self.compute_predictions()
acc = np.mean(all_y == all_y_pred)
all_y_groups = np.array([self.model.labels_groups[y] for y in all_y])
all_y_pred_groups = np.array([self.model.labels_groups[y] for y in all_y_pred])
h_acc = np.mean(all_y_groups == all_y_pred_groups)
logger.debug("Hierarchical Acc : %.4f\n" % h_acc)
return acc
accuracy.mode = "max"
@torch.no_grad()
def compute_predictions(self, soft=False):
"""
Parameters
----------
soft
(Default value = False)
Returns
-------
the true labels and the predicted labels
"""
model, cls = (
(self.sampling_model, self.model)
if hasattr(self, "sampling_model")
else (self.model, None)
)
return compute_predictions(
model, self, classifier=cls, soft=soft, model_zl=self.model_zl
)
@torch.no_grad()
def unsupervised_classification_accuracy(self):
all_y, all_y_pred = self.compute_predictions()
uca = unsupervised_clustering_accuracy(all_y, all_y_pred)[0]
logger.debug("UCA : %.4f" % (uca))
return uca
unsupervised_classification_accuracy.mode = "max"
@torch.no_grad()
def nn_latentspace(self, data_loader):
data_train, _, labels_train = self.get_latent()
data_test, _, labels_test = data_loader.get_latent()
nn = KNeighborsClassifier()
nn.fit(data_train, labels_train)
score = nn.score(data_test, labels_test)
return score
@torch.no_grad()
def compute_accuracy(vae, data_loader, classifier=None, model_zl=False):
all_y, all_y_pred = compute_predictions(
vae, data_loader, classifier=classifier, model_zl=model_zl
)
return np.mean(all_y == all_y_pred)
@torch.no_grad()
def compute_predictions(
model, data_loader, classifier=None, soft=False, model_zl=False
):
all_y_pred = []
all_y = []
for _, tensors in enumerate(data_loader):
sample_batch = tensors[_CONSTANTS.X_KEY]
labels = tensors[_CONSTANTS.LABELS_KEY]
all_y += [labels.view(-1).cpu()]
if hasattr(model, "classify"):
if model.modified:
batch_index = tensors[_CONSTANTS.BATCH_KEY]
y_pred = model.classify(sample_batch, batch_index=batch_index)
else:
y_pred = model.classify(sample_batch)
elif classifier is not None:
# Then we use the specified classifier
if model is not None:
if model.log_variational:
sample_batch = torch.log(1 + sample_batch)
if model_zl:
if model.modified:
batch_index = tensors[_CONSTANTS.BATCH_KEY]
sample_z = model.z_encoder(sample_batch, batch_index)[0]
sample_l = model.l_encoder(sample_batch)[0]
else:
sample_z = model.z_encoder(sample_batch)[0]
sample_l = model.l_encoder(sample_batch)[0]
sample_batch = torch.cat((sample_z, sample_l), dim=-1)
else:
if model.modified:
batch_index = tensors[_CONSTANTS.BATCH_KEY]
sample_batch, _, _ = model.z_encoder(sample_batch, batch_index)
else:
sample_batch, _, _ = model.z_encoder(sample_batch)
y_pred = classifier(sample_batch)
else: # The model is the raw classifier
y_pred = model(sample_batch)
if not soft:
y_pred = y_pred.argmax(dim=-1)
all_y_pred += [y_pred.cpu()]
all_y_pred = np.array(torch.cat(all_y_pred))
all_y = np.array(torch.cat(all_y))
return all_y, all_y_pred
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/dataset/scvi/annotation_data_loader.py
| 0.849066 | 0.280179 |
annotation_data_loader.py
|
pypi
|
import numpy as np
import scanpy as sc
from scarchest.dataset.trvae import AnnotatedDataset
from scarchest.dataset.trvae._utils import label_encoder
class MetaAnnotatedDataset(object):
def __init__(self,
adata: sc.AnnData,
task_key: str,
meta_test_task: str = None,
task_encoder=None,
cell_type_key=None,
cell_type_encoder=None,
size_factors_key=None,
):
self.adata = adata
self.meta_test_task = meta_test_task
self.task_key = task_key
self.unique_tasks = list(np.unique(self.adata.obs[task_key]))
_, self.task_encoder = label_encoder(self.adata,
encoder=task_encoder,
condition_key=self.task_key)
self.meta_train_tasks = [task for task in self.unique_tasks if task != self.meta_test_task]
self.meta_test_tasks = [task for task in self.unique_tasks if task == self.meta_test_task]
self.cell_type_encoder = cell_type_encoder
self.cell_type_key = cell_type_key
self.unique_cell_types = np.unique(self.adata.obs[cell_type_key]) if self.cell_type_key else None
self.size_factors_key = size_factors_key
self.meta_train_tasks_adata = [AnnotatedDataset(
adata=self.adata[self.adata.obs[self.task_key] == task],
condition_key=self.task_key,
condition_encoder=self.task_encoder,
cell_type_key=self.cell_type_key,
cell_type_encoder=self.cell_type_encoder,
) for task in self.meta_train_tasks]
if self.meta_test_task is not None:
self.meta_test_task_adata = AnnotatedDataset(
adata=self.adata[self.adata.obs[self.task_key] == self.meta_test_task],
condition_key=self.task_key,
condition_encoder=self.task_encoder,
cell_type_key=self.cell_type_key,
cell_type_encoder=None,
size_factors_key=size_factors_key,
)
else:
self.meta_test_task_adata = None
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/dataset/mars/meta_anndata.py
| 0.545165 | 0.243789 |
meta_anndata.py
|
pypi
|
import numpy as np
import torch
from torch.utils.data import Dataset
from scipy import sparse
from .data_handling import remove_sparsity
from ._utils import label_encoder
class AnnotatedDataset(Dataset):
def __init__(self,
adata,
condition_key=None,
condition_encoder=None,
cell_type_key=None,
cell_type_encoder=None,
size_factors_key=None,
unique_conditions=None,
):
self.adata = adata
if sparse.issparse(self.adata.X):
self.adata = remove_sparsity(self.adata)
self.data = np.asarray(self.adata.X)
self.condition_encoder = condition_encoder
self.condition_key = condition_key
self.unique_conditions = unique_conditions
self.cell_type_encoder = cell_type_encoder
self.cell_type_key = cell_type_key
self.unique_cell_types = None
self.size_factors_key = size_factors_key
if self.condition_key is not None:
if self.unique_conditions is None:
self.unique_conditions = adata.obs[condition_key].unique().tolist()
self.conditions, self.condition_encoder = label_encoder(self.adata,
encoder=self.condition_encoder,
condition_key=condition_key)
self.conditions = np.array(self.conditions).reshape(-1, )
if self.cell_type_key is not None:
self.unique_cell_types = adata.obs[cell_type_key].unique().tolist()
self.cell_types, self.cell_type_encoder = label_encoder(self.adata,
encoder=self.cell_type_encoder,
condition_key=cell_type_key)
self.cell_types = np.array(self.cell_types).reshape(-1, )
if self.size_factors_key:
self.raw_data = np.array(self.adata.raw.X)
self.size_factors = np.array(self.adata.obs[self.size_factors_key].values).reshape(-1, )
def __getitem__(self, index):
outputs = dict()
outputs["x"] = torch.tensor(self.data[index, :])
if self.condition_key:
outputs["c"] = torch.tensor(self.conditions[index])
if self.cell_type_key:
outputs["y"] = torch.tensor(self.cell_types[index])
if self.size_factors_key:
outputs["raw"] = torch.tensor(self.raw_data[index, :])
outputs["f"] = torch.tensor(self.size_factors[index])
return outputs
def __len__(self):
return len(self.adata)
@property
def condition_label_encoder(self) -> dict:
return self.condition_encoder
@condition_label_encoder.setter
def condition_label_encoder(self, value: dict):
if value is not None:
self.condition_encoder = value
@property
def cell_type_label_encoder(self) -> dict:
return self.cell_type_encoder
@cell_type_label_encoder.setter
def cell_type_label_encoder(self, value: dict):
if value is not None:
self.cell_type_encoder = value
@property
def stratifier_weights(self):
condition_coeff = 1 / len(self.conditions)
weights_per_condition = list()
for i in range(len(self.conditions)):
samples_per_condition = np.count_nonzero(self.conditions == i)
if samples_per_condition == 0:
weights_per_condition.append(0)
else:
weights_per_condition.append((1 / samples_per_condition) * condition_coeff)
strat_weights = np.copy(self.conditions)
for i in range(len(self.conditions)):
strat_weights = np.where(strat_weights == i, weights_per_condition[i], strat_weights)
return strat_weights.astype(float)
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/dataset/trvae/anndata.py
| 0.822082 | 0.316132 |
anndata.py
|
pypi
|
import scanpy as sc
from scipy import sparse
def hvg_batch(adata, batch_key=None, target_genes=2000, flavor='cell_ranger', n_bins=20, adataout=False):
"""
Method to select HVGs based on mean dispersions of genes that are highly
variable genes in all batches. Using a the top target_genes per batch by
average normalize dispersion. If target genes still hasn't been reached,
then HVGs in all but one batches are used to fill up. This is continued
until HVGs in a single batch are considered.
"""
adata_hvg = adata if adataout else adata.copy()
n_batches = len(adata_hvg.obs[batch_key].cat.categories)
# Calculate double target genes per dataset
sc.pp.highly_variable_genes(adata_hvg,
flavor=flavor,
n_top_genes=target_genes,
n_bins=n_bins,
batch_key=batch_key)
nbatch1_dispersions = adata_hvg.var['dispersions_norm'][adata_hvg.var.highly_variable_nbatches >
len(adata_hvg.obs[batch_key].cat.categories) - 1]
nbatch1_dispersions.sort_values(ascending=False, inplace=True)
if len(nbatch1_dispersions) > target_genes:
hvg = nbatch1_dispersions.index[:target_genes]
else:
enough = False
print(f'Using {len(nbatch1_dispersions)} HVGs from full intersect set')
hvg = nbatch1_dispersions.index[:]
not_n_batches = 1
while not enough:
target_genes_diff = target_genes - len(hvg)
tmp_dispersions = adata_hvg.var['dispersions_norm'][adata_hvg.var.highly_variable_nbatches ==
(n_batches - not_n_batches)]
if len(tmp_dispersions) < target_genes_diff:
print(f'Using {len(tmp_dispersions)} HVGs from n_batch-{not_n_batches} set')
hvg = hvg.append(tmp_dispersions.index)
not_n_batches += 1
else:
print(f'Using {target_genes_diff} HVGs from n_batch-{not_n_batches} set')
tmp_dispersions.sort_values(ascending=False, inplace=True)
hvg = hvg.append(tmp_dispersions.index[:target_genes_diff])
enough = True
print(f'Using {len(hvg)} HVGs')
if not adataout:
del adata_hvg
return hvg.tolist()
else:
return adata_hvg[:, hvg].copy()
def remove_sparsity(adata):
"""
If ``adata.X`` is a sparse matrix, this will convert it in to normal matrix.
Parameters
----------
adata: :class:`~anndata.AnnData`
Annotated data matrix.
Returns
-------
adata: :class:`~anndata.AnnData`
Annotated dataset.
"""
if sparse.issparse(adata.X):
new_adata = sc.AnnData(X=adata.X.A, obs=adata.obs.copy(deep=True), var=adata.var.copy(deep=True))
return new_adata
return adata
def preprocess_data(adata,
filter_min_counts=True,
size_factors=True,
target_sum=None,
log_trans_input=True,
batch_key=None,
n_top_genes=1000,
scale=False):
"""Preprocesses the `adata`.
Parameters
----------
adata: `~anndata.AnnData`
Annotated data matrix.
filter_min_counts: boolean
If 'True' filter out Genes and Cells under min_count.
size_factors: boolean
If 'True' add Size Factors for ZINB/NB loss to 'adata'.
target_sum:
log_trans_input: boolean
If 'True' logarithmize the data matrix.
batch_key:
n_top_genes: int
Only keeps n highest variable genes in 'adata'
scale: boolean
If 'True' scale data to unit variance and zero mean.
Returns
-------
adata: `~anndata.AnnData`
Preprocessed annotated data matrix.
"""
if filter_min_counts:
sc.pp.filter_genes(adata, min_counts=1)
sc.pp.filter_cells(adata, min_counts=1)
adata_count = adata.copy()
obs = adata.obs_keys()
if size_factors and 'size_factors' not in obs:
sc.pp.normalize_total(adata,
target_sum=target_sum,
exclude_highly_expressed=False,
key_added='size_factors')
if log_trans_input:
sc.pp.log1p(adata)
if 0 < n_top_genes < adata.shape[1]:
if batch_key:
genes = hvg_batch(adata.copy(), batch_key=batch_key, adataout=False, target_genes=n_top_genes)
else:
sc.pp.highly_variable_genes(adata, n_top_genes=n_top_genes)
genes = adata.var['highly_variable']
adata = adata[:, genes]
adata_count = adata_count[:, genes]
if scale:
sc.pp.scale(adata)
if sparse.issparse(adata_count.X):
adata_count.X = adata_count.X.A
if sparse.issparse(adata.X):
adata.X = adata.X.A
if adata.raw is None:
adata.raw = adata_count.copy()
return adata
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/dataset/trvae/data_handling.py
| 0.808823 | 0.525308 |
data_handling.py
|
pypi
|
import numpy as np
import torch
from typing import Sequence
from torch.distributions import Normal, Categorical, kl_divergence as kl
from scvi.core.modules.utils import broadcast_labels
from scarchest.models.scvi._base import Decoder, Encoder
from .classifier import Classifier
from .scvi import scVI
class scANVI(scVI):
"""Single-cell annotation using variational inference.
This is an implementation of the scANVI model descibed in [Xu19]_,
inspired from M1 + M2 model, as described in (https://arxiv.org/pdf/1406.5298.pdf).
Parameters
----------
n_input
Number of input genes
n_batch
Number of batches
n_labels
Number of labels
n_hidden
Number of nodes per hidden layer
n_latent
Dimensionality of the latent space
n_layers
Number of hidden layers used for encoder and decoder NNs
dropout_rate
Dropout rate for neural networks
dispersion
One of the following
* ``'gene'`` - dispersion parameter of NB is constant per gene across cells
* ``'gene-batch'`` - dispersion can differ between different batches
* ``'gene-label'`` - dispersion can differ between different labels
* ``'gene-cell'`` - dispersion can differ for every gene in every cell
log_variational
Log(data+1) prior to encoding for numerical stability. Not normalization.
reconstruction_loss
One of
* ``'nb'`` - Negative binomial distribution
* ``'zinb'`` - Zero-inflated negative binomial distribution
y_prior
If None, initialized to uniform probability over cell types
labels_groups
Label group designations
use_labels_groups
Whether to use the label groups
Returns
-------
Examples
--------
>>> gene_dataset = CortexDataset()
>>> scanvi = SCANVI(gene_dataset.nb_genes, n_batch=gene_dataset.n_batches * False,
... n_labels=gene_dataset.n_labels)
>>> gene_dataset = SyntheticDataset(n_labels=3)
>>> scanvi = SCANVI(gene_dataset.nb_genes, n_batch=gene_dataset.n_batches * False,
... n_labels=3, y_prior=torch.tensor([[0.1,0.5,0.4]]), labels_groups=[0,0,1])
"""
def __init__(
self,
n_input: int,
n_batch: int = 0,
n_labels: int = 0,
n_hidden: int = 128,
n_latent: int = 10,
n_layers: int = 1,
dropout_rate: float = 0.1,
dispersion: str = "gene",
log_variational: bool = True,
gene_likelihood: str = "zinb",
y_prior=None,
labels_groups: Sequence[int] = None,
use_labels_groups: bool = False,
classifier_parameters: dict = dict(),
modified: bool = False,
):
super().__init__(
n_input,
n_batch=n_batch,
n_labels=n_labels,
n_hidden=n_hidden,
n_latent=n_latent,
n_layers=n_layers,
dropout_rate=dropout_rate,
dispersion=dispersion,
log_variational=log_variational,
gene_likelihood=gene_likelihood,
modified=modified,
)
# Classifier takes n_latent as input
self.cls_parameters = {
"n_layers": n_layers,
"n_hidden": n_hidden,
"dropout_rate": dropout_rate,
}
self.cls_parameters.update(classifier_parameters)
self.classifier = Classifier(n_latent, n_labels=n_labels, **self.cls_parameters)
self.encoder_z2_z1 = Encoder(
n_latent,
n_latent,
n_cat_list=[self.n_labels],
n_layers=n_layers,
n_hidden=n_hidden,
dropout_rate=dropout_rate,
)
self.decoder_z1_z2 = Decoder(
n_latent,
n_latent,
n_cat_list=[self.n_labels],
n_layers=n_layers,
n_hidden=n_hidden,
)
self.y_prior = torch.nn.Parameter(
y_prior
if y_prior is not None
else (1 / n_labels) * torch.ones(1, n_labels),
requires_grad=False,
)
self.use_labels_groups = use_labels_groups
self.labels_groups = (
np.array(labels_groups) if labels_groups is not None else None
)
if self.use_labels_groups:
assert labels_groups is not None, "Specify label groups"
unique_groups = np.unique(self.labels_groups)
self.n_groups = len(unique_groups)
assert (unique_groups == np.arange(self.n_groups)).all()
self.classifier_groups = Classifier(
n_latent, n_hidden, self.n_groups, n_layers, dropout_rate
)
self.groups_index = torch.nn.ParameterList(
[
torch.nn.Parameter(
torch.tensor(
(self.labels_groups == i).astype(np.uint8),
dtype=torch.uint8,
),
requires_grad=False,
)
for i in range(self.n_groups)
]
)
def classify(self, x, batch_index=None):
if self.log_variational:
x = torch.log(1 + x)
qz_m, _, z = self.z_encoder(x, batch_index)
# We classify using the inferred mean parameter of z_1 in the latent space
z = qz_m
if self.use_labels_groups:
w_g = self.classifier_groups(z)
unw_y = self.classifier(z)
w_y = torch.zeros_like(unw_y)
for i, group_index in enumerate(self.groups_index):
unw_y_g = unw_y[:, group_index]
w_y[:, group_index] = unw_y_g / (
unw_y_g.sum(dim=-1, keepdim=True) + 1e-8
)
w_y[:, group_index] *= w_g[:, [i]]
else:
w_y = self.classifier(z)
return w_y
def get_latents(self, x, y=None, batch_index=None):
zs = super().get_latents(x, batch_index=batch_index)
qz2_m, qz2_v, z2 = self.encoder_z2_z1(zs[0], y)
if not self.training:
z2 = qz2_m
return [zs[0], z2]
def forward(self, x, local_l_mean, local_l_var, batch_index=None, y=None):
is_labelled = False if y is None else True
outputs = self.inference(x, batch_index, y)
px_r = outputs["px_r"]
px_rate = outputs["px_rate"]
px_dropout = outputs["px_dropout"]
qz1_m = outputs["qz_m"]
qz1_v = outputs["qz_v"]
z1 = outputs["z"]
ql_m = outputs["ql_m"]
ql_v = outputs["ql_v"]
# Enumerate choices of label
ys, z1s = broadcast_labels(y, z1, n_broadcast=self.n_labels)
qz2_m, qz2_v, z2 = self.encoder_z2_z1(z1s, ys)
pz1_m, pz1_v = self.decoder_z1_z2(z2, ys)
reconst_loss = self.get_reconstruction_loss(x, px_rate, px_r, px_dropout)
# KL Divergence
mean = torch.zeros_like(qz2_m)
scale = torch.ones_like(qz2_v)
kl_divergence_z2 = kl(
Normal(qz2_m, torch.sqrt(qz2_v)), Normal(mean, scale)
).sum(dim=1)
loss_z1_unweight = -Normal(pz1_m, torch.sqrt(pz1_v)).log_prob(z1s).sum(dim=-1)
loss_z1_weight = Normal(qz1_m, torch.sqrt(qz1_v)).log_prob(z1).sum(dim=-1)
kl_divergence_l = kl(
Normal(ql_m, torch.sqrt(ql_v)),
Normal(local_l_mean, torch.sqrt(local_l_var)),
).sum(dim=1)
if is_labelled:
return (
reconst_loss + loss_z1_weight + loss_z1_unweight,
kl_divergence_z2 + kl_divergence_l,
0.0,
)
probs = self.classifier(z1)
reconst_loss += loss_z1_weight + (
(loss_z1_unweight).view(self.n_labels, -1).t() * probs
).sum(dim=1)
kl_divergence = (kl_divergence_z2.view(self.n_labels, -1).t() * probs).sum(
dim=1
)
kl_divergence += kl(
Categorical(probs=probs),
Categorical(probs=self.y_prior.repeat(probs.size(0), 1)),
)
kl_divergence += kl_divergence_l
return reconst_loss, kl_divergence, 0.0
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/models/scvi/scanvi.py
| 0.911155 | 0.59796 |
scanvi.py
|
pypi
|
"""Main module."""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Normal, kl_divergence as kl
from scvi.core._distributions import (
ZeroInflatedNegativeBinomial,
NegativeBinomial,
Poisson,
)
from scvi.core.modules.utils import one_hot
from scarchest.models.scvi._base import Encoder, DecoderSCVI
from typing import Tuple, Dict
torch.backends.cudnn.benchmark = True
# VAE model
class scVI(nn.Module):
"""Variational auto-encoder model.
This is an implementation of the scVI model descibed in [Lopez18]_
Parameters
----------
n_input
Number of input genes
n_batch
Number of batches, if 0, no batch correction is performed.
n_labels
Number of labels
n_hidden
Number of nodes per hidden layer
n_latent
Dimensionality of the latent space
n_layers
Number of hidden layers used for encoder and decoder NNs
dropout_rate
Dropout rate for neural networks
dispersion
One of the following
* ``'gene'`` - dispersion parameter of NB is constant per gene across cells
* ``'gene-batch'`` - dispersion can differ between different batches
* ``'gene-label'`` - dispersion can differ between different labels
* ``'gene-cell'`` - dispersion can differ for every gene in every cell
log_variational
Log(data+1) prior to encoding for numerical stability. Not normalization.
reconstruction_loss
One of
* ``'nb'`` - Negative binomial distribution
* ``'zinb'`` - Zero-inflated negative binomial distribution
* ``'poisson'`` - Poisson distribution
Examples
--------
>>> gene_dataset = CortexDataset()
>>> vae = VAE(gene_dataset.nb_genes, n_batch=gene_dataset.n_batches * False,
... n_labels=gene_dataset.n_labels)
"""
def __init__(
self,
n_input: int,
n_batch: int = 0,
n_labels: int = 0,
n_hidden: int = 128,
n_latent: int = 10,
n_layers: int = 1,
dropout_rate: float = 0.1,
dispersion: str = "gene",
log_variational: bool = True,
gene_likelihood: str = "zinb",
latent_distribution: str = "normal",
modified: bool = False,
):
super().__init__()
self.n_input = n_input
self.n_batch = n_batch
self.n_labels = n_labels
self.n_hidden = n_hidden
self.n_latent = n_latent
self.n_layers = n_layers
self.dropout_rate = dropout_rate
self.dispersion = dispersion
self.log_variational = log_variational
self.gene_likelihood = gene_likelihood
self.latent_distribution = latent_distribution
# Added for scArches
self.modified = modified
self.freeze = False
self.new_conditions = 0
if self.dispersion == "gene":
self.px_r = torch.nn.Parameter(torch.randn(n_input))
elif self.dispersion == "gene-batch":
self.px_r = torch.nn.Parameter(torch.randn(n_input, n_batch))
elif self.dispersion == "gene-label":
self.px_r = torch.nn.Parameter(torch.randn(n_input, n_labels))
elif self.dispersion == "gene-cell":
pass
else:
raise ValueError(
"dispersion must be one of ['gene', 'gene-batch',"
" 'gene-label', 'gene-cell'], but input was "
"{}.format(self.dispersion)"
)
# z encoder goes from the n_input-dimensional data to an n_latent-d
# latent space representation
self.z_encoder = Encoder(
n_input,
n_latent,
n_cat_list=[n_batch] if self.modified else None,
n_layers=n_layers,
n_hidden=n_hidden,
dropout_rate=self.dropout_rate,
distribution=latent_distribution,
modified=self.modified
)
# l encoder goes from n_input-dimensional data to 1-d library size
self.l_encoder = Encoder(
n_input,
1,
n_layers=1,
n_hidden=n_hidden,
dropout_rate=self.dropout_rate,
)
# decoder goes from n_latent-dimensional space to n_input-d data
self.decoder = DecoderSCVI(
n_latent,
n_input,
n_cat_list=[n_batch],
n_layers=n_layers,
n_hidden=n_hidden,
modified=modified
)
def get_latents(self, x, y=None, batch_index=None) -> torch.Tensor:
"""Returns the result of ``sample_from_posterior_z`` inside a list
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input)``
y
tensor of cell-types labels with shape ``(batch_size, n_labels)`` (Default value = None)
batch_index
tensor of study/batch labels with shape ``(batch_size, n_labels)`` (Default value = None)
Returns
-------
type
one element list of tensor
"""
return [self.sample_from_posterior_z(x, y=y, batch_index=batch_index)]
def sample_from_posterior_z(
self, x, y=None, batch_index=None, give_mean=False, n_samples=5000
) -> torch.Tensor:
"""Samples the tensor of latent values from the posterior
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input)``
y
tensor of cell-types labels with shape ``(batch_size, n_labels)`` (Default value = None)
batch_index
tensor of study/batch labels with shape ``(batch_size, n_labels)`` (Default value = None)
give_mean
is True when we want the mean of the posterior distribution rather than sampling (Default value = False)
n_samples
how many MC samples to average over for transformed mean (Default value = 5000)
Returns
-------
type
tensor of shape ``(batch_size, n_latent)``
"""
if self.log_variational:
x = torch.log(1 + x)
qz_m, qz_v, z = self.z_encoder(x, batch_index, y) # y only used in VAEC
if give_mean:
if self.latent_distribution == "ln":
samples = Normal(qz_m, qz_v.sqrt()).sample([n_samples])
z = self.z_encoder.z_transformation(samples)
z = z.mean(dim=0)
else:
z = qz_m
return z
def sample_from_posterior_l(self, x, batch_index=None, give_mean=True) -> torch.Tensor:
"""Samples the tensor of library sizes from the posterior
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input)``
batch_index
tensor of study/batch labels with shape ``(batch_size, n_labels)`` (Default value = None)
give_mean
Return mean or sample
Returns
-------
type
tensor of shape ``(batch_size, 1)``
"""
if self.log_variational:
x = torch.log(1 + x)
ql_m, ql_v, library = self.l_encoder(x, batch_index)
if give_mean is False:
library = library
else:
library = torch.distributions.LogNormal(ql_m, ql_v.sqrt()).mean
return library
def get_sample_scale(
self, x, batch_index=None, y=None, n_samples=1, transform_batch=None
) -> torch.Tensor:
"""Returns the tensor of predicted frequencies of expression
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input)``
batch_index
array that indicates which batch the cells belong to with shape ``batch_size`` (Default value = None)
y
tensor of cell-types labels with shape ``(batch_size, n_labels)`` (Default value = None)
n_samples
number of samples (Default value = 1)
transform_batch
int of batch to transform samples into (Default value = None)
Returns
-------
type
tensor of predicted frequencies of expression with shape ``(batch_size, n_input)``
"""
return self.inference(
x,
batch_index=batch_index,
y=y,
n_samples=n_samples,
transform_batch=transform_batch,
)["px_scale"]
def get_sample_rate(
self, x, batch_index=None, y=None, n_samples=1, transform_batch=None
) -> torch.Tensor:
"""Returns the tensor of means of the negative binomial distribution
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input)``
y
tensor of cell-types labels with shape ``(batch_size, n_labels)`` (Default value = None)
batch_index
array that indicates which batch the cells belong to with shape ``batch_size`` (Default value = None)
n_samples
number of samples (Default value = 1)
transform_batch
int of batch to transform samples into (Default value = None)
Returns
-------
type
tensor of means of the negative binomial distribution with shape ``(batch_size, n_input)``
"""
return self.inference(
x,
batch_index=batch_index,
y=y,
n_samples=n_samples,
transform_batch=transform_batch,
)["px_rate"]
def get_reconstruction_loss(
self, x, px_rate, px_r, px_dropout, **kwargs
) -> torch.Tensor:
# Reconstruction Loss
if self.gene_likelihood == "zinb":
reconst_loss = (
-ZeroInflatedNegativeBinomial(
mu=px_rate, theta=px_r, zi_logits=px_dropout
)
.log_prob(x)
.sum(dim=-1)
)
elif self.gene_likelihood == "nb":
reconst_loss = (
-NegativeBinomial(mu=px_rate, theta=px_r).log_prob(x).sum(dim=-1)
)
elif self.gene_likelihood == "poisson":
reconst_loss = -Poisson(px_rate).log_prob(x).sum(dim=-1)
return reconst_loss
def inference(
self, x, batch_index=None, y=None, n_samples=1, transform_batch=None
) -> Dict[str, torch.Tensor]:
"""Helper function used in forward pass
"""
x_ = x
if self.log_variational:
x_ = torch.log(1 + x_)
# Sampling
qz_m, qz_v, z = self.z_encoder(x_, batch_index, y)
ql_m, ql_v, library = self.l_encoder(x_, batch_index)
if n_samples > 1:
qz_m = qz_m.unsqueeze(0).expand((n_samples, qz_m.size(0), qz_m.size(1)))
qz_v = qz_v.unsqueeze(0).expand((n_samples, qz_v.size(0), qz_v.size(1)))
# when z is normal, untran_z == z
untran_z = Normal(qz_m, qz_v.sqrt()).sample()
z = self.z_encoder.z_transformation(untran_z)
ql_m = ql_m.unsqueeze(0).expand((n_samples, ql_m.size(0), ql_m.size(1)))
ql_v = ql_v.unsqueeze(0).expand((n_samples, ql_v.size(0), ql_v.size(1)))
library = Normal(ql_m, ql_v.sqrt()).sample()
if transform_batch is not None:
dec_batch_index = transform_batch * torch.ones_like(batch_index)
else:
dec_batch_index = batch_index
px_scale, px_r, px_rate, px_dropout = self.decoder(
self.dispersion, z, library, dec_batch_index, y
)
if self.dispersion == "gene-label":
px_r = F.linear(
one_hot(y, self.n_labels), self.px_r
) # px_r gets transposed - last dimension is nb genes
elif self.dispersion == "gene-batch":
px_r = F.linear(one_hot(dec_batch_index, self.n_batch), self.px_r)
elif self.dispersion == "gene":
px_r = self.px_r
px_r = torch.exp(px_r)
return dict(
px_scale=px_scale,
px_r=px_r,
px_rate=px_rate,
px_dropout=px_dropout,
qz_m=qz_m,
qz_v=qz_v,
z=z,
ql_m=ql_m,
ql_v=ql_v,
library=library,
)
def forward(
self, x, local_l_mean, local_l_var, batch_index=None, y=None
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Returns the reconstruction loss and the KL divergences
Parameters
----------
x
tensor of values with shape (batch_size, n_input)
local_l_mean
tensor of means of the prior distribution of latent variable l
with shape (batch_size, 1)
local_l_var
tensor of variancess of the prior distribution of latent variable l
with shape (batch_size, 1)
batch_index
array that indicates which batch the cells belong to with shape ``batch_size`` (Default value = None)
y
tensor of cell-types labels with shape (batch_size, n_labels) (Default value = None)
Returns
-------
type
the reconstruction loss and the Kullback divergences
"""
# Parameters for z latent distribution
outputs = self.inference(x, batch_index, y)
qz_m = outputs["qz_m"]
qz_v = outputs["qz_v"]
ql_m = outputs["ql_m"]
ql_v = outputs["ql_v"]
px_rate = outputs["px_rate"]
px_r = outputs["px_r"]
px_dropout = outputs["px_dropout"]
# KL Divergence
mean = torch.zeros_like(qz_m)
scale = torch.ones_like(qz_v)
kl_divergence_z = kl(Normal(qz_m, torch.sqrt(qz_v)), Normal(mean, scale)).sum(
dim=1
)
kl_divergence_l = kl(
Normal(ql_m, torch.sqrt(ql_v)),
Normal(local_l_mean, torch.sqrt(local_l_var)),
).sum(dim=1)
kl_divergence = kl_divergence_z
reconst_loss = self.get_reconstruction_loss(x, px_rate, px_r, px_dropout)
return reconst_loss + kl_divergence_l, kl_divergence, 0.0
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/models/scvi/scvi.py
| 0.960519 | 0.525978 |
scvi.py
|
pypi
|
"""Main module."""
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.distributions import Normal, kl_divergence as kl
from typing import Dict, Optional, Tuple, Union, List
from scvi.core._distributions import ZeroInflatedNegativeBinomial, NegativeBinomial
from scvi.core._log_likelihood import log_mixture_nb
from scvi.core.modules.utils import one_hot
from scarchest.models.scvi._base import DecoderTOTALVI, EncoderTOTALVI
torch.backends.cudnn.benchmark = True
# VAE model
class totalVI(nn.Module):
"""
Total variational inference for CITE-seq data.
Implements the totalVI model of [GayosoSteier20]_.
Parameters
----------
n_input_genes
Number of input genes
n_input_proteins
Number of input proteins
n_batch
Number of batches
n_labels
Number of labels
n_hidden
Number of nodes per hidden layer for encoder and decoder
n_latent
Dimensionality of the latent space
n_layers
Number of hidden layers used for encoder and decoder NNs
dropout_rate
Dropout rate for neural networks
genes_dispersion
One of the following
* ``'gene'`` - genes_dispersion parameter of NB is constant per gene across cells
* ``'gene-batch'`` - genes_dispersion can differ between different batches
* ``'gene-label'`` - genes_dispersion can differ between different labels
protein_dispersion
One of the following
* ``'protein'`` - protein_dispersion parameter is constant per protein across cells
* ``'protein-batch'`` - protein_dispersion can differ between different batches NOT TESTED
* ``'protein-label'`` - protein_dispersion can differ between different labels NOT TESTED
log_variational
Log(data+1) prior to encoding for numerical stability. Not normalization.
gene_likelihood
One of
* ``'nb'`` - Negative binomial distribution
* ``'zinb'`` - Zero-inflated negative binomial distribution
latent_distribution
One of
* ``'normal'`` - Isotropic normal
* ``'ln'`` - Logistic normal with normal params N(0, 1)
"""
def __init__(
self,
n_input_genes: int,
n_input_proteins: int,
n_batch: int = 0,
n_labels: int = 0,
n_hidden: int = 256,
n_latent: int = 20,
n_layers_encoder: int = 1,
n_layers_decoder: int = 1,
dropout_rate_decoder: float = 0.2,
dropout_rate_encoder: float = 0.2,
gene_dispersion: str = "gene",
protein_dispersion: str = "protein",
log_variational: bool = True,
gene_likelihood: str = "nb",
latent_distribution: str = "ln",
protein_batch_mask: List[np.ndarray] = None,
encoder_batch: bool = True,
):
super().__init__()
self.gene_dispersion = gene_dispersion
self.n_latent = n_latent
self.log_variational = log_variational
self.gene_likelihood = gene_likelihood
self.n_batch = n_batch
self.n_labels = n_labels
self.n_input_genes = n_input_genes
self.n_input_proteins = n_input_proteins
self.protein_dispersion = protein_dispersion
self.latent_distribution = latent_distribution
self.protein_batch_mask = protein_batch_mask
# parameters for prior on rate_back (background protein mean)
if n_batch > 0:
self.background_pro_alpha = torch.nn.Parameter(
torch.randn(n_input_proteins, n_batch)
)
self.background_pro_log_beta = torch.nn.Parameter(
torch.clamp(torch.randn(n_input_proteins, n_batch), -10, 1)
)
else:
self.background_pro_alpha = torch.nn.Parameter(
torch.randn(n_input_proteins)
)
self.background_pro_log_beta = torch.nn.Parameter(
torch.clamp(torch.randn(n_input_proteins), -10, 1)
)
if self.gene_dispersion == "gene":
self.px_r = torch.nn.Parameter(torch.randn(n_input_genes))
elif self.gene_dispersion == "gene-batch":
self.px_r = torch.nn.Parameter(torch.randn(n_input_genes, n_batch))
elif self.gene_dispersion == "gene-label":
self.px_r = torch.nn.Parameter(torch.randn(n_input_genes, n_labels))
else: # gene-cell
pass
if self.protein_dispersion == "protein":
self.py_r = torch.nn.Parameter(torch.ones(self.n_input_proteins))
elif self.protein_dispersion == "protein-batch":
self.py_r = torch.nn.Parameter(torch.ones(self.n_input_proteins, n_batch))
elif self.protein_dispersion == "protein-label":
self.py_r = torch.nn.Parameter(torch.ones(self.n_input_proteins, n_labels))
else: # protein-cell
pass
# z encoder goes from the n_input-dimensional data to an n_latent-d
# latent space representation
self.encoder = EncoderTOTALVI(
n_input_genes + self.n_input_proteins,
n_latent,
n_layers=n_layers_encoder,
n_cat_list=[n_batch] if encoder_batch else None,
n_hidden=n_hidden,
dropout_rate=dropout_rate_encoder,
distribution=latent_distribution,
)
self.decoder = DecoderTOTALVI(
n_latent,
n_input_genes,
self.n_input_proteins,
n_layers=n_layers_decoder,
n_cat_list=[n_batch],
n_hidden=n_hidden,
dropout_rate=dropout_rate_decoder,
)
def sample_from_posterior_z(
self,
x: torch.Tensor,
y: torch.Tensor,
batch_index: Optional[torch.Tensor] = None,
give_mean: bool = False,
n_samples: int = 5000,
) -> torch.Tensor:
"""
Access the tensor of latent values from the posterior.
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input_genes)``
y
tensor of values with shape ``(batch_size, n_input_proteins)``
batch_index
tensor of batch indices
give_mean
Whether to sample, or give mean of distribution
n_samples
Number of samples for monte carlo estimation
Returns
-------
type
tensor of shape ``(batch_size, n_latent)``
"""
if self.log_variational:
x = torch.log(1 + x)
y = torch.log(1 + y)
qz_m, qz_v, _, _, latent, _ = self.encoder(
torch.cat((x, y), dim=-1), batch_index
)
z = latent["z"]
if give_mean:
if self.latent_distribution == "ln":
samples = Normal(qz_m, qz_v.sqrt()).sample([n_samples])
z = self.encoder.z_transformation(samples)
z = z.mean(dim=0)
else:
z = qz_m
return z
def sample_from_posterior_l(
self,
x: torch.Tensor,
y: torch.Tensor,
batch_index: Optional[torch.Tensor] = None,
give_mean: bool = True,
) -> torch.Tensor:
"""
Provides the tensor of library size from the posterior.
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input_genes)``
y
tensor of values with shape ``(batch_size, n_input_proteins)``
batch_index
tensor of values with shape ``(batch_size, 1)``
give_mean
return mean of l or sample from it
Returns
-------
type
tensor of shape ``(batch_size, 1)``
"""
if self.log_variational:
x = torch.log(1 + x)
y = torch.log(1 + y)
_, _, ql_m, ql_v, latent, _ = self.encoder(
torch.cat((x, y), dim=-1), batch_index
)
library_gene = latent["l"]
if give_mean is True:
return torch.exp(ql_m + 0.5 * ql_v)
else:
return library_gene
def get_sample_dispersion(
self,
x: torch.Tensor,
y: torch.Tensor,
batch_index: Optional[torch.Tensor] = None,
label: Optional[torch.Tensor] = None,
n_samples: int = 1,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Returns the tensors of dispersions for genes and proteins.
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input_genes)``
y
tensor of values with shape ``(batch_size, n_input_proteins)``
batch_index
array that indicates which batch the cells belong to with shape ``batch_size``
label
tensor of cell-types labels with shape ``(batch_size, n_labels)``
n_samples
number of samples
Returns
-------
type
tensors of dispersions of the negative binomial distribution
"""
outputs = self.inference(
x, y, batch_index=batch_index, label=label, n_samples=n_samples
)
px_r = outputs["px_"]["r"]
py_r = outputs["py_"]["r"]
return px_r, py_r
def get_reconstruction_loss(
self,
x: torch.Tensor,
y: torch.Tensor,
px_dict: Dict[str, torch.Tensor],
py_dict: Dict[str, torch.Tensor],
pro_batch_mask_minibatch: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Compute reconstruction loss."""
px_ = px_dict
py_ = py_dict
# Reconstruction Loss
if self.gene_likelihood == "zinb":
reconst_loss_gene = (
-ZeroInflatedNegativeBinomial(
mu=px_["rate"], theta=px_["r"], zi_logits=px_["dropout"]
)
.log_prob(x)
.sum(dim=-1)
)
else:
reconst_loss_gene = (
-NegativeBinomial(mu=px_["rate"], theta=px_["r"])
.log_prob(x)
.sum(dim=-1)
)
reconst_loss_protein_full = -log_mixture_nb(
y, py_["rate_back"], py_["rate_fore"], py_["r"], None, py_["mixing"]
)
if pro_batch_mask_minibatch is not None:
temp_pro_loss_full = torch.zeros_like(reconst_loss_protein_full)
temp_pro_loss_full.masked_scatter_(
pro_batch_mask_minibatch.bool(), reconst_loss_protein_full
)
reconst_loss_protein = temp_pro_loss_full.sum(dim=-1)
else:
reconst_loss_protein = reconst_loss_protein_full.sum(dim=-1)
return reconst_loss_gene, reconst_loss_protein
def inference(
self,
x: torch.Tensor,
y: torch.Tensor,
batch_index: Optional[torch.Tensor] = None,
label: Optional[torch.Tensor] = None,
n_samples=1,
transform_batch: Optional[int] = None,
) -> Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]]:
"""
Internal helper function to compute necessary inference quantities.
We use the dictionary ``px_`` to contain the parameters of the ZINB/NB for genes.
The rate refers to the mean of the NB, dropout refers to Bernoulli mixing parameters.
`scale` refers to the quanity upon which differential expression is performed. For genes,
this can be viewed as the mean of the underlying gamma distribution.
We use the dictionary ``py_`` to contain the parameters of the Mixture NB distribution for proteins.
`rate_fore` refers to foreground mean, while `rate_back` refers to background mean. ``scale`` refers to
foreground mean adjusted for background probability and scaled to reside in simplex.
``back_alpha`` and ``back_beta`` are the posterior parameters for ``rate_back``. ``fore_scale`` is the scaling
factor that enforces `rate_fore` > `rate_back`.
``px_["r"]`` and ``py_["r"]`` are the inverse dispersion parameters for genes and protein, respectively.
"""
x_ = x
y_ = y
if self.log_variational:
x_ = torch.log(1 + x_)
y_ = torch.log(1 + y_)
# Sampling - Encoder gets concatenated genes + proteins
qz_m, qz_v, ql_m, ql_v, latent, untran_latent = self.encoder(
torch.cat((x_, y_), dim=-1), batch_index
)
z = latent["z"]
library_gene = latent["l"]
untran_z = untran_latent["z"]
untran_l = untran_latent["l"]
if n_samples > 1:
qz_m = qz_m.unsqueeze(0).expand((n_samples, qz_m.size(0), qz_m.size(1)))
qz_v = qz_v.unsqueeze(0).expand((n_samples, qz_v.size(0), qz_v.size(1)))
untran_z = Normal(qz_m, qz_v.sqrt()).sample()
z = self.encoder.z_transformation(untran_z)
ql_m = ql_m.unsqueeze(0).expand((n_samples, ql_m.size(0), ql_m.size(1)))
ql_v = ql_v.unsqueeze(0).expand((n_samples, ql_v.size(0), ql_v.size(1)))
untran_l = Normal(ql_m, ql_v.sqrt()).sample()
library_gene = self.encoder.l_transformation(untran_l)
if self.gene_dispersion == "gene-label":
# px_r gets transposed - last dimension is nb genes
px_r = F.linear(one_hot(label, self.n_labels), self.px_r)
elif self.gene_dispersion == "gene-batch":
px_r = F.linear(one_hot(batch_index, self.n_batch), self.px_r)
elif self.gene_dispersion == "gene":
px_r = self.px_r
px_r = torch.exp(px_r)
if self.protein_dispersion == "protein-label":
# py_r gets transposed - last dimension is n_proteins
py_r = F.linear(one_hot(label, self.n_labels), self.py_r)
elif self.protein_dispersion == "protein-batch":
py_r = F.linear(one_hot(batch_index, self.n_batch), self.py_r)
elif self.protein_dispersion == "protein":
py_r = self.py_r
py_r = torch.exp(py_r)
# Background regularization
if self.n_batch > 0:
py_back_alpha_prior = F.linear(
one_hot(batch_index, self.n_batch), self.background_pro_alpha
)
py_back_beta_prior = F.linear(
one_hot(batch_index, self.n_batch),
torch.exp(self.background_pro_log_beta),
)
else:
py_back_alpha_prior = self.background_pro_alpha
py_back_beta_prior = torch.exp(self.background_pro_log_beta)
self.back_mean_prior = Normal(py_back_alpha_prior, py_back_beta_prior)
if transform_batch is not None:
batch_index = torch.ones_like(batch_index) * transform_batch
px_, py_, log_pro_back_mean = self.decoder(z, library_gene, batch_index, label)
px_["r"] = px_r
py_["r"] = py_r
return dict(
px_=px_,
py_=py_,
qz_m=qz_m,
qz_v=qz_v,
z=z,
untran_z=untran_z,
ql_m=ql_m,
ql_v=ql_v,
library_gene=library_gene,
untran_l=untran_l,
log_pro_back_mean=log_pro_back_mean,
)
def forward(
self,
x: torch.Tensor,
y: torch.Tensor,
local_l_mean_gene: torch.Tensor,
local_l_var_gene: torch.Tensor,
batch_index: Optional[torch.Tensor] = None,
label: Optional[torch.Tensor] = None,
) -> Tuple[
torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor
]:
"""
Returns the reconstruction loss and the Kullback divergences.
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input_genes)``
y
tensor of values with shape ``(batch_size, n_input_proteins)``
local_l_mean_gene
tensor of means of the prior distribution of latent variable l
with shape ``(batch_size, 1)````
local_l_var_gene
tensor of variancess of the prior distribution of latent variable l
with shape ``(batch_size, 1)``
batch_index
array that indicates which batch the cells belong to with shape ``batch_size``
label
tensor of cell-types labels with shape (batch_size, n_labels)
Returns
-------
type
the reconstruction loss and the Kullback divergences
"""
# Parameters for z latent distribution
outputs = self.inference(x, y, batch_index, label)
qz_m = outputs["qz_m"]
qz_v = outputs["qz_v"]
ql_m = outputs["ql_m"]
ql_v = outputs["ql_v"]
px_ = outputs["px_"]
py_ = outputs["py_"]
if self.protein_batch_mask is not None:
pro_batch_mask_minibatch = torch.zeros_like(y)
for b in np.arange(len(torch.unique(batch_index))):
b_indices = (batch_index == b).reshape(-1)
pro_batch_mask_minibatch[b_indices] = torch.tensor(
self.protein_batch_mask[b].astype(np.float32), device=y.device
)
else:
pro_batch_mask_minibatch = None
reconst_loss_gene, reconst_loss_protein = self.get_reconstruction_loss(
x, y, px_, py_, pro_batch_mask_minibatch
)
# KL Divergence
kl_div_z = kl(Normal(qz_m, torch.sqrt(qz_v)), Normal(0, 1)).sum(dim=1)
kl_div_l_gene = kl(
Normal(ql_m, torch.sqrt(ql_v)),
Normal(local_l_mean_gene, torch.sqrt(local_l_var_gene)),
).sum(dim=1)
kl_div_back_pro_full = kl(
Normal(py_["back_alpha"], py_["back_beta"]), self.back_mean_prior
)
if pro_batch_mask_minibatch is not None:
kl_div_back_pro = (pro_batch_mask_minibatch * kl_div_back_pro_full).sum(
dim=1
)
else:
kl_div_back_pro = kl_div_back_pro_full.sum(dim=1)
return (
reconst_loss_gene,
reconst_loss_protein,
kl_div_z,
kl_div_l_gene,
kl_div_back_pro,
)
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/models/scvi/totalvi.py
| 0.956012 | 0.525795 |
totalvi.py
|
pypi
|
from typing import Optional
import torch
import torch.nn as nn
from scarchest.models.trvae._utils import one_hot_encoder
from .activations import ACTIVATIONS
from .losses import mse, kl
import numpy as np
def dense_block(i, in_features, out_features, use_batchnorm, dropout_rate, activation):
model = nn.Sequential()
model.add_module(name=f"FC_{i}",
module=nn.Linear(in_features, out_features, bias=False))
if use_batchnorm:
model.add_module(f"BN_{i}", module=nn.BatchNorm1d(out_features, affine=True))
model.add_module(name=f"ACT_{i}", module=ACTIVATIONS[activation])
if dropout_rate > 0:
model.add_module(name=f"DR_{i}", module=nn.Dropout(p=dropout_rate))
return model
class MARS(nn.Module):
def __init__(self, x_dim: int,
conditions: Optional[list] = [],
architecture: list = [128, 32],
z_dim: int = 10,
alpha=1e-3,
activation: str = 'elu',
output_activation: str = 'relu',
use_batchnorm: bool = False,
dropout_rate: float = 0.2):
super(MARS, self).__init__()
self.x_dim = x_dim
self.conditions = conditions if isinstance(conditions, list) else []
self.n_conditions = len(self.conditions)
self.condition_encoder = {k: v for k, v in zip(self.conditions, range(self.n_conditions))}
self.z_dim = z_dim
self.alpha = alpha
self.architecture = architecture
self.use_batchnorm = use_batchnorm
self.dropout_rate = dropout_rate
self.activation = activation
self.output_activation = output_activation
self.encoder_architecture = [self.x_dim + self.n_conditions] + self.architecture
self.decoder_architecture = [self.z_dim + self.n_conditions] + list(reversed(self.architecture))
self.encoder = nn.Sequential(
*[dense_block(i, in_size, out_size, use_batchnorm, dropout_rate, activation) for i, (in_size, out_size) in
enumerate(zip(self.encoder_architecture[:-1], self.encoder_architecture[1:]))])
self.mean = nn.Linear(self.encoder_architecture[-1], self.z_dim)
self.log_var = nn.Linear(self.encoder_architecture[-1], self.z_dim)
self.decoder = nn.Sequential(
*[dense_block(i, in_size, out_size, use_batchnorm, dropout_rate, activation) for i, (in_size, out_size) in
enumerate(zip(self.decoder_architecture[:-1], self.decoder_architecture[1:]))])
self.decoder.add_module(name='X_hat',
module=dense_block('X_hat', self.decoder_architecture[-1], self.x_dim, use_batchnorm,
dropout_rate, self.output_activation))
def sampling(self, mu, log_var):
"""Samples from standard Normal distribution and applies re-parametrization trick.
It is actually sampling from latent space distributions with N(mu, var), computed by encoder.
Parameters
----------
mu: torch.Tensor
Torch Tensor of Means.
log_var: torch.Tensor
Torch Tensor of log. variances.
Returns
-------
Torch Tensor of sampled data.
"""
std = torch.exp(0.5 * log_var)
eps = torch.randn_like(std)
return eps.mul(std).add(mu)
def forward(self, x, c=None):
if c is not None:
c = one_hot_encoder(c, n_cls=self.n_conditions)
xc = torch.cat((x, c), dim=-1)
else:
xc = x
encoded = self.encoder(xc)
mean_encoded = self.mean(encoded)
log_var_encoded = self.log_var(encoded)
encoded = self.sampling(mean_encoded, log_var_encoded)
if c is not None:
ec = torch.cat((encoded, c), dim=-1)
else:
ec = encoded
decoded = self.decoder(ec)
kl_loss = kl(mean_encoded, log_var_encoded)
recon_loss = mse(decoded, x) # TODO: support other loss functions
loss = recon_loss + self.alpha * kl_loss
return encoded, decoded, loss, recon_loss, kl_loss
def get_latent(self, x, c=None):
x = torch.as_tensor(np.array(x).astype(np.float)).type(torch.float32)
if c is not None:
c = torch.as_tensor(np.array(c).astype(np.int))
c = one_hot_encoder(c, n_cls=self.n_conditions)
xc = torch.cat((x, c), dim=-1)
else:
xc = x
encoded = self.encoder(xc)
mean_encoded = self.mean(encoded)
log_var_encoded = self.log_var(encoded)
encoded = self.sampling(mean_encoded, log_var_encoded)
return encoded.cpu().data.numpy()
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/models/mars/mars.py
| 0.94285 | 0.396127 |
mars.py
|
pypi
|
import torch
import numpy as np
from functools import partial
from torch.autograd import Variable
from ._utils import partition
def _nan2inf(x):
return torch.where(torch.isnan(x), torch.zeros_like(x) + np.inf, x)
def _nan2zero(x):
return torch.where(torch.isnan(x), torch.zeros_like(x), x)
def kl(mu, logvar):
"""Computes KL loss between tensor of means, log. variances and zero mean, unit variance.
Parameters
----------
mu: Tensor
Torch Tensor of means
logvar: Tensor
Torch Tensor of log. variances
Returns
-------
KL loss value
"""
kl_loss = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp(), )
kl_loss = kl_loss / mu.size(0)
return kl_loss
def mse(recon_x, x):
"""Computes MSE loss between reconstructed data and ground truth data.
Parameters
----------
recon_x: Tensor
Torch Tensor of reconstructed data
x: Tensor
Torch Tensor of ground truth data
Returns
-------
MSE loss value
"""
mse_loss = torch.nn.functional.mse_loss(recon_x, x, reduction="mean")
return mse_loss
def nb(x, mu, theta, eps=1e-8, mean=True):
"""Computes negative binomial loss.
Parameters
----------
x: Tensor
Torch Tensor of ground truth data.
mu: Tensor
Torch Tensor of means of the negative binomial (has to be positive support).
theta: Tensor
Torch Tensor of inverse dispersion parameter (has to be positive support).
eps: Float
numerical stability constant.
mean: boolean
If 'True' NB loss value gets returned, if 'False' NB loss Tensor gets returned with same shape as 'x'
(needed for ZINB loss calculation).
Returns
-------
If 'mean' is 'True' NB loss value gets returned, otherwise Torch tensor of losses gets returned.
"""
if theta.ndimension() == 1:
theta = theta.view(1, theta.size(0)) # In this case, we reshape theta for broadcasting
t1 = torch.lgamma(theta + eps) + torch.lgamma(x + 1.0) - torch.lgamma(x + theta + eps)
t2 = (theta + x) * torch.log(1.0 + (mu / (theta + eps))) + (x * (torch.log(theta + eps) - torch.log(mu + eps)))
final = t1 + t2
final = _nan2inf(final)
if mean:
final = torch.mean(final)
return final
def zinb(x, mu, theta, pi, eps=1e-8, ridge_lambda=0.0, mean=True):
"""Computes zero inflated negative binomial loss.
Parameters
----------
x: Tensor
Torch Tensor of ground truth data.
mu: Tensor
Torch Tensor of means of the negative binomial (has to be positive support).
theta: Tensor
Torch Tensor of inverses dispersion parameter (has to be positive support).
pi: Tensor
Torch Tensor of logits of the dropout parameter (real support)
eps: Float
numerical stability constant.
ridge_lambda: Float
Ridge Coefficient.
mean: boolean
If 'True' NB loss value gets returned, if 'False' NB loss Tensor gets returned with same shape as 'x'
(needed for ZINB loss calculation).
Returns
-------
If 'mean' is 'True' ZINB loss value gets returned, otherwise Torch tensor of losses gets returned.
"""
nb_case = nb(x, mu, theta, mean=False) - torch.log(1.0 - pi + eps)
if theta.ndimension() == 1:
theta = theta.view(1, theta.size(0)) # In this case, we reshape theta for broadcasting
zero_nb = torch.pow(theta / (theta + mu + eps), theta)
zero_case = -torch.log(pi + ((1.0 - pi) * zero_nb) + eps)
result = torch.where((x < 1e-8), zero_case, nb_case)
ridge = ridge_lambda * torch.square(pi)
result += ridge
if mean:
result = torch.mean(result)
result = _nan2inf(result)
return result
def pairwise_distance(x, y):
if not len(x.shape) == len(y.shape) == 2:
raise ValueError('Both inputs should be matrices.')
if x.shape[1] != y.shape[1]:
raise ValueError('The number of features should be the same.')
x = x.view(x.shape[0], x.shape[1], 1)
y = torch.transpose(y, 0, 1)
output = torch.sum((x - y) ** 2, 1)
output = torch.transpose(output, 0, 1)
return output
def gaussian_kernel_matrix(x, y, sigmas):
"""Computes multiscale-RBF kernel between x and y.
Parameters
----------
x: Tensor
Tensor with shape [batch_size, z_dim].
y: Tensor
Tensor with shape [batch_size, z_dim].
sigmas: Tensor
Returns
-------
Returns the computed multiscale-RBF kernel between x and y.
"""
sigmas = sigmas.view(sigmas.shape[0], 1)
beta = 1. / (2. * sigmas)
dist = pairwise_distance(x, y).contiguous()
dist_ = dist.view(1, -1)
s = torch.matmul(beta, dist_)
return torch.sum(torch.exp(-s), 0).view_as(dist)
def maximum_mean_discrepancy(x, y, kernel=gaussian_kernel_matrix):
"""Computes Maximum Mean Discrepancy(MMD) between x and y.
Parameters
----------
x: Tensor
Tensor with shape [batch_size, z_dim]
y: Tensor
Tensor with shape [batch_size, z_dim]
kernel: gaussian_kernel_matrix
Returns
-------
Returns the computed MMD between x and y.
"""
cost = torch.mean(kernel(x, x))
cost += torch.mean(kernel(y, y))
cost -= 2 * torch.mean(kernel(x, y))
return cost
def mmd_loss_calc(source_features, target_features):
"""Initializes Maximum Mean Discrepancy(MMD) between source_features and target_features.
Parameters
----------
source_features: Tensor
Tensor with shape [batch_size, z_dim]
target_features: Tensor
Tensor with shape [batch_size, z_dim]
Returns
-------
Returns the computed MMD between x and y.
"""
sigmas = [
1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1, 5, 10, 15, 20, 25, 30, 35, 100,
1e3, 1e4, 1e5, 1e6
]
if torch.cuda.is_available():
gaussian_kernel = partial(
gaussian_kernel_matrix, sigmas=Variable(torch.cuda.FloatTensor(sigmas))
)
else:
gaussian_kernel = partial(
gaussian_kernel_matrix, sigmas=Variable(torch.FloatTensor(sigmas))
)
loss_value = maximum_mean_discrepancy(source_features, target_features, kernel=gaussian_kernel)
return loss_value
def mmd(n_conditions, beta, boundary):
"""Initializes Maximum Mean Discrepancy(MMD) between every different condition.
Parameters
----------
n_conditions: integer
Number of classes (conditions) the data contain.
beta: float
beta coefficient for MMD loss.
boundary: integer
If not 'None', mmd loss is only calculated on #new conditions.
y: Tensor
Torch Tensor of computed latent data.
c: Tensor
Torch Tensor of labels
Returns
-------
Returns MMD loss.
"""
def mmd_loss(y, c):
# partition separates y into num_cls subsets w.r.t. their labels c
conditions_mmd = partition(y, c, n_conditions)
loss = 0.0
if boundary is not None:
for i in range(boundary):
for j in range(boundary, n_conditions):
if conditions_mmd[i].size(0) < 2 or conditions_mmd[j].size(0) < 2:
continue
loss += mmd_loss_calc(conditions_mmd[i], conditions_mmd[j])
else:
for i in range(len(conditions_mmd)):
if conditions_mmd[i].size(0) < 1:
continue
for j in range(i):
if conditions_mmd[j].size(0) < 1 or i == j:
continue
loss += mmd_loss_calc(conditions_mmd[i], conditions_mmd[j])
return beta * loss
return mmd_loss
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/models/trvae/losses.py
| 0.952386 | 0.853547 |
losses.py
|
pypi
|
import torch
import torch.nn as nn
from ._utils import one_hot_encoder
class CondLayers(nn.Module):
def __init__(
self,
n_in: int,
n_out: int,
n_cond: int,
bias: bool = True,
):
super().__init__()
self.n_cond = n_cond
self.expr_L = nn.Linear(n_in, n_out, bias=bias)
if self.n_cond != 0:
self.cond_L = nn.Linear(self.n_cond, n_out, bias=False)
def forward(self, x: torch.Tensor):
if self.n_cond == 0:
out = self.expr_L(x)
else:
expr, cond = torch.split(x, x.shape[1] - self.n_cond, dim=1)
out = self.expr_L(expr) + self.cond_L(cond)
return out
class Encoder(nn.Module):
"""Scnet Encoder class. Constructs the encoder sub-network of scNet. It will transform primary space input to means
and log. variances of latent space with n_dimensions = z_dimension.
Parameters
----------
layer_sizes: List
List of first and hidden layer sizes
latent_dim: Integer
Bottleneck layer (z) size.
use_bn: Boolean
If `True` batch normalization will applied to layers.
use_dr: Boolean
If `True` dropout will applied to layers.
dr_rate: Float
Dropput rate applied to all layers, if `dr_rate`==0 no dropput will be applied.
num_classes: Integer
Number of classes (conditions) the data contain. if `None` the model will be a normal VAE instead of
conditional VAE.
Returns
-------
"""
def __init__(self, layer_sizes, latent_dim,
use_bn, use_dr, dr_rate, num_classes=None):
super().__init__()
self.n_classes = 0
if num_classes is not None:
self.n_classes = num_classes
self.FC = None
if len(layer_sizes) > 1:
print("Encoder Architecture:")
self.FC = nn.Sequential()
for i, (in_size, out_size) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):
if i == 0:
print("\tInput Layer in, out and cond:", in_size, out_size, self.n_classes)
self.FC.add_module(name="L{:d}".format(i), module=CondLayers(in_size,
out_size,
self.n_classes,
bias=False))
else:
print("\tHidden Layer", i, "in/out:", in_size, out_size)
self.FC.add_module(name="L{:d}".format(i), module=nn.Linear(in_size, out_size, bias=False))
if use_bn:
self.FC.add_module("B{:d}".format(i), module=nn.BatchNorm1d(out_size, affine=True))
self.FC.add_module(name="A{:d}".format(i), module=nn.ReLU())
if use_dr:
self.FC.add_module(name="D{:d}".format(i), module=nn.Dropout(p=dr_rate))
print("\tMean/Var Layer in/out:", layer_sizes[-1], latent_dim)
self.mean_encoder = nn.Linear(layer_sizes[-1], latent_dim)
self.log_var_encoder = nn.Linear(layer_sizes[-1], latent_dim)
def forward(self, x, c=None):
if c is not None:
c = one_hot_encoder(c, n_cls=self.n_classes)
x = torch.cat((x, c), dim=-1)
if self.FC is not None:
x = self.FC(x)
means = self.mean_encoder(x)
log_vars = self.log_var_encoder(x)
return means, log_vars
class Decoder(nn.Module):
"""Scnet Decoder class. Constructs the decoder sub-network of scNet. It will transform constructed latent space to
the previous space of data with n_dimensions = x_dimension.
Parameters
----------
layer_sizes: List
List of hidden and last layer sizes
latent_dim: Integer
Bottleneck layer (z) size.
recon_loss: String
Definition of Reconstruction-Loss-Method, 'mse', 'nb' or 'zinb'.
use_bn: Boolean
If `True` batch normalization will applied to layers.
use_dr: Boolean
If `True` dropout will applied to layers.
dr_rate: Float
Dropput rate applied to all layers, if `dr_rate`==0 no dropput will be applied.
use_mmd: boolean
If `True` then MMD will be applied to first decoder layer.
num_classes: Integer
Number of classes (conditions) the data contain. if `None` the model will be a normal VAE instead of
conditional VAE.
output_active: String
Defines the Activation for the last layer of decoder if 'recon_loss' is 'mse'.
Returns
-------
"""
def __init__(self, layer_sizes, latent_dim, recon_loss, use_bn, use_dr, dr_rate, use_mmd=False, num_classes=None):
super().__init__()
self.use_mmd = use_mmd
self.use_bn = use_bn
self.use_dr = use_dr
self.recon_loss = recon_loss
self.n_classes = 0
if num_classes is not None:
self.n_classes = num_classes
layer_sizes = [latent_dim] + layer_sizes
print("Decoder Architecture:")
# Create first Decoder layer
self.FirstL = nn.Sequential()
print("\tFirst Layer in/out: ", layer_sizes[0], layer_sizes[1])
self.FirstL.add_module(name="L0", module=CondLayers(layer_sizes[0], layer_sizes[1], self.n_classes, bias=False))
if self.use_bn:
self.FirstL.add_module("B0", module=nn.BatchNorm1d(layer_sizes[1], affine=True))
self.FirstL.add_module(name="A0", module=nn.ReLU())
if self.use_dr:
self.FirstL.add_module(name="D0", module=nn.Dropout(p=dr_rate))
# Create all Decoder hidden layers
if len(layer_sizes) > 2:
self.HiddenL = nn.Sequential()
for i, (in_size, out_size) in enumerate(zip(layer_sizes[1:-1], layer_sizes[2:])):
if i+3 < len(layer_sizes):
print("\tHidden Layer", i+1, "in/out:", in_size, out_size)
self.HiddenL.add_module(name="L{:d}".format(i+1), module=nn.Linear(in_size, out_size, bias=False))
if self.use_bn:
self.HiddenL.add_module("B{:d}".format(i+1), module=nn.BatchNorm1d(out_size, affine=True))
self.HiddenL.add_module(name="A{:d}".format(i+1), module=nn.ReLU())
if self.use_dr:
self.HiddenL.add_module(name="D{:d}".format(i+1), module=nn.Dropout(p=dr_rate))
else:
self.HiddenL = None
# Create Output Layers
print("\tOutput Layer in/out: ", layer_sizes[-2], layer_sizes[-1], "\n")
if self.recon_loss == "mse":
self.OutputLayer = nn.Sequential()
self.OutputLayer.add_module(name="outputL", module=nn.Linear(layer_sizes[-2], layer_sizes[-1]))
self.OutputLayer.add_module(name="outputA", module=nn.ReLU())
if self.recon_loss == "zinb":
# mean gamma
self.mean_decoder = nn.Linear(layer_sizes[-2], layer_sizes[-1])
# dispersion: here we only deal with gene-cell dispersion case
self.disp_decoder = nn.Sequential(nn.Linear(layer_sizes[-2], layer_sizes[-1]), nn.Softplus())
# dropout
self.dropout_decoder = nn.Sequential(nn.Linear(layer_sizes[-2], layer_sizes[-1]), nn.Sigmoid())
if self.recon_loss == "nb":
# mean gamma
self.mean_decoder = nn.Linear(layer_sizes[-2], layer_sizes[-1])
# dispersion: here we only deal with gene-cell dispersion case
self.disp_decoder = nn.Sequential(nn.Linear(layer_sizes[-2], layer_sizes[-1]), nn.Softplus())
def forward(self, z, c=None):
# Add Condition Labels to Decoder Input
if c is not None:
c = one_hot_encoder(c, n_cls=self.n_classes)
z_cat = torch.cat((z, c), dim=-1)
dec_latent = self.FirstL(z_cat)
else:
dec_latent = self.FirstL(z)
# Compute Hidden Output
if self.HiddenL is not None:
x = self.HiddenL(dec_latent)
else:
x = dec_latent
# Compute Decoder Output
if self.recon_loss == "mse":
output = self.OutputLayer(x)
return output, dec_latent
if self.recon_loss == "zinb":
# Parameters for ZINB and NB
dec_mean_gamma = self.mean_decoder(x)
dec_mean_gamma = torch.clamp(torch.exp(dec_mean_gamma), min=1e-4, max=1e4)
dec_disp = self.disp_decoder(x)
dec_disp = torch.clamp(dec_disp, min=1e-6, max=1e6)
dec_dropout = self.dropout_decoder(x)
return dec_mean_gamma, dec_dropout, dec_disp, dec_latent
if self.recon_loss == "nb":
# Parameters for ZINB and NB
dec_mean_gamma = self.mean_decoder(x)
dec_mean_gamma = torch.clamp(torch.exp(dec_mean_gamma), min=1e-4, max=1e4)
dec_disp = self.disp_decoder(x)
dec_disp = torch.clamp(dec_disp, min=1e-6, max=1e6)
return dec_mean_gamma, dec_disp, dec_latent
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/models/trvae/modules.py
| 0.954276 | 0.410756 |
modules.py
|
pypi
|
from typing import Optional
import torch
import torch.nn as nn
from .modules import Encoder, Decoder
from .losses import mse, mmd, zinb, nb, kl
class trVAE(nn.Module):
"""scNet class. This class contains the implementation of Conditional Variational Auto-encoder.
Parameters
----------
input_dim: integer
Number of input features (i.e. gene in case of scRNA-seq).
conditions: integer
Number of classes (conditions) the data contain. if `None` the model will be a normal VAE instead of
conditional VAE.
encoder_layer_sizes: List
A list of hidden layer sizes for encoder network.
latent_dim: integer
Bottleneck layer (z) size.
decoder_layer_sizes: List
A list of hidden layer sizes for decoder network.
recon_loss: String
Definition of Reconstruction-Loss-Method, 'mse', 'nb' or 'zinb'.
alpha: float
Alpha coefficient for KL loss.
use_batch_norm: boolean
If `True` batch normalization will applied to hidden layers.
dr_rate: float
Dropput rate applied to all layers, if `dr_rate`==0 no dropput will be applied.
use_mmd: boolean
If `True` then MMD will be applied to first decoder layer.
beta: float
beta coefficient for MMD loss.
eta: float
Eta coefficient for Reconstruction loss.
calculate_mmd: String
Defines the layer which the mmd loss is calculated on, 'y' for first layer of decoder or 'z' for bottleneck
layer.
"""
def __init__(self,
input_dim: int,
conditions: list,
encoder_layer_sizes: list = [256, 64],
latent_dim: int = 32,
decoder_layer_sizes: list = [64, 256],
dr_rate: float = 0.05,
use_batch_norm: bool = False,
calculate_mmd: Optional[str] = 'z',
mmd_boundary: Optional[int] = None,
recon_loss: Optional[str] = 'zinb',
alpha: Optional[float] = 0.0005,
beta: Optional[float] = 200,
eta: Optional[float] = 5000):
super().__init__()
assert isinstance(encoder_layer_sizes, list)
assert isinstance(latent_dim, int)
assert isinstance(decoder_layer_sizes, list)
assert isinstance(conditions, list)
assert recon_loss in ["mse", "nb", "zinb"], "'recon_loss' must be 'mse', 'nb' or 'zinb'"
assert calculate_mmd in [None, "y", "z"], "'calculate_mmd' must be None, 'y' or 'z'"
print("\nINITIALIZING NEW NETWORK..............")
self.input_dim = input_dim
self.latent_dim = latent_dim
self.n_conditions = len(conditions)
self.conditions = conditions
self.condition_encoder = {k: v for k, v in zip(conditions, range(len(conditions)))}
self.recon_loss = recon_loss
self.alpha = alpha
self.beta = beta
self.eta = eta
self.dr_rate = dr_rate
if self.dr_rate > 0:
self.use_dr = True
else:
self.use_dr = False
self.use_bn = use_batch_norm
self.calculate_mmd = calculate_mmd
self.mmd_boundary = mmd_boundary
self.use_mmd = True if self.calculate_mmd in ['z', 'y'] else False
self.enc_layer_sizes = encoder_layer_sizes.copy()
self.dec_layer_sizes = decoder_layer_sizes.copy()
encoder_layer_sizes.insert(0, self.input_dim)
decoder_layer_sizes.append(self.input_dim)
self.encoder = Encoder(encoder_layer_sizes, self.latent_dim,
self.use_bn, self.use_dr, self.dr_rate, self.n_conditions)
self.decoder = Decoder(decoder_layer_sizes, self.latent_dim, self.recon_loss, self.use_bn, self.use_dr,
self.dr_rate, self.use_mmd, self.n_conditions)
self.freeze = False
def sampling(self, mu, log_var):
"""Samples from standard Normal distribution and applies re-parametrization trick.
It is actually sampling from latent space distributions with N(mu, var), computed by encoder.
Parameters
----------
mu: torch.Tensor
Torch Tensor of Means.
log_var: torch.Tensor
Torch Tensor of log. variances.
Returns
-------
Torch Tensor of sampled data.
"""
std = torch.exp(0.5 * log_var)
eps = torch.randn_like(std)
return eps.mul(std).add(mu)
def generate_with_condition(self, n_samples, c=None):
z = torch.randn([n_samples, self.latent_dim])
if c is not None:
c = torch.ones([n_samples, 1], device=self.device) * c
output = self.decoder(z, c)
# If recon Loss is zinb, how to get recon_x?
return output
def get_latent(self, x, c=None, mean=False):
"""Map `x` in to the latent space. This function will feed data in encoder and return z for each sample in
data.
Parameters
----------
x: numpy nd-array
Numpy nd-array to be mapped to latent space. `x` has to be in shape [n_obs, input_dim].
c: `numpy nd-array`
`numpy nd-array` of original desired labels for each sample.
mean: boolean
Returns
-------
Returns array containing latent space encoding of 'x'.
"""
if c is not None:
c = torch.tensor(c, device=self.device)
x = torch.tensor(x, device=self.device)
z_mean, z_log_var = self.encoder(x, c)
latent = self.sampling(z_mean, z_log_var)
if mean:
return z_mean
return latent.cpu().data.numpy()
def get_y(self, x, c=None):
"""Map `x` in to the y dimension (First Layer of Decoder). This function will feed data in encoder and return
y for each sample in data.
Parameters
----------
x: numpy nd-array
Numpy nd-array to be mapped to latent space. `x` has to be in shape [n_obs, input_dim].
c: `numpy nd-array`
`numpy nd-array` of original desired labels for each sample.
Returns
-------
Returns array containing latent space encoding of 'x'
"""
if c is not None:
c = torch.tensor(c).to(self.device)
x = torch.tensor(x).to(self.device)
z_mean, z_log_var = self.encoder(x, c)
latent = self.sampling(z_mean, z_log_var)
output = self.decoder(latent, c)
return output[-1].cpu().data.numpy()
def calc_recon_binomial_loss(self, outputs, x_raw, size_factor):
dec_mean_gamma = outputs["dec_mean_gamma"]
size_factor_view = size_factor.unsqueeze(1).expand(dec_mean_gamma.size(0), dec_mean_gamma.size(1))
dec_mean = dec_mean_gamma * size_factor_view
if outputs["dec_dropout"] is None:
recon_loss = nb(x_raw, dec_mean, outputs["dec_disp"])
else:
recon_loss = zinb(x_raw, dec_mean, outputs["dec_disp"], outputs["dec_dropout"])
return recon_loss
def inference(self, x, c=None):
z1_mean, z1_log_var = self.encoder(x, c)
z1 = self.sampling(z1_mean, z1_log_var)
outputs = self.decoder(z1, c)
recon_x = dec_mean_gamma = dec_dropout = dec_disp = y1 = None
if self.recon_loss == "mse":
recon_x, y1 = outputs
if self.recon_loss == "zinb":
dec_mean_gamma, dec_dropout, dec_disp, y1 = outputs
if self.recon_loss == "nb":
dec_mean_gamma, dec_disp, y1 = outputs
return dict(
z1_mean=z1_mean,
z1_log_var=z1_log_var,
z1=z1,
y1=y1,
recon_x=recon_x,
dec_mean_gamma=dec_mean_gamma,
dec_dropout=dec_dropout,
dec_disp=dec_disp,
)
def forward(self, x=None, raw=None, f=None, c=None, y=None):
outputs = self.inference(x, c)
if outputs["recon_x"] is not None:
recon_loss = mse(outputs["recon_x"], x)
else:
recon_loss = self.calc_recon_binomial_loss(outputs, raw, f)
recon_loss *= self.eta
kl_div = kl(outputs["z1_mean"], outputs["z1_log_var"])
kl_loss = self.alpha * kl_div
mmd_loss = 0
if self.calculate_mmd is not None:
mmd_calculator = mmd(self.n_conditions, self.beta, self.mmd_boundary)
if self.calculate_mmd == "z":
mmd_loss = mmd_calculator(outputs["z1"], c)
else:
mmd_loss = mmd_calculator(outputs["y1"], c)
return recon_loss, kl_loss, mmd_loss
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/models/trvae/trvae.py
| 0.970219 | 0.704795 |
trvae.py
|
pypi
|
import numpy as np
from typing import Union
import torch
import torch.nn as nn
import anndata
from scvi.data import get_from_registry
from scarchest.models import scVI, scANVI
from scarchest.trainers import scVITrainer, scANVITrainer, UnlabelledScanviTrainer
def weight_update_check(old_network, op_network):
for op_name, op_p in op_network.named_parameters():
for name, p in old_network.named_parameters():
if op_name == name:
comparison = torch.eq(p, op_p)
if False in comparison:
print("UPDATED WEIGHTS", op_name)
for name, module in op_network.named_modules():
if isinstance(module, nn.BatchNorm1d):
if module.affine == False and module.track_running_stats == False:
print("FROZEN BATCHNORM:", name)
def scvi_operate(
network: Union[scVI, scANVI],
data: anndata.AnnData,
labels_per_class: int = 0,
n_epochs: int = 50,
freeze: bool = True,
freeze_expression: bool = True,
remove_dropout: bool = False,
) -> [Union[scVI, scANVI], Union[scVITrainer, scANVITrainer], anndata.AnnData]:
"""Transfer Learning function for new data. Uses old trained Network and expands it for new conditions.
Parameters
----------
network: VAE_M, SCANVI_M
A Scvi/Scanvi model object.
data: GeneExpressionDataset
GeneExpressionDataset object.
labels_per_class: Integer
Number of labelled Samples used for Retraining
n_epochs: Integer
Number of epochs for training the network on query data.
freeze: Boolean
If 'True' freezes every part of the network except the first layers of encoder/decoder.
freeze_expression: Boolean
If 'True' freeze every weight in first layers except the condition weights.
remove_dropout: Boolean
If 'True' remove Dropout for Transfer Learning.
Returns
-------
op_network: VAE_M, SCANVI_M
Newly network that got trained on query data.
op_trainer: UnsupervisedTrainer, SemiSupervisedTrainer
Trainer for the newly network.
data: GeneExpressionDataset
GeneExpressionDataset object with updated batch labels.
"""
early_stopping_kwargs = {
"early_stopping_metric": "elbo",
"save_best_state_metric": "elbo",
"patience": 15,
"threshold": 0,
"reduce_lr_on_plateau": True,
"lr_patience": 8,
"lr_factor": 0.1,
}
early_stopping_kwargs_scanvi = {
"early_stopping_metric": "accuracy",
"save_best_state_metric": "accuracy",
"on": "full_dataset",
"patience": 15,
"threshold": 0.001,
"reduce_lr_on_plateau": True,
"lr_patience": 8,
"lr_factor": 0.1,
}
# Update DR Rate
new_dr = network.dropout_rate
if remove_dropout:
new_dr = 0.0
n_new_conditions = data.uns["_scvi"]["summary_stats"]["n_batch"]
adata = data.copy()
adata.obs['_scvi_batch'] = get_from_registry(adata, "batch_indices").astype(np.int8) + network.n_batch
n_conditions = network.n_batch + n_new_conditions
if type(network) is scVI:
print("Create new VAE....")
op_network = scVI(
n_input=network.n_input,
n_batch=n_conditions,
n_hidden=network.n_hidden,
n_latent=network.n_latent,
n_layers=network.n_layers,
dropout_rate=new_dr,
dispersion=network.dispersion,
log_variational=network.log_variational,
gene_likelihood=network.gene_likelihood,
latent_distribution=network.latent_distribution,
modified=network.modified,
)
elif type(network) is scANVI:
print("Create new SCANVI....")
op_network = scANVI(
n_input=network.n_input,
n_batch=n_conditions,
n_labels=network.n_labels,
n_hidden=network.n_hidden,
n_latent=network.n_latent,
n_layers=network.n_layers,
dropout_rate=new_dr,
dispersion=network.dispersion,
log_variational=network.log_variational,
gene_likelihood=network.gene_likelihood,
y_prior=network.y_prior,
labels_groups=network.labels_groups,
use_labels_groups=network.use_labels_groups,
classifier_parameters=network.cls_parameters,
modified=network.modified,
)
else:
print("Please use a compatible model for this operate function")
exit()
op_network.new_conditions = n_new_conditions
if network.modified:
# Expand first Layer weights of z encoder of old network by new conditions
encoder_input_weights = network.z_encoder.encoder.fc_layers.Layer0.L.cond_L.weight
to_be_added_encoder_input_weights = np.random.randn(encoder_input_weights.size()[0], n_new_conditions) * \
np.sqrt(2 / (encoder_input_weights.size()[0] + 1 +
encoder_input_weights.size()[1]))
to_be_added_encoder_input_weights = torch.tensor(
to_be_added_encoder_input_weights,
device=encoder_input_weights.get_device()).float()
network.z_encoder.encoder.fc_layers.Layer0.L.cond_L.weight.data = torch.cat(
(network.z_encoder.encoder.fc_layers.Layer0.L.cond_L.weight, to_be_added_encoder_input_weights), 1)
# Expand first Layer weights of decoder of old network by new conditions
decoder_input_weights = network.decoder.px_decoder.fc_layers.Layer0.L.cond_L.weight
to_be_added_decoder_input_weights = np.random.randn(decoder_input_weights.size()[0], n_new_conditions) * \
np.sqrt(2 / (decoder_input_weights.size()[0] + 1 +
decoder_input_weights.size()[1]))
to_be_added_decoder_input_weights = torch.tensor(
to_be_added_decoder_input_weights,
device=decoder_input_weights.get_device()).float()
network.decoder.px_decoder.fc_layers.Layer0.L.cond_L.weight.data = torch.cat(
(network.decoder.px_decoder.fc_layers.Layer0.L.cond_L.weight, to_be_added_decoder_input_weights), 1)
else:
for layer in network.decoder.px_decoder.fc_layers:
decoder_input_weights = layer.L.cond_L.weight
to_be_added_decoder_input_weights = np.random.randn(decoder_input_weights.size()[0], n_new_conditions) * \
np.sqrt(2 / (decoder_input_weights.size()[0] + 1 +
decoder_input_weights.size()[1]))
to_be_added_decoder_input_weights = torch.tensor(
to_be_added_decoder_input_weights,
device=decoder_input_weights.get_device()).float()
layer.L.cond_L.weight.data = torch.cat(
(layer.L.cond_L.weight, to_be_added_decoder_input_weights), 1)
# Set the weights of new network to old network weights
op_network.load_state_dict(network.state_dict())
# Freeze parts of the network
if freeze:
op_network.freeze = True
for name, p in op_network.named_parameters():
p.requires_grad = False
if freeze_expression:
if network.modified:
if 'cond_L.weight' in name and ('z_encoder' in name or 'px_decoder' in name):
p.requires_grad = True
if 'l_encoder' in name:
p.requires_grad = True
else:
if 'cond_L.weight' in name and ('z_encoder' in name or 'px_decoder' in name):
p.requires_grad = True
if 'z_encoder' in name and 'Layer0' in name:
p.requires_grad = True
if 'l_encoder' in name:
p.requires_grad = True
else:
if network.modified:
if ('z_encoder' in name or 'px_decoder' in name) and 'Layer0' in name:
p.requires_grad = True
if 'l_encoder' in name:
p.requires_grad = True
else:
if 'z_encoder' in name and 'Layer0' in name:
p.requires_grad = True
if 'px_decoder' in name:
p.requires_grad = True
# Retrain Networks
if type(network) is scVI:
op_trainer = scVITrainer(
op_network,
adata,
train_size=0.9,
use_cuda=True,
frequency=1,
early_stopping_kwargs=early_stopping_kwargs
)
op_trainer.train(n_epochs=n_epochs, lr=1e-3)
if type(network) is scANVI:
if labels_per_class == 0:
op_trainer = UnlabelledScanviTrainer(
op_network,
adata,
n_labelled_samples_per_class=labels_per_class,
train_size=0.9,
use_cuda=True,
frequency=1,
early_stopping_kwargs=early_stopping_kwargs_scanvi
)
else:
op_trainer = scANVITrainer(
op_network,
adata,
n_labelled_samples_per_class=labels_per_class,
classification_ratio=50,
train_size=0.9,
use_cuda=True,
frequency=1,
early_stopping_kwargs=early_stopping_kwargs_scanvi
)
op_trainer.train(n_epochs=n_epochs, lr=1e-3)
weight_update_check(network, op_network)
return op_network, op_trainer, adata
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/surgery/scvi.py
| 0.883864 | 0.328893 |
scvi.py
|
pypi
|
import numpy as np
from typing import Union
import torch
from scarchest.models.trvae.trvae import trVAE
def trvae_operate(network: trVAE,
data_conditions: Union[list, str],
freeze: bool = True,
freeze_expression: bool = True,
remove_dropout: bool = True,
) -> trVAE:
"""Transfer Learning function for new data. Uses old trained Network and expands it for new conditions.
Parameters
----------
network: trVAE
A scNet model object.
data_conditions: list_str
List of Strings of new Conditions.
freeze: Boolean
If 'True' freezes every part of the network except the first layers of encoder/decoder.
remove_dropout: Boolean
If 'True' remove Dropout for Transfer Learning.
Returns
-------
new_network: trVAE
New expanded network with old weights for Transfer Learning.
"""
conditions = network.conditions
new_conditions = []
# Check if new conditions are already known
for item in data_conditions:
if item not in conditions:
new_conditions.append(item)
n_new_conditions = len(new_conditions)
# Add new conditions to overall conditions
for condition in new_conditions:
conditions.append(condition)
# Update DR Rate
new_dr = network.dr_rate
if remove_dropout:
new_dr = 0.0
new_network = trVAE(
network.input_dim,
conditions=conditions,
encoder_layer_sizes=network.enc_layer_sizes,
latent_dim=network.latent_dim,
decoder_layer_sizes=network.dec_layer_sizes,
recon_loss=network.recon_loss,
alpha=network.alpha,
use_batch_norm=network.use_bn,
dr_rate=new_dr,
beta=network.beta,
eta=network.eta,
calculate_mmd=network.calculate_mmd,
mmd_boundary=network.mmd_boundary
)
# Expand First Layer weights of encoder/decoder of old network by new conditions
encoder_input_weights = network.encoder.FC.L0.cond_L.weight
to_be_added_encoder_input_weights = np.random.randn(encoder_input_weights.size()[0], n_new_conditions) * np.sqrt(
2 / (encoder_input_weights.size()[0] + 1 + encoder_input_weights.size()[1]))
to_be_added_encoder_input_weights = torch.from_numpy(to_be_added_encoder_input_weights).float().to(network.device)
new_encoder_input_weights = torch.cat((encoder_input_weights, to_be_added_encoder_input_weights), 1)
network.encoder.FC.L0.cond_L.weight.data = new_encoder_input_weights
decoder_input_weights = network.decoder.FirstL.L0.cond_L.weight
to_be_added_decoder_input_weights = np.random.randn(decoder_input_weights.size()[0], n_new_conditions) * np.sqrt(
2 / (decoder_input_weights.size()[0] + 1 + decoder_input_weights.size()[1]))
to_be_added_decoder_input_weights = torch.from_numpy(to_be_added_decoder_input_weights).float().to(network.device)
new_decoder_input_weights = torch.cat((decoder_input_weights, to_be_added_decoder_input_weights), 1)
network.decoder.FirstL.L0.cond_L.weight.data = new_decoder_input_weights
# Set the weights of new network to old network weights
new_network.load_state_dict(network.state_dict())
# Freeze parts of the network
if freeze:
new_network.freeze = True
for name, p in new_network.named_parameters():
p.requires_grad = False
if freeze_expression:
if 'cond_L.weight' in name:
p.requires_grad = True
else:
if "L0" in name or "B0" in name:
p.requires_grad = True
return new_network
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/surgery/trvae.py
| 0.899817 | 0.526647 |
trvae.py
|
pypi
|
import numpy as np
from typing import Union
import torch
import scanpy as sc
from scarchest.models import MARS
from scarchest.trainers import MARSTrainer
def mars_operate(network: MARS,
new_adata: sc.AnnData,
new_tasks: Union[list, str],
meta_tasks: list,
n_clusters: int,
task_key: str,
cell_type_key: str,
tau: float = 0.2,
eta: float = 1.0,
freeze: bool = True,
remove_dropout: bool = True,
) -> MARS:
"""Transfer Learning function for new data. Uses old trained Network and expands it for new conditions.
Parameters
----------
network: MARS
A MARS model object.
new_tasks: list_str
List of Strings of new Conditions.
freeze: Boolean
If 'True' freezes every part of the network except the first layers of encoder/decoder.
remove_dropout: Boolean
If 'True' remove Dropout for Transfer Learning.
Returns
-------
new_network: MARS
New expanded network with old weights for Transfer Learning.
"""
conditions = network.conditions
new_conditions = []
# Check if new conditions are already known
for item in new_tasks:
if item not in conditions:
new_conditions.append(item)
n_new_conditions = len(new_conditions)
# Add new conditions to overall conditions
for condition in new_conditions:
conditions.append(condition)
# Update DR Rate
new_dr = network.dropout_rate
if remove_dropout:
new_dr = 0.0
new_network = MARS(
x_dim=network.x_dim,
architecture=network.architecture,
z_dim=network.z_dim,
conditions=conditions,
alpha=network.alpha,
activation=network.activation,
output_activation=network.output_activation,
use_batchnorm=network.use_batchnorm,
dropout_rate=new_dr,
)
# Expand First Layer weights of encoder/decoder of old network by new conditions
encoder_input_weights = network.encoder[0].FC_0.weight
to_be_added_encoder_input_weights = np.random.randn(encoder_input_weights.size()[0], n_new_conditions) * np.sqrt(
2 / (encoder_input_weights.size()[0] + 1 + encoder_input_weights.size()[1]))
to_be_added_encoder_input_weights = torch.from_numpy(to_be_added_encoder_input_weights).float().to(network.device)
new_encoder_input_weights = torch.cat((encoder_input_weights, to_be_added_encoder_input_weights), 1)
network.encoder[0].FC_0.weight.data = new_encoder_input_weights
decoder_input_weights = network.decoder[0].FC_0.weight
to_be_added_decoder_input_weights = np.random.randn(decoder_input_weights.size()[0], n_new_conditions) * np.sqrt(
2 / (decoder_input_weights.size()[0] + 1 + decoder_input_weights.size()[1]))
to_be_added_decoder_input_weights = torch.from_numpy(to_be_added_decoder_input_weights).float().to(network.device)
new_decoder_input_weights = torch.cat((decoder_input_weights, to_be_added_decoder_input_weights), 1)
network.decoder[0].FC_0.weight.data = new_decoder_input_weights
# Set the weights of new network to old network weights
new_network.load_state_dict(network.state_dict())
# Freeze parts of the network
if freeze:
for name, p in new_network.named_parameters():
if "FC_0" not in name:
p.requires_grad = False
new_trainer = MARSTrainer(model=new_network,
adata=new_adata,
task_key=task_key,
meta_test_tasks=meta_tasks,
cell_type_key=cell_type_key,
n_clusters=n_clusters,
tau=tau,
eta=eta,
)
return new_network, new_trainer
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/surgery/mars.py
| 0.888475 | 0.432962 |
mars.py
|
pypi
|
import numpy as np
class EarlyStopping(object):
def __init__(self,
mode: str = 'min',
early_stopping_metric: str = 'val_loss',
save_best_state_metric: str = 'val_loss',
benchmark: bool = False,
threshold: int = 3,
patience: int = 50):
self.benchmark = benchmark
self.patience = patience
self.threshold = threshold
self.epoch = 0
self.wait = 0
self.mode = mode
self.save_best_state_metric = save_best_state_metric
self.early_stopping_metric = early_stopping_metric
self.current_performance = np.inf
self.best_performance = np.inf
self.best_performance_state = np.inf
if self.mode == "max":
self.best_performance *= -1
self.current_performance *= -1
if patience == 0:
self.is_better = lambda a, b: True
self.step = lambda a: False
def step(self, scalar):
self.epoch += 1
if self.benchmark or self.epoch < self.patience:
continue_training = True
elif self.wait >= self.patience:
continue_training = False
else:
# Shift
self.current_performance = scalar
improvement = 0
# Compute improvement
if self.mode == "max":
improvement = self.current_performance - self.best_performance
elif self.mode == "min":
improvement = self.best_performance - self.current_performance
# updating best performance
if improvement > 0:
self.best_performance = self.current_performance
if improvement < self.threshold:
self.wait += 1
else:
self.wait = 0
continue_training = True
if not continue_training:
print("\nStopping early: no improvement of more than " + str(self.threshold) +
" nats in " + str(self.patience) + " epochs")
print("If the early stopping criterion is too strong, "
"please instantiate it with different parameters in the train method.")
return continue_training
def update_state(self, scalar):
improved = ((self.mode == "max" and scalar - self.best_performance_state > 0) or
(self.mode == "min" and self.best_performance_state - scalar > 0))
if improved:
self.best_performance_state = scalar
return improved
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/utils/monitor.py
| 0.825449 | 0.201971 |
monitor.py
|
pypi
|
import numpy as np
from scipy.stats import itemfreq, entropy
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score, adjusted_rand_score, normalized_mutual_info_score
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import LabelEncoder
from scarchest.dataset.trvae.data_handling import remove_sparsity
def __entropy_from_indices(indices):
return entropy(np.array(itemfreq(indices)[:, 1].astype(np.int32)))
def entropy_batch_mixing(adata, label_key='batch',
n_neighbors=50, n_pools=50, n_samples_per_pool=100):
"""Computes Entory of Batch mixing metric for ``adata`` given the batch column name.
Parameters
----------
adata: :class:`~anndata.AnnData`
Annotated dataset.
label_key: str
Name of the column which contains information about different studies in ``adata.obs`` data frame.
n_neighbors: int
Number of nearest neighbors.
n_pools: int
Number of EBM computation which will be averaged.
n_samples_per_pool: int
Number of samples to be used in each pool of execution.
Returns
-------
score: float
EBM score. A float between zero and one.
"""
adata = remove_sparsity(adata)
neighbors = NearestNeighbors(n_neighbors=n_neighbors + 1).fit(adata.X)
indices = neighbors.kneighbors(adata.X, return_distance=False)[:, 1:]
batch_indices = np.vectorize(lambda i: adata.obs[label_key].values[i])(indices)
entropies = np.apply_along_axis(__entropy_from_indices, axis=1, arr=batch_indices)
# average n_pools entropy results where each result is an average of n_samples_per_pool random samples.
if n_pools == 1:
score = np.mean(entropies)
else:
score = np.mean([
np.mean(entropies[np.random.choice(len(entropies), size=n_samples_per_pool)])
for _ in range(n_pools)
])
return score
def asw(adata, label_key):
"""Computes Average Silhouette Width (ASW) metric for ``adata`` given the batch column name.
Parameters
----------
adata: :class:`~anndata.AnnData`
Annotated dataset.
label_key: str
Name of the column which contains information about different studies in ``adata.obs`` data frame.
Returns
-------
score: float
ASW score. A float between -1 and 1.
"""
adata = remove_sparsity(adata)
labels = adata.obs[label_key].values
labels_encoded = LabelEncoder().fit_transform(labels)
return silhouette_score(adata.X, labels_encoded)
def ari(adata, label_key):
"""Computes Adjusted Rand Index (ARI) metric for ``adata`` given the batch column name.
Parameters
----------
adata: :class:`~anndata.AnnData`
Annotated dataset.
label_key: str
Name of the column which contains information about different studies in ``adata.obs`` data frame.
Returns
-------
score: float
ARI score. A float between 0 and 1.
"""
adata = remove_sparsity(adata)
n_labels = len(adata.obs[label_key].unique().tolist())
kmeans = KMeans(n_labels, n_init=200)
labels_pred = kmeans.fit_predict(adata.X)
labels = adata.obs[label_key].values
labels_encoded = LabelEncoder().fit_transform(labels)
return adjusted_rand_score(labels_encoded, labels_pred)
def nmi(adata, label_key):
"""Computes Normalized Mutual Information (NMI) metric for ``adata`` given the batch column name.
Parameters
----------
adata: :class:`~anndata.AnnData`
Annotated dataset.
label_key: str
Name of the column which contains information about different studies in ``adata.obs`` data frame.
Returns
-------
score: float
NMI score. A float between 0 and 1.
"""
adata = remove_sparsity(adata)
n_labels = len(adata.obs[label_key].unique().tolist())
kmeans = KMeans(n_labels, n_init=200)
labels_pred = kmeans.fit_predict(adata.X)
labels = adata.obs[label_key].values
labels_encoded = LabelEncoder().fit_transform(labels)
return normalized_mutual_info_score(labels_encoded, labels_pred)
def knn_purity(adata, label_key, n_neighbors=30):
"""Computes KNN Purity metric for ``adata`` given the batch column name.
Parameters
----------
adata: :class:`~anndata.AnnData`
Annotated dataset.
label_key: str
Name of the column which contains information about different studies in ``adata.obs`` data frame.
n_neighbors: int
Number of nearest neighbors.
Returns
-------
score: float
KNN purity score. A float between 0 and 1.
"""
adata = remove_sparsity(adata)
labels = LabelEncoder().fit_transform(adata.obs[label_key].to_numpy())
nbrs = NearestNeighbors(n_neighbors=n_neighbors + 1).fit(adata.X)
indices = nbrs.kneighbors(adata.X, return_distance=False)[:, 1:]
neighbors_labels = np.vectorize(lambda i: labels[i])(indices)
# pre cell purity scores
scores = ((neighbors_labels - labels.reshape(-1, 1)) == 0).mean(axis=1)
res = [
np.mean(scores[labels == i]) for i in np.unique(labels)
] # per cell-type purity
return np.mean(res)
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/metrics/metrics.py
| 0.939401 | 0.779028 |
metrics.py
|
pypi
|
from scvi.data import get_from_registry
from scarchest.metrics.metrics import entropy_batch_mixing, knn_purity
from scarchest.models import scVI, scANVI
from scarchest.trainers import scVITrainer, scANVITrainer
import numpy as np
import scanpy as sc
import torch
from typing import Union
import anndata
import matplotlib.pyplot as plt
sc.settings.set_figure_params(dpi=100, frameon=False)
sc.set_figure_params(dpi=100)
torch.set_printoptions(precision=3, sci_mode=False, edgeitems=7)
np.set_printoptions(precision=2, edgeitems=7)
class SCVI_EVAL:
def __init__(
self,
model: Union[scVI, scANVI],
trainer: Union[scVITrainer, scANVITrainer],
adata: anndata.AnnData,
cell_type_key: str,
batch_key: str,
):
self.model = model
self.trainer = trainer
self.adata = adata
self.modified = model.modified
self.annotated = type(model) is scANVI
self.post_adata_2 = None
self.predictions = None
if self.trainer.use_cuda:
self.device = torch.device('cuda')
else:
self.device = torch.device('cpu')
self.x_tensor = torch.tensor(self.adata.X, device=self.device)
self.labels = get_from_registry(self.adata, "labels").astype(np.int8)
self.label_tensor = torch.tensor(self.labels, device=self.device)
self.cell_types = self.adata.obs[cell_type_key].tolist()
self.batch_indices = get_from_registry(self.adata, "batch_indices").astype(np.int8)
self.batch_tensor = torch.tensor(self.batch_indices, device=self.device)
self.batch_names = self.adata.obs[batch_key].tolist()
self.post_adata = self.latent_as_anndata()
def latent_as_anndata(self):
if self.modified:
latents = self.model.get_latents(
self.x_tensor,
y=self.label_tensor,
batch_index=self.batch_tensor
)
else:
latents = self.model.get_latents(
self.x_tensor,
y=self.label_tensor,
)
if self.annotated:
latent = latents[0].cpu().detach().numpy()
latent2 = latents[1].cpu().detach().numpy()
post_adata_2 = sc.AnnData(latent2)
post_adata_2.obs['cell_type'] = self.cell_types
post_adata_2.obs['batch'] = self.batch_names
self.post_adata_2 = post_adata_2
else:
latent = latents[0].cpu().detach().numpy()
post_adata = sc.AnnData(latent)
post_adata.obs['cell_type'] = self.cell_types
post_adata.obs['batch'] = self.batch_names
return post_adata
def get_model_arch(self):
for name, p in self.model.named_parameters():
print(name, " - ", p.size(0), p.size(-1))
def plot_latent(self, n_neighbors=8):
sc.pp.neighbors(self.post_adata, n_neighbors=n_neighbors)
sc.tl.umap(self.post_adata)
sc.pl.umap(self.post_adata, color=['cell_type', 'batch'], frameon=False, wspace=0.6)
def plot_latent_ann(self, n_neighbors=8):
if self.annotated:
sc.pp.neighbors(self.post_adata_2, n_neighbors=n_neighbors)
sc.tl.umap(self.post_adata_2)
sc.pl.umap(self.post_adata_2, color=['cell_type', 'batch'], frameon=False, wspace=0.6)
else:
print("Second latent space not available for scVI models")
def plot_history(self, n_epochs):
if self.annotated:
elbo_full = self.trainer.history["elbo_full_dataset"]
x_1 = np.linspace(0, len(elbo_full), len(elbo_full))
fig, axs = plt.subplots(2, 1)
axs[0].plot(x_1, elbo_full, label="Full")
accuracy_labelled_set = self.trainer.history["accuracy_labelled_set"]
accuracy_unlabelled_set = self.trainer.history["accuracy_unlabelled_set"]
if len(accuracy_labelled_set) != 0:
x_2 = np.linspace(0, len(accuracy_labelled_set), (len(accuracy_labelled_set)))
axs[1].plot(x_2, accuracy_labelled_set, label="accuracy labelled")
if len(accuracy_unlabelled_set) != 0:
x_3 = np.linspace(0, len(accuracy_unlabelled_set), (len(accuracy_unlabelled_set)))
axs[1].plot(x_3, accuracy_unlabelled_set, label="accuracy unlabelled")
axs[0].set_xlabel('Epochs')
axs[0].set_ylabel('ELBO')
axs[1].set_xlabel('Epochs')
axs[1].set_ylabel('Accuracy')
plt.legend()
plt.show()
else:
elbo_train = self.trainer.history["elbo_train_set"]
elbo_test = self.trainer.history["elbo_test_set"]
x = np.linspace(0, len(elbo_train), len(elbo_train))
plt.plot(x, elbo_train, label="train")
plt.plot(x, elbo_test, label="test")
plt.ylim(min(elbo_train) - 50, min(elbo_train) + 1000)
plt.legend()
plt.show()
def get_ebm(self, n_neighbors=50, n_pools=50, n_samples_per_pool=100, verbose=True):
ebm_score = entropy_batch_mixing(
adata=self.post_adata,
label_key='batch',
n_neighbors=n_neighbors,
n_pools=n_pools,
n_samples_per_pool=n_samples_per_pool
)
if verbose:
print("Entropy of Batchmixing-Score:", ebm_score)
return ebm_score
def get_knn_purity(self, n_neighbors=50, verbose=True):
knn_score = knn_purity(
adata=self.post_adata,
label_key='cell_type',
n_neighbors=n_neighbors
)
if verbose:
print("KNN Purity-Score:", knn_score)
return knn_score
def get_latent_score(self):
ebm = self.get_ebm(verbose=False)
knn = self.get_knn_purity(verbose=False)
score = ebm + knn
print("Latent-Space Score (KNN + EBM):", score)
return score
def get_classification_accuracy(self):
if self.annotated:
if self.modified:
predictions = self.model.classify(self.x_tensor, batch_index=self.batch_tensor)
else:
predictions = self.model.classify(self.x_tensor)
self.predictions = predictions.cpu().detach().numpy()
self.predictions = np.argmax(self.predictions, axis=1)
class_check = np.array(np.expand_dims(self.predictions, axis=1) == self.labels)
accuracy = np.sum(class_check) / class_check.shape[0]
print("Classification Accuracy: %0.2f" % accuracy)
return accuracy
else:
print("Classification ratio not available for scVI models")
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/plotting/scvi_eval.py
| 0.814791 | 0.278508 |
scvi_eval.py
|
pypi
|
import numpy as np
import logging
import torch
from torch.nn import functional as F
from scvi.data._anndata import get_from_registry
from scvi import _CONSTANTS
from scarchest.trainers.scvi import Trainer, scVITrainer
from scarchest.dataset.scvi import AnnotationDataLoader
logger = logging.getLogger(__name__)
class ClassifierTrainer(Trainer):
"""Class for training a classifier either on the raw data or on top of the latent space of another model.
Parameters
----------
model
A model instance from class ``VAE``, ``VAEC``, ``SCANVI``
gene_dataset
A gene_dataset instance like ``CortexDataset()``
train_size
The train size, a float between 0 and 1 representing proportion of dataset to use for training
to use Default: ``0.9``.
test_size
The test size, a float between 0 and 1 representing proportion of dataset to use for testing
to use Default: ``None``.
sampling_model
Model with z_encoder with which to first transform data.
sampling_zl
Transform data with sampling_model z_encoder and l_encoder and concat.
**kwargs
Other keywords arguments from the general Trainer class.
Examples
--------
>>> gene_dataset = CortexDataset()
>>> vae = VAE(gene_dataset.nb_genes, n_batch=gene_dataset.n_batches * False,
... n_labels=gene_dataset.n_labels)
>>> classifier = Classifier(vae.n_latent, n_labels=cortex_dataset.n_labels)
>>> trainer = ClassifierTrainer(classifier, gene_dataset, sampling_model=vae, train_size=0.5)
>>> trainer.train(n_epochs=20, lr=1e-3)
>>> trainer.test_set.accuracy()
"""
def __init__(
self,
*args,
train_size=0.9,
test_size=None,
sampling_model=None,
sampling_zl=False,
use_cuda=True,
**kwargs
):
train_size = float(train_size)
if train_size > 1.0 or train_size <= 0.0:
raise ValueError(
"train_size needs to be greater than 0 and less than or equal to 1"
)
self.sampling_model = sampling_model
self.sampling_zl = sampling_zl
super().__init__(*args, use_cuda=use_cuda, **kwargs)
self.train_set, self.test_set, self.validation_set = self.train_test_validation(
self.model,
self.adata,
train_size=train_size,
test_size=test_size,
type_class=AnnotationDataLoader,
)
self.train_set.to_monitor = ["accuracy"]
self.test_set.to_monitor = ["accuracy"]
self.validation_set.to_monitor = ["accuracy"]
self.train_set.model_zl = sampling_zl
self.test_set.model_zl = sampling_zl
self.validation_set.model_zl = sampling_zl
@property
def scvi_data_loaders_loop(self):
return ["train_set"]
def __setattr__(self, key, value):
if key in ["train_set", "test_set"]:
value.sampling_model = self.sampling_model
super().__setattr__(key, value)
def loss(self, tensors_labelled):
x = tensors_labelled[_CONSTANTS.X_KEY]
labels_train = tensors_labelled[_CONSTANTS.LABELS_KEY]
if hasattr(self.sampling_model, "classify"):
if self.sampling_model.modified:
batch_index = tensors_labelled[_CONSTANTS.BATCH_KEY]
return F.cross_entropy(
self.sampling_model.classify(x, batch_index), labels_train.view(-1)
)
return F.cross_entropy(
self.sampling_model.classify(x), labels_train.view(-1)
)
else:
if self.sampling_model.log_variational:
x = torch.log(1 + x)
if self.sampling_zl:
if self.sampling_model.modified:
batch_index = tensors_labelled[_CONSTANTS.BATCH_KEY]
x_z = self.sampling_model.z_encoder(x, batch_index)[0]
x_l = self.sampling_model.l_encoder(x, batch_index)[0]
else:
x_z = self.sampling_model.z_encoder(x)[0]
x_l = self.sampling_model.l_encoder(x)[0]
x = torch.cat((x_z, x_l), dim=-1)
else:
if self.sampling_model.modified:
batch_index = tensors_labelled[_CONSTANTS.BATCH_KEY]
x = self.sampling_model.z_encoder(x, batch_index)[0]
else:
x = self.sampling_model.z_encoder(x)[0]
return F.cross_entropy(self.model(x), labels_train.view(-1))
def create_scvi_dl(
self,
model=None,
adata=None,
shuffle=False,
indices=None,
type_class=AnnotationDataLoader,
):
return super().create_scvi_dl(model, adata, shuffle, indices, type_class)
class scANVITrainer(scVITrainer):
"""Class for the semi-supervised training of an autoencoder.
This parent class can be inherited to specify the different training schemes for semi-supervised learning
Parameters
----------
n_labelled_samples_per_class
number of labelled samples per class
"""
def __init__(
self,
model,
adata,
n_labelled_samples_per_class=50,
n_epochs_classifier=1,
lr_classification=5 * 1e-3,
classification_ratio=50,
seed=0,
**kwargs
):
super().__init__(model, adata, **kwargs)
self.model = model
self.adata = adata
self.n_epochs_classifier = n_epochs_classifier
self.lr_classification = lr_classification
self.classification_ratio = classification_ratio
n_labelled_samples_per_class_array = [
n_labelled_samples_per_class
] * self.adata.uns["_scvi"]["summary_stats"]["n_labels"]
labels = np.array(get_from_registry(self.adata, _CONSTANTS.LABELS_KEY)).ravel()
np.random.seed(seed=seed)
permutation_idx = np.random.permutation(len(labels))
labels = labels[permutation_idx]
indices = []
current_nbrs = np.zeros(len(n_labelled_samples_per_class_array))
for idx, (label) in enumerate(labels):
label = int(label)
if current_nbrs[label] < n_labelled_samples_per_class_array[label]:
indices.insert(0, idx)
current_nbrs[label] += 1
else:
indices.append(idx)
indices = np.array(indices)
total_labelled = sum(n_labelled_samples_per_class_array)
indices_labelled = permutation_idx[indices[:total_labelled]]
indices_unlabelled = permutation_idx[indices[total_labelled:]]
self.classifier_trainer = ClassifierTrainer(
model.classifier,
self.adata,
metrics_to_monitor=[],
silent=True,
frequency=0,
sampling_model=self.model,
)
self.full_dataset = self.create_scvi_dl(shuffle=True)
self.labelled_set = self.create_scvi_dl(indices=indices_labelled)
self.unlabelled_set = self.create_scvi_dl(indices=indices_unlabelled)
for scdl in [self.labelled_set, self.unlabelled_set]:
scdl.to_monitor = ["reconstruction_error", "accuracy"]
@property
def scvi_data_loaders_loop(self):
return ["full_dataset", "labelled_set"]
def __setattr__(self, key, value):
if key == "labelled_set":
self.classifier_trainer.train_set = value
super().__setattr__(key, value)
def loss(self, tensors_all, tensors_labelled):
loss = super().loss(tensors_all, feed_labels=False)
sample_batch = tensors_labelled[_CONSTANTS.X_KEY]
y = tensors_labelled[_CONSTANTS.LABELS_KEY]
if self.model.modified:
batch_index = tensors_labelled[_CONSTANTS.BATCH_KEY]
classification_loss = F.cross_entropy(
self.model.classify(sample_batch, batch_index), y.view(-1)
)
else:
classification_loss = F.cross_entropy(
self.model.classify(sample_batch), y.view(-1)
)
loss += classification_loss * self.classification_ratio
return loss
def on_epoch_end(self):
self.model.eval()
self.classifier_trainer.train(
self.n_epochs_classifier, lr=self.lr_classification
)
self.model.train()
return super().on_epoch_end()
def create_scvi_dl(
self,
model=None,
adata=None,
shuffle=False,
indices=None,
type_class=AnnotationDataLoader,
):
return super().create_scvi_dl(model, adata, shuffle, indices, type_class)
class UnlabelledScanviTrainer(scANVITrainer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def loss(self, all_tensor):
return scVITrainer.loss(self, all_tensor, feed_labels=False)
@property
def scvi_data_loaders_loop(self):
return ["full_dataset"]
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/trainers/scvi/annotation.py
| 0.901531 | 0.458955 |
annotation.py
|
pypi
|
from typing import Union
import anndata
import logging
import torch
from scvi import _CONSTANTS
from scvi.core.modules import Classifier
from scvi.core.modules.utils import one_hot
from scarchest.models.scvi import totalVI
from scarchest.trainers.scvi import scVITrainer
from scarchest.dataset.scvi import TotalDataLoader
logger = logging.getLogger(__name__)
default_early_stopping_kwargs = {
"early_stopping_metric": "elbo",
"save_best_state_metric": "elbo",
"patience": 45,
"threshold": 0,
"reduce_lr_on_plateau": True,
"lr_patience": 30,
"lr_factor": 0.6,
"scvi_data_loader_class": TotalDataLoader,
}
def _unpack_tensors(tensors):
x = tensors[_CONSTANTS.X_KEY]
local_l_mean = tensors[_CONSTANTS.LOCAL_L_MEAN_KEY]
local_l_var = tensors[_CONSTANTS.LOCAL_L_VAR_KEY]
batch_index = tensors[_CONSTANTS.BATCH_KEY]
labels = tensors[_CONSTANTS.LABELS_KEY]
y = tensors[_CONSTANTS.PROTEIN_EXP_KEY]
return x, local_l_mean, local_l_var, batch_index, labels, y
class totalTrainer(scVITrainer):
"""
Unsupervised training for totalVI using variational inference.
Parameters
----------
model
A model instance from class ``TOTALVAE``
adata
A registered AnnData object
train_size
The train size, a float between 0 and 1 representing proportion of dataset to use for training
to use Default: ``0.90``.
test_size
The test size, a float between 0 and 1 representing proportion of dataset to use for testing
to use Default: ``0.10``. Note that if train and test do not add to 1 the remainder is placed in a validation set
pro_recons_weight
Scaling factor on the reconstruction loss for proteins. Default: ``1.0``.
n_epochs_kl_warmup
Number of epochs for annealing the KL terms for `z` and `mu` of the ELBO (from 0 to 1). If None, no warmup performed, unless
`n_iter_kl_warmup` is set.
n_iter_kl_warmup
Number of minibatches for annealing the KL terms for `z` and `mu` of the ELBO (from 0 to 1). If set to "auto", the number
of iterations is equal to 75% of the number of cells. `n_epochs_kl_warmup` takes precedence if it is not None. If both are None, then
no warmup is performed.
discriminator
Classifier used for adversarial training scheme
use_adversarial_loss
Whether to use adversarial classifier to improve mixing
kappa
Scaling factor for adversarial loss. If None, follow inverse of kl warmup schedule.
early_stopping_kwargs
Keyword args for early stopping. If "auto", use totalVI defaults. If None, disable early stopping.
"""
default_metrics_to_monitor = ["elbo"]
def __init__(
self,
model: totalVI,
dataset: anndata.AnnData,
train_size: float = 0.90,
test_size: float = 0.10,
pro_recons_weight: float = 1.0,
n_epochs_kl_warmup: int = None,
n_iter_kl_warmup: Union[str, int] = "auto",
discriminator: Classifier = None,
use_adversarial_loss: bool = False,
kappa: float = None,
early_stopping_kwargs: Union[dict, str, None] = "auto",
**kwargs,
):
train_size = float(train_size)
if train_size > 1.0 or train_size <= 0.0:
raise ValueError(
"train_size needs to be greater than 0 and less than or equal to 1"
)
self.n_genes = model.n_input_genes
self.n_proteins = model.n_input_proteins
self.use_adversarial_loss = use_adversarial_loss
self.kappa = kappa
self.pro_recons_weight = pro_recons_weight
if early_stopping_kwargs == "auto":
early_stopping_kwargs = default_early_stopping_kwargs
super().__init__(
model,
dataset,
n_epochs_kl_warmup=n_epochs_kl_warmup,
n_iter_kl_warmup=0.75 * len(dataset)
if n_iter_kl_warmup == "auto"
else n_iter_kl_warmup,
early_stopping_kwargs=early_stopping_kwargs,
**kwargs,
)
if use_adversarial_loss is True and discriminator is None:
discriminator = Classifier(
n_input=self.model.n_latent,
n_hidden=32,
n_labels=self.adata.uns["_scvi"]["summary_stats"]["n_batch"],
n_layers=2,
logits=True,
)
self.discriminator = discriminator
if self.use_cuda and self.discriminator is not None:
self.discriminator.cuda()
if isinstance(self, totalTrainer):
(
self.train_set,
self.test_set,
self.validation_set,
) = self.train_test_validation(
model, dataset, train_size, test_size, type_class=TotalDataLoader
)
self.train_set.to_monitor = []
self.test_set.to_monitor = ["elbo"]
self.validation_set.to_monitor = ["elbo"]
def loss(self, tensors):
(
sample_batch_x,
local_l_mean,
local_l_var,
batch_index,
label,
sample_batch_y,
) = _unpack_tensors(tensors)
(
reconst_loss_gene,
reconst_loss_protein,
kl_div_z,
kl_div_l_gene,
kl_div_back_pro,
) = self.model(
sample_batch_x,
sample_batch_y,
local_l_mean,
local_l_var,
batch_index,
label,
)
loss = torch.mean(
reconst_loss_gene
+ self.pro_recons_weight * reconst_loss_protein
+ self.kl_weight * kl_div_z
+ kl_div_l_gene
+ self.kl_weight * kl_div_back_pro
)
return loss
def loss_discriminator(
self, z, batch_index, predict_true_class=True, return_details=True
):
n_classes = self.adata.uns["_scvi"]["summary_stats"]["n_batch"]
cls_logits = torch.nn.LogSoftmax(dim=1)(self.discriminator(z))
if predict_true_class:
cls_target = one_hot(batch_index, n_classes)
else:
one_hot_batch = one_hot(batch_index, n_classes)
cls_target = torch.zeros_like(one_hot_batch)
# place zeroes where true label is
cls_target.masked_scatter_(
~one_hot_batch.bool(), torch.ones_like(one_hot_batch) / (n_classes - 1)
)
l_soft = cls_logits * cls_target
loss = -l_soft.sum(dim=1).mean()
return loss
def _get_z(self, tensors):
(
sample_batch_x,
local_l_mean,
local_l_var,
batch_index,
label,
sample_batch_y,
) = _unpack_tensors(tensors)
z = self.model.sample_from_posterior_z(
sample_batch_x, sample_batch_y, batch_index, give_mean=False
)
return z
def train(self, n_epochs=500, lr=4e-3, eps=0.01, params=None):
super().train(n_epochs=n_epochs, lr=lr, eps=eps, params=params)
def on_training_loop(self, tensors_dict):
if self.use_adversarial_loss:
if self.kappa is None:
kappa = 1 - self.kl_weight
else:
kappa = self.kappa
batch_index = tensors_dict[0][_CONSTANTS.BATCH_KEY]
if kappa > 0:
z = self._get_z(*tensors_dict)
# Train discriminator
d_loss = self.loss_discriminator(z.detach(), batch_index, True)
d_loss *= kappa
self.d_optimizer.zero_grad()
d_loss.backward()
self.d_optimizer.step()
# Train generative model to fool discriminator
fool_loss = self.loss_discriminator(z, batch_index, False)
fool_loss *= kappa
# Train generative model
self.optimizer.zero_grad()
self.current_loss = loss = self.loss(*tensors_dict)
if kappa > 0:
(loss + fool_loss).backward()
else:
loss.backward()
self.optimizer.step()
else:
self.current_loss = loss = self.loss(*tensors_dict)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
def training_extras_init(self, lr_d=1e-3, eps=0.01):
if self.discriminator is not None:
self.discriminator.train()
d_params = filter(
lambda p: p.requires_grad, self.discriminator.parameters()
)
self.d_optimizer = torch.optim.Adam(d_params, lr=lr_d, eps=eps)
def training_extras_end(self):
if self.discriminator is not None:
self.discriminator.eval()
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/trainers/scvi/total_inference.py
| 0.934947 | 0.289862 |
total_inference.py
|
pypi
|
import logging
import time
import numpy as np
import torch
import torch.nn as nn
import anndata
from abc import abstractmethod
from collections import defaultdict, OrderedDict
from itertools import cycle
from typing import List
from sklearn.model_selection._split import _validate_shuffle_split
from torch.utils.data.sampler import SubsetRandomSampler
from scvi._utils import track
from scvi import _CONSTANTS
from scarchest.dataset.scvi import ScviDataLoader
logger = logging.getLogger(__name__)
class Trainer:
"""The abstract Trainer class for training a PyTorch model and monitoring its statistics.
It should be inherited at least with a ``.loss()`` function to be optimized in the training loop.
Parameters
----------
model :
A model instance from class ``VAE``, ``VAEC``, ``SCANVI``
adata:
A registered anndata object
use_cuda :
Default: ``True``.
metrics_to_monitor :
A list of the metrics to monitor. If not specified, will use the
``default_metrics_to_monitor`` as specified in each . Default: ``None``.
benchmark :
if True, prevents statistics computation in the training. Default: ``False``.
frequency :
The frequency at which to keep track of statistics. Default: ``None``.
early_stopping_metric :
The statistics on which to perform early stopping. Default: ``None``.
save_best_state_metric :
The statistics on which we keep the network weights achieving the best store, and
restore them at the end of training. Default: ``None``.
on :
The data_loader name reference for the ``early_stopping_metric`` and ``save_best_state_metric``, that
should be specified if any of them is. Default: ``None``.
show_progbar :
If False, disables progress bar.
seed :
Random seed for train/test/validate split
Returns
-------
"""
default_metrics_to_monitor = []
def __init__(
self,
model,
adata: anndata.AnnData,
use_cuda: bool = True,
metrics_to_monitor: List = None,
benchmark: bool = False,
frequency: int = None,
weight_decay: float = 1e-6,
early_stopping_kwargs: dict = None,
data_loader_kwargs: dict = None,
silent: bool = False,
batch_size: int = 128,
seed: int = 0,
max_nans: int = 10,
):
# Model, dataset management
self.model = model
self.adata = adata
self._scvi_data_loaders = OrderedDict()
self.seed = seed # For train/test splitting
self.use_cuda = use_cuda and torch.cuda.is_available()
if self.use_cuda:
self.model.cuda()
# Data loader attributes
self.batch_size = batch_size
self.data_loader_kwargs = {"pin_memory": use_cuda}
data_loader_kwargs = data_loader_kwargs if data_loader_kwargs else dict()
self.data_loader_kwargs.update(data_loader_kwargs)
# Optimization attributes
self.optimizer = None
self.weight_decay = weight_decay
self.n_epochs = None
self.epoch = -1 # epoch = self.epoch + 1 in compute metrics
self.training_time = 0
self.n_iter = 0
# Training NaNs handling
self.max_nans = max_nans
self.current_loss = None # torch.Tensor training loss
self.previous_loss_was_nan = False
self.nan_counter = 0 # Counts occuring NaNs during training
# Metrics and early stopping
self.compute_metrics_time = None
if metrics_to_monitor is not None:
self.metrics_to_monitor = set(metrics_to_monitor)
else:
self.metrics_to_monitor = set(self.default_metrics_to_monitor)
early_stopping_kwargs = (
early_stopping_kwargs if early_stopping_kwargs else dict()
)
self.early_stopping = EarlyStopping(**early_stopping_kwargs)
self.benchmark = benchmark
self.frequency = frequency if not benchmark else None
self.history = defaultdict(list)
self.best_state_dict = self.model.state_dict()
self.best_epoch = self.epoch
if self.early_stopping.early_stopping_metric:
self.metrics_to_monitor.add(self.early_stopping.early_stopping_metric)
self.silent = silent
@torch.no_grad()
def compute_metrics(self):
begin = time.time()
epoch = self.epoch + 1
if self.frequency and (
epoch == 0 or epoch == self.n_epochs or (epoch % self.frequency == 0)
):
with torch.set_grad_enabled(False):
self.model.eval()
logger.debug("\nEPOCH [%d/%d]: " % (epoch, self.n_epochs))
for name, scdl in self._scvi_data_loaders.items():
message = " ".join([s.capitalize() for s in name.split("_")[-2:]])
if scdl.n_cells < 5:
logging.debug(
message + " is too small to track metrics (<5 samples)"
)
continue
if hasattr(scdl, "to_monitor"):
for metric in scdl.to_monitor:
if metric not in self.metrics_to_monitor:
logger.debug(message)
result = getattr(scdl, metric)()
self.history[metric + "_" + name] += [result]
for metric in self.metrics_to_monitor:
result = getattr(scdl, metric)()
self.history[metric + "_" + name] += [result]
self.model.train()
self.compute_metrics_time += time.time() - begin
def train(self, n_epochs=400, lr=1e-3, eps=0.01, params=None, **extras_kwargs):
begin = time.time()
self.model.train()
if params is None:
params = filter(lambda p: p.requires_grad, self.model.parameters())
if len(list(params)) == 0:
return
else:
params = filter(lambda p: p.requires_grad, self.model.parameters())
self.optimizer = torch.optim.Adam(
params, lr=lr, eps=eps, weight_decay=self.weight_decay
)
# Initialization of other model's optimizers
self.training_extras_init(**extras_kwargs)
self.compute_metrics_time = 0
self.n_epochs = n_epochs
self.compute_metrics()
self.on_training_begin()
for self.epoch in track(
range(n_epochs), description="Training...", disable=self.silent
):
self.on_epoch_begin()
for tensors_dict in self.data_loaders_loop():
if tensors_dict[0][_CONSTANTS.X_KEY].shape[0] < 3:
continue
self.on_iteration_begin()
# Update the model's parameters after seeing the data
self.on_training_loop(tensors_dict)
# Checks the training status, ensures no nan loss
self.on_iteration_end()
# Computes metrics and controls early stopping
if not self.on_epoch_end():
break
if self.early_stopping.save_best_state_metric is not None:
self.model.load_state_dict(self.best_state_dict)
self.compute_metrics()
self.model.eval()
self.training_extras_end()
self.training_time += (time.time() - begin) - self.compute_metrics_time
self.on_training_end()
def on_training_loop(self, tensors_dict):
if self.model.freeze:
for name, module in self.model.named_modules():
if isinstance(module, nn.BatchNorm1d):
if not module.weight.requires_grad:
module.affine = False
module.track_running_stats = False
self.current_loss = loss = self.loss(*tensors_dict)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
def training_extras_init(self, **extras_kwargs):
"""Other necessary models to simultaneously train."""
pass
def training_extras_end(self):
"""Place to put extra models in eval mode, etc."""
pass
def on_training_begin(self):
pass
def on_epoch_begin(self):
# Epochs refer to a pass through the entire dataset (in minibatches)
pass
def on_epoch_end(self):
self.compute_metrics()
on = self.early_stopping.on
early_stopping_metric = self.early_stopping.early_stopping_metric
save_best_state_metric = self.early_stopping.save_best_state_metric
if save_best_state_metric is not None and on is not None:
if self.early_stopping.update_state(
self.history[save_best_state_metric + "_" + on][-1]
):
self.best_state_dict = self.model.state_dict()
self.best_epoch = self.epoch
continue_training = True
if early_stopping_metric is not None and on is not None:
continue_training, reduce_lr = self.early_stopping.update(
self.history[early_stopping_metric + "_" + on][-1]
)
if reduce_lr:
logger.info("Reducing LR on epoch {}.".format(self.epoch))
for param_group in self.optimizer.param_groups:
param_group["lr"] *= self.early_stopping.lr_factor
return continue_training
def on_iteration_begin(self):
# Iterations refer to minibatches
pass
def on_iteration_end(self):
self.check_training_status()
self.n_iter += 1
def on_training_end(self):
pass
def check_training_status(self):
"""
Checks if loss is admissible.
If not, training is stopped after max_nans consecutive inadmissible loss
loss corresponds to the training loss of the model.
`max_nans` is the maximum number of consecutive NaNs after which a ValueError will be
"""
loss_is_nan = torch.isnan(self.current_loss).item()
if loss_is_nan:
logger.warning("Model training loss was NaN")
self.nan_counter += 1
self.previous_loss_was_nan = True
else:
self.nan_counter = 0
self.previous_loss_was_nan = False
if self.nan_counter >= self.max_nans:
raise ValueError(
"Loss was NaN {} consecutive times: the model is not training properly. "
"Consider using a lower learning rate.".format(self.max_nans)
)
@property
@abstractmethod
def scvi_data_loaders_loop(self):
pass
def data_loaders_loop(self):
"""Returns an zipped iterable corresponding to loss signature."""
data_loaders_loop = [
self._scvi_data_loaders[name] for name in self.scvi_data_loaders_loop
]
return zip(
data_loaders_loop[0],
*[cycle(data_loader) for data_loader in data_loaders_loop[1:]]
)
def register_data_loader(self, name, value):
name = name.strip("_")
self._scvi_data_loaders[name] = value
def __getattr__(self, name):
if "_scvi_data_loaders" in self.__dict__:
_scvi_data_loaders = self.__dict__["_scvi_data_loaders"]
if name.strip("_") in _scvi_data_loaders:
return _scvi_data_loaders[name.strip("_")]
return object.__getattribute__(self, name)
def __delattr__(self, name):
if name.strip("_") in self._scvi_data_loaders:
del self._scvi_data_loaders[name.strip("_")]
else:
object.__delattr__(self, name)
def __setattr__(self, name, value):
if isinstance(value, ScviDataLoader):
name = name.strip("_")
self.register_data_loader(name, value)
else:
object.__setattr__(self, name, value)
def train_test_validation(
self,
model=None,
adata=None,
train_size=0.9,
test_size=None,
type_class=ScviDataLoader,
):
"""
Creates data loaders ``train_set``, ``test_set``, ``validation_set``.
If ``train_size + test_size < 1`` then ``validation_set`` is non-empty.
Parameters
----------
train_size :
float, or None (default is 0.9)
test_size :
float, or None (default is None)
model :
(Default value = None)
adata:
(Default value = None)
type_class :
(Default value = ScviDataLoader)
"""
train_size = float(train_size)
if train_size > 1.0 or train_size <= 0.0:
raise ValueError(
"train_size needs to be greater than 0 and less than or equal to 1"
)
model = self.model if model is None and hasattr(self, "model") else model
# what to do here if it has the attribute modle
adata = self.adata if adata is None and hasattr(self, "model") else adata
n = len(adata)
try:
n_train, n_test = _validate_shuffle_split(n, test_size, train_size)
except ValueError:
if train_size != 1.0:
raise ValueError(
"Choice of train_size={} and test_size={} not understood".format(
train_size, test_size
)
)
n_train, n_test = n, 0
random_state = np.random.RandomState(seed=self.seed)
permutation = random_state.permutation(n)
indices_test = permutation[:n_test]
indices_train = permutation[n_test: (n_test + n_train)]
indices_validation = permutation[(n_test + n_train):]
return (
self.create_scvi_dl(
model, adata, indices=indices_train, type_class=type_class
),
self.create_scvi_dl(
model, adata, indices=indices_test, type_class=type_class
),
self.create_scvi_dl(
model, adata, indices=indices_validation, type_class=type_class
),
)
def create_scvi_dl(
self,
model=None,
adata: anndata.AnnData = None,
shuffle=False,
indices=None,
type_class=ScviDataLoader,
):
model = self.model if model is None and hasattr(self, "model") else model
adata = self.adata if adata is None and hasattr(self, "model") else adata
return type_class(
model,
adata,
shuffle=shuffle,
indices=indices,
use_cuda=self.use_cuda,
batch_size=self.batch_size,
data_loader_kwargs=self.data_loader_kwargs,
)
class SequentialSubsetSampler(SubsetRandomSampler):
def __init__(self, indices):
self.indices = np.sort(indices)
def __iter__(self):
return iter(self.indices)
class EarlyStopping:
def __init__(
self,
early_stopping_metric: str = None,
save_best_state_metric: str = None,
on: str = "test_set",
patience: int = 15,
threshold: int = 3,
benchmark: bool = False,
reduce_lr_on_plateau: bool = False,
lr_patience: int = 10,
lr_factor: float = 0.5,
scvi_data_loader_class=ScviDataLoader,
):
self.benchmark = benchmark
self.patience = patience
self.threshold = threshold
self.epoch = 0
self.wait = 0
self.wait_lr = 0
self.mode = (
getattr(scvi_data_loader_class, early_stopping_metric).mode
if early_stopping_metric is not None
else None
)
# We set the best to + inf because we're dealing with a loss we want to minimize
self.current_performance = np.inf
self.best_performance = np.inf
self.best_performance_state = np.inf
# If we want to maximize, we start at - inf
if self.mode == "max":
self.best_performance *= -1
self.current_performance *= -1
self.mode_save_state = (
getattr(ScviDataLoader, save_best_state_metric).mode
if save_best_state_metric is not None
else None
)
if self.mode_save_state == "max":
self.best_performance_state *= -1
self.early_stopping_metric = early_stopping_metric
self.save_best_state_metric = save_best_state_metric
self.on = on
self.reduce_lr_on_plateau = reduce_lr_on_plateau
self.lr_patience = lr_patience
self.lr_factor = lr_factor
def update(self, scalar):
self.epoch += 1
if self.benchmark:
continue_training = True
reduce_lr = False
elif self.wait >= self.patience:
continue_training = False
reduce_lr = False
else:
# Check if we should reduce the learning rate
if not self.reduce_lr_on_plateau:
reduce_lr = False
elif self.wait_lr >= self.lr_patience:
reduce_lr = True
self.wait_lr = 0
else:
reduce_lr = False
# Shift
self.current_performance = scalar
# Compute improvement
if self.mode == "max":
improvement = self.current_performance - self.best_performance
elif self.mode == "min":
improvement = self.best_performance - self.current_performance
else:
raise NotImplementedError("Unknown optimization mode")
# updating best performance
if improvement > 0:
self.best_performance = self.current_performance
if improvement < self.threshold:
self.wait += 1
self.wait_lr += 1
else:
self.wait = 0
self.wait_lr = 0
continue_training = True
if not continue_training:
# FIXME: log total number of epochs run
logger.info(
"\nStopping early: no improvement of more than "
+ str(self.threshold)
+ " nats in "
+ str(self.patience)
+ " epochs"
)
logger.info(
"If the early stopping criterion is too strong, "
"please instantiate it with different parameters in the train method."
)
return continue_training, reduce_lr
def update_state(self, scalar):
improved = (
self.mode_save_state == "max" and scalar - self.best_performance_state > 0
) or (
self.mode_save_state == "min" and self.best_performance_state - scalar > 0
)
if improved:
self.best_performance_state = scalar
return improved
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/trainers/scvi/trainer.py
| 0.919665 | 0.415017 |
trainer.py
|
pypi
|
import time
import torch
from sklearn.cluster import KMeans
from torch.utils.data import DataLoader
from scarchest.dataset.mars import MetaAnnotatedDataset
from scarchest.dataset.trvae import AnnotatedDataset
from scarchest.models import MARS
from ._utils import split_meta_train_tasks, euclidean_dist, print_meta_progress
from .meta import MetaTrainer
import scanpy as sc
class MARSTrainer(MetaTrainer):
def __init__(self, model: MARS, adata: sc.AnnData, task_key: str, cell_type_key: str, n_clusters: int,
meta_test_tasks: list,
tau: float = 0.2, eta: float = 1.0, **kwargs):
super().__init__(model, adata, task_key, **kwargs)
self.cell_type_key = cell_type_key
self.n_clusters = n_clusters
self.meta_test_tasks = meta_test_tasks
self.tau = tau
self.eta = eta
self.pre_train_n_epochs = kwargs.pop('pre_train_n_epochs', 100)
self.pre_train_batch_size = kwargs.pop('pre_train_batch_size', 128)
def on_training_begin(self):
self.meta_adata = MetaAnnotatedDataset(adata=self.adata,
task_key=self.task_key,
meta_test_task=self.meta_test_tasks[0],
cell_type_key=self.cell_type_key,
task_encoder=self.model.condition_encoder,
)
self.meta_train_data_loaders_tr, self.meta_train_data_loaders_ts = split_meta_train_tasks(self.meta_adata,
self.train_frac,
stratify=True,
batch_size=self.batch_size,
num_workers=self.n_workers)
self.meta_test_data_loader = pre_train_data_loader = DataLoader(dataset=self.meta_adata.meta_test_task_adata,
batch_size=self.pre_train_batch_size,
num_workers=self.n_workers)
self.pre_train_with_meta_test(pre_train_data_loader)
self.meta_train_landmarks, self.meta_test_landmarks = self.initialize_landmarks()
self.optimizer = torch.optim.Adam(params=list(self.model.encoder.parameters()), lr=self.learning_rate)
self.meta_test_landmark_optimizer = torch.optim.Adam(params=[self.meta_test_landmarks], lr=self.learning_rate)
self.lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer=self.optimizer,
gamma=self.lr_gamma,
step_size=self.lr_step_size)
def pre_train_with_meta_test(self, pre_train_data_loader):
pre_train_optimizer = torch.optim.Adam(params=list(self.model.parameters()), lr=self.pre_train_learning_rate)
for _ in range(self.pre_train_n_epochs):
for _, batch_data in enumerate(pre_train_data_loader):
x = batch_data['x'].to(self.device)
c = batch_data['c'].to(self.device)
_, decoded, loss, recon_loss, kl_loss = self.model(x, c)
pre_train_optimizer.zero_grad()
loss.backward()
if self.clip_value > 0:
torch.nn.utils.clip_grad_value_(self.model.parameters(), self.clip_value)
pre_train_optimizer.step()
def initialize_landmarks(self):
def k_means_initalization(dataset: AnnotatedDataset, n_clusters):
encoded = self.model.get_latent(dataset.data, dataset.conditions)
k_means = KMeans(n_clusters=n_clusters, random_state=0).fit(encoded)
return torch.tensor(k_means.cluster_centers_, device=self.device)
meta_train_landmarks = [
torch.zeros(size=(len(adataset.unique_cell_types), self.model.z_dim), requires_grad=True,
device=self.device) for adataset in self.meta_adata.meta_train_tasks_adata]
meta_test_landmarks = torch.zeros(size=(self.n_clusters, self.model.z_dim), requires_grad=True,
device=self.device)
k_means_init_train = [k_means_initalization(adataset, n_clusters=len(adataset.unique_cell_types))
for adataset in self.meta_adata.meta_train_tasks_adata]
k_means_init_test = k_means_initalization(self.meta_adata.meta_test_task_adata,
n_clusters=self.n_clusters)
with torch.no_grad():
[landmark.copy_(k_means_init_train[idx]) for idx, landmark in enumerate(meta_train_landmarks)]
meta_test_landmarks.copy_(k_means_init_test)
return meta_train_landmarks, meta_test_landmarks
def train(self,
n_epochs=400,
evaluate_on_meta_test=True,
):
begin = time.time()
# Initialize Train/Val Data, Optimizer, Sampler, and Dataloader
self.on_training_begin()
for self.epoch in range(n_epochs):
self.on_epoch_begin()
loss, acc = self.on_epoch()
# Validation of Model, Monitoring, Early Stopping
if evaluate_on_meta_test:
valid_loss, valid_acc, test_accuracy = self.on_epoch_end(evaluate_on_meta_test)
else:
valid_loss, valid_acc = self.on_epoch_end(evaluate_on_meta_test)
if self.use_early_stopping:
if not self.check_early_stop():
break
logs = {
'loss': [loss],
'acc': [acc],
'val_loss': [valid_loss],
'val_acc': [valid_acc],
}
if evaluate_on_meta_test:
logs['test_accuracy'] = [test_accuracy]
if self.monitor:
print_meta_progress(self.epoch, logs, n_epochs)
if hasattr(self, 'best_state_dict') and self.best_state_dict is not None:
print("Saving best state of network...")
print("Best State was in Epoch", self.best_epoch)
self.model.load_state_dict(self.best_state_dict)
self.model.eval()
self.training_time += (time.time() - begin)
# Empty at the moment
self.on_training_end()
def on_epoch(self): # EM step perfomed on each epoch
self.model.train()
# Update Landmarks
for param in self.model.parameters():
param.requires_grad = False
self.meta_test_landmarks.requires_grad = False
self.meta_test_landmark_optimizer.zero_grad()
for idx, task_data_loader_tr in enumerate(self.meta_train_data_loaders_tr):
for task_data in task_data_loader_tr:
X = task_data['x'].to(self.device)
c = task_data['c'].to(self.device)
y = task_data['y'].to(self.device)
encoded, _, _, _, _ = self.model(X, c)
current_meta_train_landmarks = self.update_meta_train_landmarks(encoded, y,
self.meta_train_landmarks[idx],
self.tau)
self.meta_train_landmarks[idx] = current_meta_train_landmarks.data
self.meta_test_landmarks.requires_grad = True
for task_data in self.meta_test_data_loader:
X = task_data['x'].to(self.device)
c = task_data['c'].to(self.device)
encoded, _, loss, _, _ = self.model(X, c)
loss = self.eta * loss + self.test_loss(encoded, self.meta_test_landmarks, self.tau)
loss.backward()
self.meta_test_landmark_optimizer.step()
# Update Encoder
for param in self.model.parameters():
param.requires_grad = True
self.meta_test_landmarks.requires_grad = False
self.optimizer.zero_grad()
loss = torch.tensor(0.0)
acc = torch.tensor(0.0)
for idx, task_data_loader_tr in enumerate(self.meta_train_data_loaders_tr):
for batch_data in task_data_loader_tr:
X = batch_data['x'].to(self.device)
c = batch_data['c'].to(self.device)
y = batch_data['y'].to(self.device)
encoded, _, loss, _, _ = self.model(X, c)
task_loss, task_acc = self.task_loss(encoded, y, self.meta_train_landmarks[idx])
loss = self.eta * loss + task_loss
acc += task_acc
n_tasks = len(self.meta_train_data_loaders_tr)
acc /= n_tasks
for batch_data in self.meta_test_data_loader:
X = batch_data['x'].to(self.device)
c = batch_data['c'].to(self.device)
encoded, _, loss, _, _ = self.model(X, c)
loss = self.eta * loss + self.test_loss(encoded, self.meta_test_landmarks, self.tau)
loss = loss / (n_tasks + 1)
loss.backward()
self.optimizer.step()
return loss, acc
def on_epoch_end(self, evaluate_on_meta_test=False):
self.model.eval()
n_tasks = len(self.meta_train_data_loaders_ts)
with torch.no_grad():
valid_loss, valid_acc = 0.0, 0.0
for idx, task_data_loader_tr in enumerate(self.meta_train_data_loaders_ts):
for task_data in task_data_loader_tr:
X = task_data['x'].to(self.device)
c = task_data['c'].to(self.device)
y = task_data['y'].to(self.device)
encoded, _, _, _, _ = self.model(X, c)
task_loss, task_acc = self.task_loss(encoded, y, self.meta_train_landmarks[idx])
valid_loss += task_loss
valid_acc += task_acc.item()
mean_accuracy = valid_acc / n_tasks
mean_loss = valid_loss / n_tasks
if evaluate_on_meta_test:
test_accuracy = 0.0
with torch.no_grad():
for batch_data in self.meta_test_data_loader:
X = batch_data['x'].to(self.device)
c = batch_data['c'].to(self.device)
y = batch_data['y'].to(self.device)
encoded, _, _, _, _ = self.model(X, c)
test_accuracy += self.evaluate_on_unannotated_dataset(encoded, y) * X.shape[0]
test_accuracy /= len(self.meta_test_data_loader.dataset)
return mean_loss, mean_accuracy, test_accuracy
else:
return mean_loss, mean_accuracy
def evaluate_on_unannotated_dataset(self, encoded, y_true):
distances = euclidean_dist(encoded, self.meta_test_landmarks)
_, y_pred = torch.max(-distances, dim=1)
accuracy = y_pred.eq(y_true).float().mean()
return accuracy
def task_loss(self, embeddings, labels, landmarks):
n_samples = embeddings.shape[0]
unique_labels = torch.unique(labels, sorted=True)
class_indices = list(map(lambda x: labels.eq(x).nonzero(), unique_labels))
for idx, value in enumerate(unique_labels):
labels[labels == value] = idx
distances = euclidean_dist(embeddings, landmarks)
loss = torch.stack(
[distances[indices, landmark_index].sum(0) for landmark_index, indices in
enumerate(class_indices)]).sum() / n_samples
_, y_pred = torch.max(-distances, dim=1)
accuracy = y_pred.eq(labels.squeeze()).float().mean()
return loss, accuracy
def test_loss(self, embeddings, landmarks, tau):
distances = euclidean_dist(embeddings, landmarks)
min_distances, y_hat = torch.min(distances, dim=1)
unique_predicted_labels = torch.unique(y_hat, sorted=True)
loss = torch.stack(
[min_distances[y_hat == unique_y_hat].mean(0) for unique_y_hat in unique_predicted_labels]).mean()
if tau > 0:
landmarks_distances = euclidean_dist(landmarks, landmarks)
n_landmarks = landmarks.shape[0]
loss -= torch.sum(landmarks_distances) * tau / (n_landmarks * (n_landmarks - 1))
return loss
def update_meta_train_landmarks(self, embeddings, labels, previous_landmarks, tau):
unique_labels = torch.unique(labels, sorted=True)
class_indices = list(map(lambda y: labels.eq(y).nonzero(), unique_labels))
landmarks_mean = torch.stack([embeddings[class_index].mean(0) for class_index in class_indices]).squeeze()
if previous_landmarks is None or tau == 0:
return landmarks_mean
previous_landmarks_sum = previous_landmarks.sum(0)
n_landmarks = previous_landmarks.shape[0]
landmarks_distance_partial = (tau / (n_landmarks - 1)) * torch.stack(
[previous_landmarks_sum - landmark for landmark in previous_landmarks])
landmarks = (1 / (1 - tau)) * (landmarks_mean - landmarks_distance_partial)
return landmarks
def on_epoch_begin(self):
pass
def on_iteration_begin(self):
pass
def on_iteration_end(self):
pass
def on_training_end(self):
pass
def check_early_stop(self):
return True
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/trainers/mars/mars_meta_trainer.py
| 0.842734 | 0.242301 |
mars_meta_trainer.py
|
pypi
|
import time
import scanpy as sc
import torch
from torch.utils.data import DataLoader
from scarchest.models import MARS
from scarchest.trainers.trvae._utils import make_dataset
from ._utils import print_meta_progress
from .meta import MetaTrainer
class MARSPreTrainer(MetaTrainer):
def __init__(self, model: MARS, adata: sc.AnnData, task_key: str,
**kwargs):
super().__init__(model, adata, task_key, **kwargs)
def on_training_begin(self):
self.train_dataset, self.valid_dataset = make_dataset(self.adata,
train_frac=self.train_frac,
use_stratified_split=True,
condition_key=self.task_key,
cell_type_key=None,
size_factor_key=None,
condition_encoder=self.model.condition_encoder,
)
self.train_data_loader = DataLoader(dataset=self.train_dataset,
batch_size=self.batch_size,
num_workers=self.n_workers)
self.valid_data_loader = DataLoader(dataset=self.valid_dataset,
batch_size=len(self.valid_dataset),
num_workers=1)
self.optimizer = torch.optim.Adam(params=list(self.model.parameters()), lr=self.learning_rate)
self.lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer=self.optimizer,
gamma=self.lr_gamma,
step_size=self.lr_step_size)
def train(self,
n_epochs=400,
):
begin = time.time()
# Initialize Train/Val Data, Optimizer, Sampler, and Dataloader
self.on_training_begin()
for self.epoch in range(n_epochs):
self.on_epoch_begin()
loss, recon_loss, kl_loss = self.on_epoch()
# Validation of Model, Monitoring, Early Stopping
valid_loss, valid_recon_loss, valid_kl_loss = self.on_epoch_end()
if self.use_early_stopping:
if not self.check_early_stop():
break
logs = {
'loss': [loss],
'recon_loss': [recon_loss],
'kl_loss': [kl_loss],
'val_loss': [valid_loss],
'val_recon_loss': [valid_recon_loss],
'val_kl_loss': [valid_kl_loss],
}
if self.monitor:
print_meta_progress(self.epoch, logs, n_epochs)
if hasattr(self, 'best_state_dict') and self.best_state_dict is not None:
print("Saving best state of network...")
print("Best State was in Epoch", self.best_epoch)
self.model.load_state_dict(self.best_state_dict)
self.model.eval()
self.training_time += (time.time() - begin)
# Empty at the moment
self.on_training_end()
def on_epoch(self):
self.model.train()
loss = torch.tensor(0.0)
recon_loss = torch.tensor(0.0)
kl_loss = torch.tensor(0.0)
for batch_data in self.train_data_loader:
x = batch_data['x'].to(self.device)
c = batch_data['c'].to(self.device)
_, decoded, batch_loss, batch_recon_loss, batch_kl_loss = self.model(x, c)
loss += batch_loss * len(batch_data)
kl_loss += batch_kl_loss * len(batch_data)
recon_loss += batch_recon_loss * len(batch_data)
self.optimizer.zero_grad()
batch_loss.backward()
if self.clip_value > 0:
torch.nn.utils.clip_grad_value_(self.model.parameters(), self.clip_value)
self.optimizer.step()
loss /= len(self.train_dataset)
recon_loss /= len(self.train_dataset)
kl_loss /= len(self.train_dataset)
return loss, recon_loss, kl_loss
def on_epoch_end(self, evaluate_on_meta_test=False):
self.model.eval()
with torch.no_grad():
valid_loss, valid_recon_loss, valid_kl_loss = 0.0, 0.0, 0.0
for valid_data in self.valid_data_loader:
x = valid_data['x'].to(self.device)
c = valid_data['c'].to(self.device)
_, _, batch_loss, batch_recon_loss, batch_kl_loss = self.model(x, c)
valid_loss += batch_loss * len(valid_data)
valid_recon_loss += batch_recon_loss * len(valid_data)
valid_kl_loss += batch_kl_loss * len(valid_data)
valid_loss /= len(self.valid_dataset)
valid_kl_loss /= len(self.valid_dataset)
valid_recon_loss /= len(self.valid_dataset)
return valid_loss, valid_recon_loss, valid_kl_loss
def on_epoch_begin(self):
pass
def on_iteration_begin(self):
pass
def on_iteration_end(self):
pass
def on_training_end(self):
pass
def check_early_stop(self):
return True
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/trainers/mars/unsupervised.py
| 0.848157 | 0.1779 |
unsupervised.py
|
pypi
|
import torch
import numpy as np
from torch.utils.data import DataLoader, SubsetRandomSampler
from scarchest.dataset.mars import MetaAnnotatedDataset
from scarchest.trainers.trvae._utils import _print_progress_bar
def print_meta_progress(epoch, logs, n_epochs=10000):
"""Creates Message for '_print_progress_bar'.
Parameters
----------
epoch: Integer
Current epoch iteration.
logs: dict
List of all current losses.
n_epochs: Integer
Maximum value of epochs.
Returns
-------
"""
message = f' - loss: {logs["loss"][-1]:.4f}'
train_keys = [key for key in sorted(list(logs.keys())) if (not key.startswith('val_') and not key.startswith('test_') and key != 'loss')]
for key in train_keys:
message += f' - {key}: {logs[key][-1]:.4f}'
message += f' - val_loss: {logs["val_loss"][-1]:.4f}'
valid_keys = [key for key in sorted(list(logs.keys())) if (key.startswith('val_') and key != 'val_loss')]
for key in valid_keys:
message += f' - {key}: {logs[key][-1]:.4f}'
test_keys = [key for key in sorted(list(logs.keys())) if (key.startswith('test_'))]
for key in test_keys:
message += f' - {key}: {logs[key][-1]:.4f}'
_print_progress_bar(epoch + 1, n_epochs, prefix='', suffix=message, decimals=1, length=20)
def split_meta_train_tasks(meta_adata: MetaAnnotatedDataset,
train_fraction: float = 0.8,
stratify: bool = False,
batch_size: int = 32,
num_workers=6):
train_data_loaders, valid_data_loaders = [], []
for idx, meta_train_dataset in enumerate(meta_adata.meta_train_tasks_adata):
np.random.seed(2020 * idx)
n_samples = len(meta_train_dataset)
indices = np.arange(n_samples)
np.random.shuffle(indices)
train_idx = indices[:int(train_fraction * n_samples)]
valid_idx = indices[int(train_fraction * n_samples):]
train_data_loader = DataLoader(dataset=meta_train_dataset,
sampler=SubsetRandomSampler(train_idx),
num_workers=num_workers,
batch_size=batch_size,
pin_memory=True)
valid_data_loader = DataLoader(dataset=meta_train_dataset,
sampler=SubsetRandomSampler(valid_idx),
num_workers=num_workers,
batch_size=batch_size,
pin_memory=True)
train_data_loaders.append(train_data_loader)
valid_data_loaders.append(valid_data_loader)
return train_data_loaders, valid_data_loaders
def euclidean_dist(x, y):
'''
Compute euclidean distance between two tensors
'''
# x: N x D
# y: M x D
n = x.size(0)
m = y.size(0)
d = x.size(1)
if d != y.size(1):
raise Exception
x = x.unsqueeze(1).expand(n, m, d)
y = y.unsqueeze(0).expand(n, m, d)
return torch.pow(x - y, 2).sum(2)
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/trainers/mars/_utils.py
| 0.893675 | 0.331241 |
_utils.py
|
pypi
|
from abc import abstractmethod
import torch
import torch.nn as nn
from collections import defaultdict
import numpy as np
import time
from torch.utils.data import DataLoader
from torch.utils.data import WeightedRandomSampler
from scarchest.utils.monitor import EarlyStopping
from ._utils import make_dataset, custom_collate, print_progress
class Trainer:
def __init__(self,
model,
adata,
condition_key: str = None,
cell_type_key: str = None,
size_factor_key: str = None,
is_label_key: str = None,
clip_value: float = 0.0,
weight_decay: float = 0.04,
train_frac: float = 0.9,
early_stopping_kwargs: dict = None,
batch_size: int = 512,
n_samples: int = None,
n_workers: int = 0,
**kwargs):
self.adata = adata
self.condition_key = condition_key
self.cell_type_key = cell_type_key
self.size_factor_key = size_factor_key
self.is_label_key = is_label_key
self.clip_value = clip_value
self.weight_decay = weight_decay
self.train_frac = train_frac
early_stopping_kwargs = (early_stopping_kwargs if early_stopping_kwargs else dict())
self.batch_size = batch_size
self.n_workers = n_workers
self.seed = kwargs.pop("seed", 2020)
self.use_stratified_sampling = kwargs.pop("use_stratified_sampling", True)
self.use_early_stopping = kwargs.pop("use_early_stopping", True)
self.monitor = kwargs.pop("monitor", True)
self.use_stratified_split = kwargs.pop("use_stratified_split", False)
self.early_stopping = EarlyStopping(**early_stopping_kwargs)
torch.manual_seed(self.seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(self.seed)
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.model = model.to(self.device)
self.model.device = self.device
self.epoch = -1
self.iter = 0
self.best_epoch = None
self.best_state_dict = None
self.current_loss = None
self.previous_loss_was_nan = False
self.nan_counter = 0
self.optimizer = None
self.lr_scheduler = None
self.training_time = 0
self.train_data = None
self.valid_data = None
self.sampler = None
self.dataloader_train = None
self.dataloader_valid = None
self.n_samples = n_samples
self.iters_per_epoch = None
self.val_iters_per_epoch = None
self.iter_logs = defaultdict(list)
self.logs = defaultdict(list)
def on_training_begin(self):
"""
Initializes Train-/Test Data and Dataloaders with custom_collate and WeightedRandomSampler for Trainloader.
Returns:
"""
# Create Train/Valid AnnotatetDataset objects
self.train_data, self.valid_data = make_dataset(self.adata,
train_frac=self.train_frac,
use_stratified_split=self.use_stratified_split,
condition_key=self.condition_key,
cell_type_key=self.cell_type_key,
size_factor_key=self.size_factor_key,
condition_encoder=self.model.condition_encoder,
cell_type_encoder=None
)
print("Traindata:", len(self.train_data))
for i in range(len(self.train_data.unique_conditions)):
print("Condition:", i, "Counts in TrainData:", np.count_nonzero(self.train_data.conditions == i))
if self.n_samples is None or self.n_samples > len(self.train_data):
self.n_samples = len(self.train_data)
self.iters_per_epoch = int(np.ceil(self.n_samples / self.batch_size))
if self.use_stratified_sampling:
# Create Sampler and Dataloaders
stratifier_weights = torch.tensor(self.train_data.stratifier_weights, device=self.device)
self.sampler = WeightedRandomSampler(stratifier_weights,
num_samples=self.n_samples,
replacement=True)
self.dataloader_train = torch.utils.data.DataLoader(dataset=self.train_data,
batch_size=self.batch_size,
sampler=self.sampler,
collate_fn=custom_collate,
num_workers=self.n_workers)
else:
self.dataloader_train = torch.utils.data.DataLoader(dataset=self.train_data,
batch_size=self.batch_size,
shuffle=True,
collate_fn=custom_collate,
num_workers=self.n_workers)
if self.valid_data is not None:
print("Valid_data", len(self.valid_data))
for i in range(len(self.valid_data.unique_conditions)):
print("Condition:", i, "Counts in TrainData:", np.count_nonzero(self.valid_data.conditions == i))
val_batch_size = self.batch_size
if self.batch_size > len(self.valid_data):
val_batch_size = len(self.valid_data)
self.val_iters_per_epoch = int(np.ceil(len(self.valid_data) / self.batch_size))
self.dataloader_valid = torch.utils.data.DataLoader(dataset=self.valid_data,
batch_size=val_batch_size,
shuffle=True,
collate_fn=custom_collate,
num_workers=self.n_workers)
@abstractmethod
def on_epoch_begin(self):
pass
@abstractmethod
def loss(self, **kwargs):
pass
@abstractmethod
def on_iteration_begin(self):
pass
def on_iteration(self, batch_data):
# Dont update any weight on first layers except condition weights
if self.model.freeze:
for name, module in self.model.named_modules():
if isinstance(module, nn.BatchNorm1d):
if not module.weight.requires_grad:
module.affine = False
module.track_running_stats = False
# Calculate Loss depending on Trainer/Model
self.current_loss = loss = self.loss(**batch_data)
self.optimizer.zero_grad()
loss.backward()
# Gradient Clipping
if self.clip_value > 0:
torch.nn.utils.clip_grad_value_(self.model.parameters(), self.clip_value)
self.optimizer.step()
@abstractmethod
def on_iteration_end(self):
pass
def on_epoch_end(self):
# Get Train Epoch Logs
for key in self.iter_logs:
if "loss" in key:
self.logs["epoch_" + key].append(
sum(self.iter_logs[key][-self.iters_per_epoch:]) / self.iters_per_epoch)
# Validate Model
if self.valid_data is not None:
self.validate()
# Monitor Logs
if self.monitor:
print_progress(self.epoch, self.logs, self.n_epochs)
def check_early_stop(self):
# Calculate Early Stopping and best state
early_stopping_metric = self.early_stopping.early_stopping_metric
save_best_state_metric = self.early_stopping.save_best_state_metric
if save_best_state_metric is not None and self.early_stopping.update_state(
self.logs[save_best_state_metric][-1]):
self.best_state_dict = self.model.state_dict()
self.best_epoch = self.epoch
continue_training = True
if early_stopping_metric is not None and not self.early_stopping.step(self.logs[early_stopping_metric][-1]):
continue_training = False
return continue_training
# Update Learning Rate
self.lr_scheduler.step()
return continue_training
@abstractmethod
def on_training_end(self):
pass
@torch.no_grad()
def validate(self):
self.model.eval()
# Calculate Validation Losses
for val_iter, batch_data in enumerate(self.dataloader_valid):
for key1 in batch_data:
for key2, batch in batch_data[key1].items():
batch_data[key1][key2] = batch.to(self.device)
val_loss = self.loss(**batch_data)
# Get Validation Logs
for key in self.iter_logs:
if "loss" in key:
self.logs["val_" + key].append(
sum(self.iter_logs[key][-self.val_iters_per_epoch:]) / self.val_iters_per_epoch)
self.model.train()
def train(self,
n_epochs=400,
lr=1e-3,
lr_gamma=1.0,
lr_step_size=100,
eps=0.01):
begin = time.time()
self.model.train()
self.n_epochs = n_epochs
params = filter(lambda p: p.requires_grad, self.model.parameters())
self.optimizer = torch.optim.Adam(params, lr=lr, eps=eps, weight_decay=self.weight_decay)
self.lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer=self.optimizer,
gamma=lr_gamma,
step_size=lr_step_size)
# Initialize Train/Val Data, Sampler, Dataloader
self.on_training_begin()
for self.epoch in range(n_epochs):
# Empty at the moment
self.on_epoch_begin()
for self.iter, batch_data in enumerate(self.dataloader_train):
for key1 in batch_data:
for key2, batch in batch_data[key1].items():
batch_data[key1][key2] = batch.to(self.device)
# Empty at the moment
self.on_iteration_begin()
# Loss Calculation, Gradient Clipping, Freeze first layer, Optimizer Step
self.on_iteration(batch_data)
# Empty at the moment
self.on_iteration_end()
# Validation of Model, Monitoring, Early Stopping
self.on_epoch_end()
if self.use_early_stopping:
if not self.check_early_stop():
break
if self.best_state_dict is not None:
print("Saving best state of network...")
print("Best State was in Epoch", self.best_epoch)
self.model.load_state_dict(self.best_state_dict)
self.model.eval()
self.training_time += (time.time() - begin)
# Empty at the moment
self.on_training_end()
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/trainers/trvae/trainer.py
| 0.816882 | 0.21262 |
trainer.py
|
pypi
|
import sys
import numpy as np
import re
import torch
from torch._six import container_abcs
from torch.utils.data import DataLoader, SubsetRandomSampler
from scarchest.dataset.trvae import AnnotatedDataset
def print_progress(epoch, logs, n_epochs=10000):
"""Creates Message for '_print_progress_bar'.
Parameters
----------
epoch: Integer
Current epoch iteration.
logs: dict
Dictionary of all current losses.
n_epochs: Integer
Maximum value of epochs.
Returns
-------
"""
message = ""
for key in logs:
if "loss" in key and ("epoch_" in key or "val_" in key):
message += f" - {key:s}: {logs[key][-1]:7.0f}"
_print_progress_bar(epoch + 1, n_epochs, prefix='', suffix=message, decimals=1, length=20)
def _print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'):
"""Prints out message with a progress bar.
Parameters
----------
iteration: Integer
Current epoch.
total: Integer
Maximum value of epochs.
prefix: String
String before the progress bar.
suffix: String
String after the progress bar.
decimals: Integer
Digits after comma for all the losses.
length: Integer
Length of the progress bar.
fill: String
Symbol for filling the bar.
Returns
-------
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filled_len = int(length * iteration // total)
bar = fill * filled_len + '-' * (length - filled_len)
sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percent, '%', suffix)),
if iteration == total:
sys.stdout.write('\n')
sys.stdout.flush()
def train_test_split(adata, train_frac=0.85, condition_key=None):
"""Splits 'Anndata' object into training and validation data.
Parameters
----------
adata: `~anndata.AnnData`
`AnnData` object for training the model.
train_frac: float
Train-test split fraction. the model will be trained with train_frac for training
and 1-train_frac for validation.
Returns
-------
`AnnData` objects for training and validating the model.
"""
if train_frac == 1:
return adata, None
else:
indices = np.arange(adata.shape[0])
n_val_samples = int(adata.shape[0] * (1 - train_frac))
if condition_key is not None:
conditions = adata.obs[condition_key].unique().tolist()
n_conditions = len(conditions)
n_val_samples_per_condition = int(n_val_samples / n_conditions)
condition_indices_train = []
condition_indices_val = []
for i in range(n_conditions):
idx = indices[adata.obs[condition_key] == conditions[i]]
np.random.shuffle(idx)
condition_indices_val.append(idx[:n_val_samples_per_condition])
condition_indices_train.append(idx[n_val_samples_per_condition:])
train_idx = np.concatenate(condition_indices_train)
val_idx = np.concatenate(condition_indices_val)
else:
np.random.shuffle(indices)
val_idx = indices[:n_val_samples]
train_idx = indices[n_val_samples:]
train_data = adata[train_idx, :]
valid_data = adata[val_idx, :]
return train_data, valid_data
def make_dataset(adata,
train_frac=0.9,
use_stratified_split=False,
condition_key=None,
cell_type_key=None,
size_factor_key=None,
condition_encoder=None,
cell_type_encoder=None,
):
"""Splits 'adata' into train and validation data and converts them into 'CustomDatasetFromAdata' objects.
Parameters
----------
Returns
-------
Training 'CustomDatasetFromAdata' object, Validation 'CustomDatasetFromAdata' object
"""
if use_stratified_split:
train_adata, validation_adata = train_test_split(adata, train_frac, condition_key=condition_key)
else:
train_adata, validation_adata = train_test_split(adata, train_frac)
data_set_train = AnnotatedDataset(train_adata,
condition_key=condition_key,
cell_type_key=cell_type_key,
size_factors_key=size_factor_key,
condition_encoder=condition_encoder,
cell_type_encoder=cell_type_encoder,)
if train_frac == 1:
return data_set_train, None
else:
data_set_valid = AnnotatedDataset(validation_adata,
condition_key=condition_key,
cell_type_key=cell_type_key,
size_factors_key=size_factor_key,
condition_encoder=condition_encoder,
cell_type_encoder=cell_type_encoder,)
return data_set_train, data_set_valid
def custom_collate(batch):
r"""Puts each data field into a tensor with outer dimension batch size"""
np_str_obj_array_pattern = re.compile(r'[SaUO]')
default_collate_err_msg_format = (
"default_collate: batch must contain tensors, numpy arrays, numbers, "
"dicts or lists; found {}")
elem = batch[0]
elem_type = type(elem)
if isinstance(elem, torch.Tensor):
out = None
if torch.utils.data.get_worker_info() is not None:
# If we're in a background process, concatenate directly into a
# shared memory tensor to avoid an extra copy
numel = sum([x.numel() for x in batch])
storage = elem.storage()._new_shared(numel)
out = elem.new(storage)
return torch.stack(batch, 0, out=out)
elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' and elem_type.__name__ != 'string_':
elem = batch[0]
if elem_type.__name__ == 'ndarray' or elem_type.__name__ == 'memmap':
# array of string classes and object
if np_str_obj_array_pattern.search(elem.dtype.str) is not None:
raise TypeError(default_collate_err_msg_format.format(elem.dtype))
return custom_collate([torch.as_tensor(b) for b in batch])
elif elem.shape == (): # scalars
return torch.as_tensor(batch)
elif isinstance(elem, container_abcs.Mapping):
if "y" in elem:
output = dict(total_batch=dict(),
labelled_batch=dict())
for key in elem:
total_data = [d[key] for d in batch]
labelled_data = list()
for d in batch:
if d["y"] != -1:
labelled_data.append(d[key])
output["total_batch"][key] = custom_collate(total_data)
output["labelled_batch"][key] = custom_collate(labelled_data)
else:
output = dict(total_batch=dict())
output["total_batch"] = {key: custom_collate([d[key] for d in batch]) for key in elem}
return output
|
/scArchest-0.0.1-py3-none-any.whl/scarchest/trainers/trvae/_utils.py
| 0.747339 | 0.317903 |
_utils.py
|
pypi
|
from typing import Optional
import anndata
import logging
import torch
from torch.distributions import Normal
import numpy as np
from scvi import _CONSTANTS
from scarchest.dataset.scvi import ScviDataLoader
from scarchest.models.scvi import totalVI
logger = logging.getLogger(__name__)
def _unpack_tensors(tensors):
x = tensors[_CONSTANTS.X_KEY]
local_l_mean = tensors[_CONSTANTS.LOCAL_L_MEAN_KEY]
local_l_var = tensors[_CONSTANTS.LOCAL_L_VAR_KEY]
batch_index = tensors[_CONSTANTS.BATCH_KEY]
labels = tensors[_CONSTANTS.LABELS_KEY]
y = tensors[_CONSTANTS.PROTEIN_EXP_KEY]
return x, local_l_mean, local_l_var, batch_index, labels, y
class TotalDataLoader(ScviDataLoader):
"""
Extended data loader for totalVI.
Parameters
----------
model :
A model instance from class ``TOTALVI``
adata:
A registered AnnData object
shuffle :
Specifies if a `RandomSampler` or a `SequentialSampler` should be used
indices :
Specifies how the data should be split with regards to train/test or labelled/unlabelled
use_cuda :
Default: ``True``
data_loader_kwargs :
Keyword arguments to passed into the `DataLoader`
"""
def __init__(
self,
model: totalVI,
adata: anndata.AnnData,
shuffle: bool = False,
indices: Optional[np.ndarray] = None,
use_cuda: bool = True,
batch_size: int = 256,
data_loader_kwargs=dict(),
):
super().__init__(
model,
adata,
shuffle=shuffle,
indices=indices,
use_cuda=use_cuda,
batch_size=batch_size,
data_loader_kwargs=data_loader_kwargs,
)
@property
def _data_and_attributes(self):
return {
_CONSTANTS.X_KEY: np.float32,
_CONSTANTS.BATCH_KEY: np.int64,
_CONSTANTS.LOCAL_L_MEAN_KEY: np.float32,
_CONSTANTS.LOCAL_L_VAR_KEY: np.float32,
_CONSTANTS.LABELS_KEY: np.int64,
_CONSTANTS.PROTEIN_EXP_KEY: np.float32,
}
@torch.no_grad()
def elbo(self):
elbo = self.compute_elbo(self.model)
return elbo
elbo.mode = "min"
@torch.no_grad()
def reconstruction_error(self, mode="total"):
ll_gene, ll_protein = self.compute_reconstruction_error(self.model)
if mode == "total":
return ll_gene + ll_protein
elif mode == "gene":
return ll_gene
else:
return ll_protein
reconstruction_error.mode = "min"
@torch.no_grad()
def marginal_ll(self, n_mc_samples=1000):
ll = self.compute_marginal_log_likelihood()
return ll
@torch.no_grad()
def get_protein_background_mean(self):
background_mean = []
for tensors in self:
x, _, _, batch_index, label, y = _unpack_tensors(tensors)
outputs = self.model.inference(
x, y, batch_index=batch_index, label=label, n_samples=1
)
b_mean = outputs["py_"]["rate_back"]
background_mean += [np.array(b_mean.cpu())]
return np.concatenate(background_mean)
def compute_elbo(self, vae: totalVI, **kwargs):
"""
Computes the ELBO.
The ELBO is the reconstruction error + the KL divergences
between the variational distributions and the priors.
It differs from the marginal log likelihood.
Specifically, it is a lower bound on the marginal log likelihood
plus a term that is constant with respect to the variational distribution.
It still gives good insights on the modeling of the data, and is fast to compute.
Parameters
----------
vae
vae model
**kwargs
keyword args for forward
"""
# Iterate once over the data loader and computes the total log_likelihood
elbo = 0
for _, tensors in enumerate(self):
x, local_l_mean, local_l_var, batch_index, labels, y = _unpack_tensors(
tensors
)
(
reconst_loss_gene,
reconst_loss_protein,
kl_div_z,
kl_div_gene_l,
kl_div_back_pro,
) = vae(
x,
y,
local_l_mean,
local_l_var,
batch_index=batch_index,
label=labels,
**kwargs,
)
elbo += torch.sum(
reconst_loss_gene
+ reconst_loss_protein
+ kl_div_z
+ kl_div_gene_l
+ kl_div_back_pro
).item()
n_samples = len(self.indices)
return elbo / n_samples
def compute_reconstruction_error(self, vae: totalVI, **kwargs):
r"""
Computes log p(x/z), which is the reconstruction error.
Differs from the marginal log likelihood, but still gives good
insights on the modeling of the data, and is fast to compute
This is really a helper function to self.ll, self.ll_protein, etc.
"""
# Iterate once over the data loader and computes the total log_likelihood
log_lkl_gene = 0
log_lkl_protein = 0
for _, tensors in enumerate(self):
x, local_l_mean, local_l_var, batch_index, labels, y = _unpack_tensors(
tensors
)
(
reconst_loss_gene,
reconst_loss_protein,
kl_div_z,
kl_div_l_gene,
kl_div_back_pro,
) = vae(
x,
y,
local_l_mean,
local_l_var,
batch_index=batch_index,
label=labels,
**kwargs,
)
log_lkl_gene += torch.sum(reconst_loss_gene).item()
log_lkl_protein += torch.sum(reconst_loss_protein).item()
n_samples = len(self.indices)
return log_lkl_gene / n_samples, log_lkl_protein / n_samples
def compute_marginal_log_likelihood(
self, n_samples_mc: int = 100, batch_size: int = 96
):
"""
Computes a biased estimator for log p(x, y), which is the marginal log likelihood.
Despite its bias, the estimator still converges to the real value
of log p(x, y) when n_samples_mc (for Monte Carlo) goes to infinity
(a fairly high value like 100 should be enough). 5000 is the standard in machine learning publications.
Due to the Monte Carlo sampling, this method is not as computationally efficient
as computing only the reconstruction loss
Parameters
----------
n_samples_mc
(Default value = 100)
batch_size
(Default value = 96)
"""
# Uses MC sampling to compute a tighter lower bound on log p(x)
log_lkl = 0
for _, tensors in enumerate(self.update_batch_size(batch_size)):
x, local_l_mean, local_l_var, batch_index, labels, y = _unpack_tensors(
tensors
)
to_sum = torch.zeros(x.size()[0], n_samples_mc)
for i in range(n_samples_mc):
# Distribution parameters and sampled variables
outputs = self.model.inference(x, y, batch_index, labels)
qz_m = outputs["qz_m"]
qz_v = outputs["qz_v"]
ql_m = outputs["ql_m"]
ql_v = outputs["ql_v"]
px_ = outputs["px_"]
py_ = outputs["py_"]
log_library = outputs["untran_l"]
# really need not softmax transformed random variable
z = outputs["untran_z"]
log_pro_back_mean = outputs["log_pro_back_mean"]
# Reconstruction Loss
(
reconst_loss_gene,
reconst_loss_protein,
) = self.model.get_reconstruction_loss(x, y, px_, py_)
# Log-probabilities
p_l_gene = (
Normal(local_l_mean, local_l_var.sqrt())
.log_prob(log_library)
.sum(dim=-1)
)
p_z = Normal(0, 1).log_prob(z).sum(dim=-1)
p_mu_back = self.model.back_mean_prior.log_prob(log_pro_back_mean).sum(
dim=-1
)
p_xy_zl = -(reconst_loss_gene + reconst_loss_protein)
q_z_x = Normal(qz_m, qz_v.sqrt()).log_prob(z).sum(dim=-1)
q_l_x = Normal(ql_m, ql_v.sqrt()).log_prob(log_library).sum(dim=-1)
q_mu_back = (
Normal(py_["back_alpha"], py_["back_beta"])
.log_prob(log_pro_back_mean)
.sum(dim=-1)
)
to_sum[:, i] = (
p_z + p_l_gene + p_mu_back + p_xy_zl - q_z_x - q_l_x - q_mu_back
)
batch_log_lkl = torch.logsumexp(to_sum, dim=-1) - np.log(n_samples_mc)
log_lkl += torch.sum(batch_log_lkl).item()
n_samples = len(self.indices)
# The minus sign is there because we actually look at the negative log likelihood
return -log_lkl / n_samples
|
/scArchest-0.0.1-py3-none-any.whl/scarches/dataset/scvi/total_data_loader.py
| 0.958079 | 0.320476 |
total_data_loader.py
|
pypi
|
import numpy as np
import logging
from sklearn.neighbors import KNeighborsClassifier
import torch
from scvi.core import unsupervised_clustering_accuracy
from scvi import _CONSTANTS
from scarchest.dataset.scvi import ScviDataLoader
logger = logging.getLogger(__name__)
class AnnotationDataLoader(ScviDataLoader):
def __init__(self, *args, model_zl=False, **kwargs):
super().__init__(*args, **kwargs)
self.model_zl = model_zl
def accuracy(self):
model, cls = (
(self.sampling_model, self.model)
if hasattr(self, "sampling_model")
else (self.model, None)
)
acc = compute_accuracy(model, self, classifier=cls, model_zl=self.model_zl)
logger.debug("Acc: %.4f" % (acc))
return acc
accuracy.mode = "max"
@torch.no_grad()
def hierarchical_accuracy(self):
all_y, all_y_pred = self.compute_predictions()
acc = np.mean(all_y == all_y_pred)
all_y_groups = np.array([self.model.labels_groups[y] for y in all_y])
all_y_pred_groups = np.array([self.model.labels_groups[y] for y in all_y_pred])
h_acc = np.mean(all_y_groups == all_y_pred_groups)
logger.debug("Hierarchical Acc : %.4f\n" % h_acc)
return acc
accuracy.mode = "max"
@torch.no_grad()
def compute_predictions(self, soft=False):
"""
Parameters
----------
soft
(Default value = False)
Returns
-------
the true labels and the predicted labels
"""
model, cls = (
(self.sampling_model, self.model)
if hasattr(self, "sampling_model")
else (self.model, None)
)
return compute_predictions(
model, self, classifier=cls, soft=soft, model_zl=self.model_zl
)
@torch.no_grad()
def unsupervised_classification_accuracy(self):
all_y, all_y_pred = self.compute_predictions()
uca = unsupervised_clustering_accuracy(all_y, all_y_pred)[0]
logger.debug("UCA : %.4f" % (uca))
return uca
unsupervised_classification_accuracy.mode = "max"
@torch.no_grad()
def nn_latentspace(self, data_loader):
data_train, _, labels_train = self.get_latent()
data_test, _, labels_test = data_loader.get_latent()
nn = KNeighborsClassifier()
nn.fit(data_train, labels_train)
score = nn.score(data_test, labels_test)
return score
@torch.no_grad()
def compute_accuracy(vae, data_loader, classifier=None, model_zl=False):
all_y, all_y_pred = compute_predictions(
vae, data_loader, classifier=classifier, model_zl=model_zl
)
return np.mean(all_y == all_y_pred)
@torch.no_grad()
def compute_predictions(
model, data_loader, classifier=None, soft=False, model_zl=False
):
all_y_pred = []
all_y = []
for _, tensors in enumerate(data_loader):
sample_batch = tensors[_CONSTANTS.X_KEY]
labels = tensors[_CONSTANTS.LABELS_KEY]
all_y += [labels.view(-1).cpu()]
if hasattr(model, "classify"):
if model.modified:
batch_index = tensors[_CONSTANTS.BATCH_KEY]
y_pred = model.classify(sample_batch, batch_index=batch_index)
else:
y_pred = model.classify(sample_batch)
elif classifier is not None:
# Then we use the specified classifier
if model is not None:
if model.log_variational:
sample_batch = torch.log(1 + sample_batch)
if model_zl:
if model.modified:
batch_index = tensors[_CONSTANTS.BATCH_KEY]
sample_z = model.z_encoder(sample_batch, batch_index)[0]
sample_l = model.l_encoder(sample_batch)[0]
else:
sample_z = model.z_encoder(sample_batch)[0]
sample_l = model.l_encoder(sample_batch)[0]
sample_batch = torch.cat((sample_z, sample_l), dim=-1)
else:
if model.modified:
batch_index = tensors[_CONSTANTS.BATCH_KEY]
sample_batch, _, _ = model.z_encoder(sample_batch, batch_index)
else:
sample_batch, _, _ = model.z_encoder(sample_batch)
y_pred = classifier(sample_batch)
else: # The model is the raw classifier
y_pred = model(sample_batch)
if not soft:
y_pred = y_pred.argmax(dim=-1)
all_y_pred += [y_pred.cpu()]
all_y_pred = np.array(torch.cat(all_y_pred))
all_y = np.array(torch.cat(all_y))
return all_y, all_y_pred
|
/scArchest-0.0.1-py3-none-any.whl/scarches/dataset/scvi/annotation_data_loader.py
| 0.849066 | 0.280179 |
annotation_data_loader.py
|
pypi
|
import numpy as np
import scanpy as sc
from scarchest.dataset.trvae import AnnotatedDataset
from scarchest.dataset.trvae._utils import label_encoder
class MetaAnnotatedDataset(object):
def __init__(self,
adata: sc.AnnData,
task_key: str,
meta_test_task: str = None,
task_encoder=None,
cell_type_key=None,
cell_type_encoder=None,
size_factors_key=None,
):
self.adata = adata
self.meta_test_task = meta_test_task
self.task_key = task_key
self.unique_tasks = list(np.unique(self.adata.obs[task_key]))
_, self.task_encoder = label_encoder(self.adata,
encoder=task_encoder,
condition_key=self.task_key)
self.meta_train_tasks = [task for task in self.unique_tasks if task != self.meta_test_task]
self.meta_test_tasks = [task for task in self.unique_tasks if task == self.meta_test_task]
self.cell_type_encoder = cell_type_encoder
self.cell_type_key = cell_type_key
self.unique_cell_types = np.unique(self.adata.obs[cell_type_key]) if self.cell_type_key else None
self.size_factors_key = size_factors_key
self.meta_train_tasks_adata = [AnnotatedDataset(
adata=self.adata[self.adata.obs[self.task_key] == task],
condition_key=self.task_key,
condition_encoder=self.task_encoder,
cell_type_key=self.cell_type_key,
cell_type_encoder=self.cell_type_encoder,
) for task in self.meta_train_tasks]
if self.meta_test_task is not None:
self.meta_test_task_adata = AnnotatedDataset(
adata=self.adata[self.adata.obs[self.task_key] == self.meta_test_task],
condition_key=self.task_key,
condition_encoder=self.task_encoder,
cell_type_key=self.cell_type_key,
cell_type_encoder=None,
size_factors_key=size_factors_key,
)
else:
self.meta_test_task_adata = None
|
/scArchest-0.0.1-py3-none-any.whl/scarches/dataset/mars/meta_anndata.py
| 0.545165 | 0.243789 |
meta_anndata.py
|
pypi
|
import numpy as np
import torch
from torch.utils.data import Dataset
from scipy import sparse
from .data_handling import remove_sparsity
from ._utils import label_encoder
class AnnotatedDataset(Dataset):
def __init__(self,
adata,
condition_key=None,
condition_encoder=None,
cell_type_key=None,
cell_type_encoder=None,
size_factors_key=None,
unique_conditions=None,
):
self.adata = adata
if sparse.issparse(self.adata.X):
self.adata = remove_sparsity(self.adata)
self.data = np.asarray(self.adata.X)
self.condition_encoder = condition_encoder
self.condition_key = condition_key
self.unique_conditions = unique_conditions
self.cell_type_encoder = cell_type_encoder
self.cell_type_key = cell_type_key
self.unique_cell_types = None
self.size_factors_key = size_factors_key
if self.condition_key is not None:
if self.unique_conditions is None:
self.unique_conditions = adata.obs[condition_key].unique().tolist()
self.conditions, self.condition_encoder = label_encoder(self.adata,
encoder=self.condition_encoder,
condition_key=condition_key)
self.conditions = np.array(self.conditions).reshape(-1, )
if self.cell_type_key is not None:
self.unique_cell_types = adata.obs[cell_type_key].unique().tolist()
self.cell_types, self.cell_type_encoder = label_encoder(self.adata,
encoder=self.cell_type_encoder,
condition_key=cell_type_key)
self.cell_types = np.array(self.cell_types).reshape(-1, )
if self.size_factors_key:
self.raw_data = np.array(self.adata.raw.X)
self.size_factors = np.array(self.adata.obs[self.size_factors_key].values).reshape(-1, )
def __getitem__(self, index):
outputs = dict()
outputs["x"] = torch.tensor(self.data[index, :])
if self.condition_key:
outputs["c"] = torch.tensor(self.conditions[index])
if self.cell_type_key:
outputs["y"] = torch.tensor(self.cell_types[index])
if self.size_factors_key:
outputs["raw"] = torch.tensor(self.raw_data[index, :])
outputs["f"] = torch.tensor(self.size_factors[index])
return outputs
def __len__(self):
return len(self.adata)
@property
def condition_label_encoder(self) -> dict:
return self.condition_encoder
@condition_label_encoder.setter
def condition_label_encoder(self, value: dict):
if value is not None:
self.condition_encoder = value
@property
def cell_type_label_encoder(self) -> dict:
return self.cell_type_encoder
@cell_type_label_encoder.setter
def cell_type_label_encoder(self, value: dict):
if value is not None:
self.cell_type_encoder = value
@property
def stratifier_weights(self):
condition_coeff = 1 / len(self.conditions)
weights_per_condition = list()
for i in range(len(self.conditions)):
samples_per_condition = np.count_nonzero(self.conditions == i)
if samples_per_condition == 0:
weights_per_condition.append(0)
else:
weights_per_condition.append((1 / samples_per_condition) * condition_coeff)
strat_weights = np.copy(self.conditions)
for i in range(len(self.conditions)):
strat_weights = np.where(strat_weights == i, weights_per_condition[i], strat_weights)
return strat_weights.astype(float)
|
/scArchest-0.0.1-py3-none-any.whl/scarches/dataset/trvae/anndata.py
| 0.822082 | 0.316132 |
anndata.py
|
pypi
|
import scanpy as sc
from scipy import sparse
def hvg_batch(adata, batch_key=None, target_genes=2000, flavor='cell_ranger', n_bins=20, adataout=False):
"""
Method to select HVGs based on mean dispersions of genes that are highly
variable genes in all batches. Using a the top target_genes per batch by
average normalize dispersion. If target genes still hasn't been reached,
then HVGs in all but one batches are used to fill up. This is continued
until HVGs in a single batch are considered.
"""
adata_hvg = adata if adataout else adata.copy()
n_batches = len(adata_hvg.obs[batch_key].cat.categories)
# Calculate double target genes per dataset
sc.pp.highly_variable_genes(adata_hvg,
flavor=flavor,
n_top_genes=target_genes,
n_bins=n_bins,
batch_key=batch_key)
nbatch1_dispersions = adata_hvg.var['dispersions_norm'][adata_hvg.var.highly_variable_nbatches >
len(adata_hvg.obs[batch_key].cat.categories) - 1]
nbatch1_dispersions.sort_values(ascending=False, inplace=True)
if len(nbatch1_dispersions) > target_genes:
hvg = nbatch1_dispersions.index[:target_genes]
else:
enough = False
print(f'Using {len(nbatch1_dispersions)} HVGs from full intersect set')
hvg = nbatch1_dispersions.index[:]
not_n_batches = 1
while not enough:
target_genes_diff = target_genes - len(hvg)
tmp_dispersions = adata_hvg.var['dispersions_norm'][adata_hvg.var.highly_variable_nbatches ==
(n_batches - not_n_batches)]
if len(tmp_dispersions) < target_genes_diff:
print(f'Using {len(tmp_dispersions)} HVGs from n_batch-{not_n_batches} set')
hvg = hvg.append(tmp_dispersions.index)
not_n_batches += 1
else:
print(f'Using {target_genes_diff} HVGs from n_batch-{not_n_batches} set')
tmp_dispersions.sort_values(ascending=False, inplace=True)
hvg = hvg.append(tmp_dispersions.index[:target_genes_diff])
enough = True
print(f'Using {len(hvg)} HVGs')
if not adataout:
del adata_hvg
return hvg.tolist()
else:
return adata_hvg[:, hvg].copy()
def remove_sparsity(adata):
"""
If ``adata.X`` is a sparse matrix, this will convert it in to normal matrix.
Parameters
----------
adata: :class:`~anndata.AnnData`
Annotated data matrix.
Returns
-------
adata: :class:`~anndata.AnnData`
Annotated dataset.
"""
if sparse.issparse(adata.X):
new_adata = sc.AnnData(X=adata.X.A, obs=adata.obs.copy(deep=True), var=adata.var.copy(deep=True))
return new_adata
return adata
def preprocess_data(adata,
filter_min_counts=True,
size_factors=True,
target_sum=None,
log_trans_input=True,
batch_key=None,
n_top_genes=1000,
scale=False):
"""Preprocesses the `adata`.
Parameters
----------
adata: `~anndata.AnnData`
Annotated data matrix.
filter_min_counts: boolean
If 'True' filter out Genes and Cells under min_count.
size_factors: boolean
If 'True' add Size Factors for ZINB/NB loss to 'adata'.
target_sum:
log_trans_input: boolean
If 'True' logarithmize the data matrix.
batch_key:
n_top_genes: int
Only keeps n highest variable genes in 'adata'
scale: boolean
If 'True' scale data to unit variance and zero mean.
Returns
-------
adata: `~anndata.AnnData`
Preprocessed annotated data matrix.
"""
if filter_min_counts:
sc.pp.filter_genes(adata, min_counts=1)
sc.pp.filter_cells(adata, min_counts=1)
adata_count = adata.copy()
obs = adata.obs_keys()
if size_factors and 'size_factors' not in obs:
sc.pp.normalize_total(adata,
target_sum=target_sum,
exclude_highly_expressed=False,
key_added='size_factors')
if log_trans_input:
sc.pp.log1p(adata)
if 0 < n_top_genes < adata.shape[1]:
if batch_key:
genes = hvg_batch(adata.copy(), batch_key=batch_key, adataout=False, target_genes=n_top_genes)
else:
sc.pp.highly_variable_genes(adata, n_top_genes=n_top_genes)
genes = adata.var['highly_variable']
adata = adata[:, genes]
adata_count = adata_count[:, genes]
if scale:
sc.pp.scale(adata)
if sparse.issparse(adata_count.X):
adata_count.X = adata_count.X.A
if sparse.issparse(adata.X):
adata.X = adata.X.A
if adata.raw is None:
adata.raw = adata_count.copy()
return adata
|
/scArchest-0.0.1-py3-none-any.whl/scarches/dataset/trvae/data_handling.py
| 0.808823 | 0.525308 |
data_handling.py
|
pypi
|
import numpy as np
import torch
from typing import Sequence
from torch.distributions import Normal, Categorical, kl_divergence as kl
from scvi.core.modules.utils import broadcast_labels
from scarchest.models.scvi._base import Decoder, Encoder
from .classifier import Classifier
from .scvi import scVI
class scANVI(scVI):
"""Single-cell annotation using variational inference.
This is an implementation of the scANVI model descibed in [Xu19]_,
inspired from M1 + M2 model, as described in (https://arxiv.org/pdf/1406.5298.pdf).
Parameters
----------
n_input
Number of input genes
n_batch
Number of batches
n_labels
Number of labels
n_hidden
Number of nodes per hidden layer
n_latent
Dimensionality of the latent space
n_layers
Number of hidden layers used for encoder and decoder NNs
dropout_rate
Dropout rate for neural networks
dispersion
One of the following
* ``'gene'`` - dispersion parameter of NB is constant per gene across cells
* ``'gene-batch'`` - dispersion can differ between different batches
* ``'gene-label'`` - dispersion can differ between different labels
* ``'gene-cell'`` - dispersion can differ for every gene in every cell
log_variational
Log(data+1) prior to encoding for numerical stability. Not normalization.
reconstruction_loss
One of
* ``'nb'`` - Negative binomial distribution
* ``'zinb'`` - Zero-inflated negative binomial distribution
y_prior
If None, initialized to uniform probability over cell types
labels_groups
Label group designations
use_labels_groups
Whether to use the label groups
Returns
-------
Examples
--------
>>> gene_dataset = CortexDataset()
>>> scanvi = SCANVI(gene_dataset.nb_genes, n_batch=gene_dataset.n_batches * False,
... n_labels=gene_dataset.n_labels)
>>> gene_dataset = SyntheticDataset(n_labels=3)
>>> scanvi = SCANVI(gene_dataset.nb_genes, n_batch=gene_dataset.n_batches * False,
... n_labels=3, y_prior=torch.tensor([[0.1,0.5,0.4]]), labels_groups=[0,0,1])
"""
def __init__(
self,
n_input: int,
n_batch: int = 0,
n_labels: int = 0,
n_hidden: int = 128,
n_latent: int = 10,
n_layers: int = 1,
dropout_rate: float = 0.1,
dispersion: str = "gene",
log_variational: bool = True,
gene_likelihood: str = "zinb",
y_prior=None,
labels_groups: Sequence[int] = None,
use_labels_groups: bool = False,
classifier_parameters: dict = dict(),
modified: bool = False,
):
super().__init__(
n_input,
n_batch=n_batch,
n_labels=n_labels,
n_hidden=n_hidden,
n_latent=n_latent,
n_layers=n_layers,
dropout_rate=dropout_rate,
dispersion=dispersion,
log_variational=log_variational,
gene_likelihood=gene_likelihood,
modified=modified,
)
# Classifier takes n_latent as input
self.cls_parameters = {
"n_layers": n_layers,
"n_hidden": n_hidden,
"dropout_rate": dropout_rate,
}
self.cls_parameters.update(classifier_parameters)
self.classifier = Classifier(n_latent, n_labels=n_labels, **self.cls_parameters)
self.encoder_z2_z1 = Encoder(
n_latent,
n_latent,
n_cat_list=[self.n_labels],
n_layers=n_layers,
n_hidden=n_hidden,
dropout_rate=dropout_rate,
)
self.decoder_z1_z2 = Decoder(
n_latent,
n_latent,
n_cat_list=[self.n_labels],
n_layers=n_layers,
n_hidden=n_hidden,
)
self.y_prior = torch.nn.Parameter(
y_prior
if y_prior is not None
else (1 / n_labels) * torch.ones(1, n_labels),
requires_grad=False,
)
self.use_labels_groups = use_labels_groups
self.labels_groups = (
np.array(labels_groups) if labels_groups is not None else None
)
if self.use_labels_groups:
assert labels_groups is not None, "Specify label groups"
unique_groups = np.unique(self.labels_groups)
self.n_groups = len(unique_groups)
assert (unique_groups == np.arange(self.n_groups)).all()
self.classifier_groups = Classifier(
n_latent, n_hidden, self.n_groups, n_layers, dropout_rate
)
self.groups_index = torch.nn.ParameterList(
[
torch.nn.Parameter(
torch.tensor(
(self.labels_groups == i).astype(np.uint8),
dtype=torch.uint8,
),
requires_grad=False,
)
for i in range(self.n_groups)
]
)
def classify(self, x, batch_index=None):
if self.log_variational:
x = torch.log(1 + x)
qz_m, _, z = self.z_encoder(x, batch_index)
# We classify using the inferred mean parameter of z_1 in the latent space
z = qz_m
if self.use_labels_groups:
w_g = self.classifier_groups(z)
unw_y = self.classifier(z)
w_y = torch.zeros_like(unw_y)
for i, group_index in enumerate(self.groups_index):
unw_y_g = unw_y[:, group_index]
w_y[:, group_index] = unw_y_g / (
unw_y_g.sum(dim=-1, keepdim=True) + 1e-8
)
w_y[:, group_index] *= w_g[:, [i]]
else:
w_y = self.classifier(z)
return w_y
def get_latents(self, x, y=None, batch_index=None):
zs = super().get_latents(x, batch_index=batch_index)
qz2_m, qz2_v, z2 = self.encoder_z2_z1(zs[0], y)
if not self.training:
z2 = qz2_m
return [zs[0], z2]
def forward(self, x, local_l_mean, local_l_var, batch_index=None, y=None):
is_labelled = False if y is None else True
outputs = self.inference(x, batch_index, y)
px_r = outputs["px_r"]
px_rate = outputs["px_rate"]
px_dropout = outputs["px_dropout"]
qz1_m = outputs["qz_m"]
qz1_v = outputs["qz_v"]
z1 = outputs["z"]
ql_m = outputs["ql_m"]
ql_v = outputs["ql_v"]
# Enumerate choices of label
ys, z1s = broadcast_labels(y, z1, n_broadcast=self.n_labels)
qz2_m, qz2_v, z2 = self.encoder_z2_z1(z1s, ys)
pz1_m, pz1_v = self.decoder_z1_z2(z2, ys)
reconst_loss = self.get_reconstruction_loss(x, px_rate, px_r, px_dropout)
# KL Divergence
mean = torch.zeros_like(qz2_m)
scale = torch.ones_like(qz2_v)
kl_divergence_z2 = kl(
Normal(qz2_m, torch.sqrt(qz2_v)), Normal(mean, scale)
).sum(dim=1)
loss_z1_unweight = -Normal(pz1_m, torch.sqrt(pz1_v)).log_prob(z1s).sum(dim=-1)
loss_z1_weight = Normal(qz1_m, torch.sqrt(qz1_v)).log_prob(z1).sum(dim=-1)
kl_divergence_l = kl(
Normal(ql_m, torch.sqrt(ql_v)),
Normal(local_l_mean, torch.sqrt(local_l_var)),
).sum(dim=1)
if is_labelled:
return (
reconst_loss + loss_z1_weight + loss_z1_unweight,
kl_divergence_z2 + kl_divergence_l,
0.0,
)
probs = self.classifier(z1)
reconst_loss += loss_z1_weight + (
(loss_z1_unweight).view(self.n_labels, -1).t() * probs
).sum(dim=1)
kl_divergence = (kl_divergence_z2.view(self.n_labels, -1).t() * probs).sum(
dim=1
)
kl_divergence += kl(
Categorical(probs=probs),
Categorical(probs=self.y_prior.repeat(probs.size(0), 1)),
)
kl_divergence += kl_divergence_l
return reconst_loss, kl_divergence, 0.0
|
/scArchest-0.0.1-py3-none-any.whl/scarches/models/scvi/scanvi.py
| 0.911155 | 0.59796 |
scanvi.py
|
pypi
|
"""Main module."""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Normal, kl_divergence as kl
from scvi.core._distributions import (
ZeroInflatedNegativeBinomial,
NegativeBinomial,
Poisson,
)
from scvi.core.modules.utils import one_hot
from scarchest.models.scvi._base import Encoder, DecoderSCVI
from typing import Tuple, Dict
torch.backends.cudnn.benchmark = True
# VAE model
class scVI(nn.Module):
"""Variational auto-encoder model.
This is an implementation of the scVI model descibed in [Lopez18]_
Parameters
----------
n_input
Number of input genes
n_batch
Number of batches, if 0, no batch correction is performed.
n_labels
Number of labels
n_hidden
Number of nodes per hidden layer
n_latent
Dimensionality of the latent space
n_layers
Number of hidden layers used for encoder and decoder NNs
dropout_rate
Dropout rate for neural networks
dispersion
One of the following
* ``'gene'`` - dispersion parameter of NB is constant per gene across cells
* ``'gene-batch'`` - dispersion can differ between different batches
* ``'gene-label'`` - dispersion can differ between different labels
* ``'gene-cell'`` - dispersion can differ for every gene in every cell
log_variational
Log(data+1) prior to encoding for numerical stability. Not normalization.
reconstruction_loss
One of
* ``'nb'`` - Negative binomial distribution
* ``'zinb'`` - Zero-inflated negative binomial distribution
* ``'poisson'`` - Poisson distribution
Examples
--------
>>> gene_dataset = CortexDataset()
>>> vae = VAE(gene_dataset.nb_genes, n_batch=gene_dataset.n_batches * False,
... n_labels=gene_dataset.n_labels)
"""
def __init__(
self,
n_input: int,
n_batch: int = 0,
n_labels: int = 0,
n_hidden: int = 128,
n_latent: int = 10,
n_layers: int = 1,
dropout_rate: float = 0.1,
dispersion: str = "gene",
log_variational: bool = True,
gene_likelihood: str = "zinb",
latent_distribution: str = "normal",
modified: bool = False,
):
super().__init__()
self.n_input = n_input
self.n_batch = n_batch
self.n_labels = n_labels
self.n_hidden = n_hidden
self.n_latent = n_latent
self.n_layers = n_layers
self.dropout_rate = dropout_rate
self.dispersion = dispersion
self.log_variational = log_variational
self.gene_likelihood = gene_likelihood
self.latent_distribution = latent_distribution
# Added for scArches
self.modified = modified
self.freeze = False
self.new_conditions = 0
if self.dispersion == "gene":
self.px_r = torch.nn.Parameter(torch.randn(n_input))
elif self.dispersion == "gene-batch":
self.px_r = torch.nn.Parameter(torch.randn(n_input, n_batch))
elif self.dispersion == "gene-label":
self.px_r = torch.nn.Parameter(torch.randn(n_input, n_labels))
elif self.dispersion == "gene-cell":
pass
else:
raise ValueError(
"dispersion must be one of ['gene', 'gene-batch',"
" 'gene-label', 'gene-cell'], but input was "
"{}.format(self.dispersion)"
)
# z encoder goes from the n_input-dimensional data to an n_latent-d
# latent space representation
self.z_encoder = Encoder(
n_input,
n_latent,
n_cat_list=[n_batch] if self.modified else None,
n_layers=n_layers,
n_hidden=n_hidden,
dropout_rate=self.dropout_rate,
distribution=latent_distribution,
modified=self.modified
)
# l encoder goes from n_input-dimensional data to 1-d library size
self.l_encoder = Encoder(
n_input,
1,
n_layers=1,
n_hidden=n_hidden,
dropout_rate=self.dropout_rate,
)
# decoder goes from n_latent-dimensional space to n_input-d data
self.decoder = DecoderSCVI(
n_latent,
n_input,
n_cat_list=[n_batch],
n_layers=n_layers,
n_hidden=n_hidden,
modified=modified
)
def get_latents(self, x, y=None, batch_index=None) -> torch.Tensor:
"""Returns the result of ``sample_from_posterior_z`` inside a list
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input)``
y
tensor of cell-types labels with shape ``(batch_size, n_labels)`` (Default value = None)
batch_index
tensor of study/batch labels with shape ``(batch_size, n_labels)`` (Default value = None)
Returns
-------
type
one element list of tensor
"""
return [self.sample_from_posterior_z(x, y=y, batch_index=batch_index)]
def sample_from_posterior_z(
self, x, y=None, batch_index=None, give_mean=False, n_samples=5000
) -> torch.Tensor:
"""Samples the tensor of latent values from the posterior
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input)``
y
tensor of cell-types labels with shape ``(batch_size, n_labels)`` (Default value = None)
batch_index
tensor of study/batch labels with shape ``(batch_size, n_labels)`` (Default value = None)
give_mean
is True when we want the mean of the posterior distribution rather than sampling (Default value = False)
n_samples
how many MC samples to average over for transformed mean (Default value = 5000)
Returns
-------
type
tensor of shape ``(batch_size, n_latent)``
"""
if self.log_variational:
x = torch.log(1 + x)
qz_m, qz_v, z = self.z_encoder(x, batch_index, y) # y only used in VAEC
if give_mean:
if self.latent_distribution == "ln":
samples = Normal(qz_m, qz_v.sqrt()).sample([n_samples])
z = self.z_encoder.z_transformation(samples)
z = z.mean(dim=0)
else:
z = qz_m
return z
def sample_from_posterior_l(self, x, batch_index=None, give_mean=True) -> torch.Tensor:
"""Samples the tensor of library sizes from the posterior
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input)``
batch_index
tensor of study/batch labels with shape ``(batch_size, n_labels)`` (Default value = None)
give_mean
Return mean or sample
Returns
-------
type
tensor of shape ``(batch_size, 1)``
"""
if self.log_variational:
x = torch.log(1 + x)
ql_m, ql_v, library = self.l_encoder(x, batch_index)
if give_mean is False:
library = library
else:
library = torch.distributions.LogNormal(ql_m, ql_v.sqrt()).mean
return library
def get_sample_scale(
self, x, batch_index=None, y=None, n_samples=1, transform_batch=None
) -> torch.Tensor:
"""Returns the tensor of predicted frequencies of expression
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input)``
batch_index
array that indicates which batch the cells belong to with shape ``batch_size`` (Default value = None)
y
tensor of cell-types labels with shape ``(batch_size, n_labels)`` (Default value = None)
n_samples
number of samples (Default value = 1)
transform_batch
int of batch to transform samples into (Default value = None)
Returns
-------
type
tensor of predicted frequencies of expression with shape ``(batch_size, n_input)``
"""
return self.inference(
x,
batch_index=batch_index,
y=y,
n_samples=n_samples,
transform_batch=transform_batch,
)["px_scale"]
def get_sample_rate(
self, x, batch_index=None, y=None, n_samples=1, transform_batch=None
) -> torch.Tensor:
"""Returns the tensor of means of the negative binomial distribution
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input)``
y
tensor of cell-types labels with shape ``(batch_size, n_labels)`` (Default value = None)
batch_index
array that indicates which batch the cells belong to with shape ``batch_size`` (Default value = None)
n_samples
number of samples (Default value = 1)
transform_batch
int of batch to transform samples into (Default value = None)
Returns
-------
type
tensor of means of the negative binomial distribution with shape ``(batch_size, n_input)``
"""
return self.inference(
x,
batch_index=batch_index,
y=y,
n_samples=n_samples,
transform_batch=transform_batch,
)["px_rate"]
def get_reconstruction_loss(
self, x, px_rate, px_r, px_dropout, **kwargs
) -> torch.Tensor:
# Reconstruction Loss
if self.gene_likelihood == "zinb":
reconst_loss = (
-ZeroInflatedNegativeBinomial(
mu=px_rate, theta=px_r, zi_logits=px_dropout
)
.log_prob(x)
.sum(dim=-1)
)
elif self.gene_likelihood == "nb":
reconst_loss = (
-NegativeBinomial(mu=px_rate, theta=px_r).log_prob(x).sum(dim=-1)
)
elif self.gene_likelihood == "poisson":
reconst_loss = -Poisson(px_rate).log_prob(x).sum(dim=-1)
return reconst_loss
def inference(
self, x, batch_index=None, y=None, n_samples=1, transform_batch=None
) -> Dict[str, torch.Tensor]:
"""Helper function used in forward pass
"""
x_ = x
if self.log_variational:
x_ = torch.log(1 + x_)
# Sampling
qz_m, qz_v, z = self.z_encoder(x_, batch_index, y)
ql_m, ql_v, library = self.l_encoder(x_, batch_index)
if n_samples > 1:
qz_m = qz_m.unsqueeze(0).expand((n_samples, qz_m.size(0), qz_m.size(1)))
qz_v = qz_v.unsqueeze(0).expand((n_samples, qz_v.size(0), qz_v.size(1)))
# when z is normal, untran_z == z
untran_z = Normal(qz_m, qz_v.sqrt()).sample()
z = self.z_encoder.z_transformation(untran_z)
ql_m = ql_m.unsqueeze(0).expand((n_samples, ql_m.size(0), ql_m.size(1)))
ql_v = ql_v.unsqueeze(0).expand((n_samples, ql_v.size(0), ql_v.size(1)))
library = Normal(ql_m, ql_v.sqrt()).sample()
if transform_batch is not None:
dec_batch_index = transform_batch * torch.ones_like(batch_index)
else:
dec_batch_index = batch_index
px_scale, px_r, px_rate, px_dropout = self.decoder(
self.dispersion, z, library, dec_batch_index, y
)
if self.dispersion == "gene-label":
px_r = F.linear(
one_hot(y, self.n_labels), self.px_r
) # px_r gets transposed - last dimension is nb genes
elif self.dispersion == "gene-batch":
px_r = F.linear(one_hot(dec_batch_index, self.n_batch), self.px_r)
elif self.dispersion == "gene":
px_r = self.px_r
px_r = torch.exp(px_r)
return dict(
px_scale=px_scale,
px_r=px_r,
px_rate=px_rate,
px_dropout=px_dropout,
qz_m=qz_m,
qz_v=qz_v,
z=z,
ql_m=ql_m,
ql_v=ql_v,
library=library,
)
def forward(
self, x, local_l_mean, local_l_var, batch_index=None, y=None
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Returns the reconstruction loss and the KL divergences
Parameters
----------
x
tensor of values with shape (batch_size, n_input)
local_l_mean
tensor of means of the prior distribution of latent variable l
with shape (batch_size, 1)
local_l_var
tensor of variancess of the prior distribution of latent variable l
with shape (batch_size, 1)
batch_index
array that indicates which batch the cells belong to with shape ``batch_size`` (Default value = None)
y
tensor of cell-types labels with shape (batch_size, n_labels) (Default value = None)
Returns
-------
type
the reconstruction loss and the Kullback divergences
"""
# Parameters for z latent distribution
outputs = self.inference(x, batch_index, y)
qz_m = outputs["qz_m"]
qz_v = outputs["qz_v"]
ql_m = outputs["ql_m"]
ql_v = outputs["ql_v"]
px_rate = outputs["px_rate"]
px_r = outputs["px_r"]
px_dropout = outputs["px_dropout"]
# KL Divergence
mean = torch.zeros_like(qz_m)
scale = torch.ones_like(qz_v)
kl_divergence_z = kl(Normal(qz_m, torch.sqrt(qz_v)), Normal(mean, scale)).sum(
dim=1
)
kl_divergence_l = kl(
Normal(ql_m, torch.sqrt(ql_v)),
Normal(local_l_mean, torch.sqrt(local_l_var)),
).sum(dim=1)
kl_divergence = kl_divergence_z
reconst_loss = self.get_reconstruction_loss(x, px_rate, px_r, px_dropout)
return reconst_loss + kl_divergence_l, kl_divergence, 0.0
|
/scArchest-0.0.1-py3-none-any.whl/scarches/models/scvi/scvi.py
| 0.960519 | 0.525978 |
scvi.py
|
pypi
|
"""Main module."""
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.distributions import Normal, kl_divergence as kl
from typing import Dict, Optional, Tuple, Union, List
from scvi.core._distributions import ZeroInflatedNegativeBinomial, NegativeBinomial
from scvi.core._log_likelihood import log_mixture_nb
from scvi.core.modules.utils import one_hot
from scarchest.models.scvi._base import DecoderTOTALVI, EncoderTOTALVI
torch.backends.cudnn.benchmark = True
# VAE model
class totalVI(nn.Module):
"""
Total variational inference for CITE-seq data.
Implements the totalVI model of [GayosoSteier20]_.
Parameters
----------
n_input_genes
Number of input genes
n_input_proteins
Number of input proteins
n_batch
Number of batches
n_labels
Number of labels
n_hidden
Number of nodes per hidden layer for encoder and decoder
n_latent
Dimensionality of the latent space
n_layers
Number of hidden layers used for encoder and decoder NNs
dropout_rate
Dropout rate for neural networks
genes_dispersion
One of the following
* ``'gene'`` - genes_dispersion parameter of NB is constant per gene across cells
* ``'gene-batch'`` - genes_dispersion can differ between different batches
* ``'gene-label'`` - genes_dispersion can differ between different labels
protein_dispersion
One of the following
* ``'protein'`` - protein_dispersion parameter is constant per protein across cells
* ``'protein-batch'`` - protein_dispersion can differ between different batches NOT TESTED
* ``'protein-label'`` - protein_dispersion can differ between different labels NOT TESTED
log_variational
Log(data+1) prior to encoding for numerical stability. Not normalization.
gene_likelihood
One of
* ``'nb'`` - Negative binomial distribution
* ``'zinb'`` - Zero-inflated negative binomial distribution
latent_distribution
One of
* ``'normal'`` - Isotropic normal
* ``'ln'`` - Logistic normal with normal params N(0, 1)
"""
def __init__(
self,
n_input_genes: int,
n_input_proteins: int,
n_batch: int = 0,
n_labels: int = 0,
n_hidden: int = 256,
n_latent: int = 20,
n_layers_encoder: int = 1,
n_layers_decoder: int = 1,
dropout_rate_decoder: float = 0.2,
dropout_rate_encoder: float = 0.2,
gene_dispersion: str = "gene",
protein_dispersion: str = "protein",
log_variational: bool = True,
gene_likelihood: str = "nb",
latent_distribution: str = "ln",
protein_batch_mask: List[np.ndarray] = None,
encoder_batch: bool = True,
):
super().__init__()
self.gene_dispersion = gene_dispersion
self.n_latent = n_latent
self.log_variational = log_variational
self.gene_likelihood = gene_likelihood
self.n_batch = n_batch
self.n_labels = n_labels
self.n_input_genes = n_input_genes
self.n_input_proteins = n_input_proteins
self.protein_dispersion = protein_dispersion
self.latent_distribution = latent_distribution
self.protein_batch_mask = protein_batch_mask
# parameters for prior on rate_back (background protein mean)
if n_batch > 0:
self.background_pro_alpha = torch.nn.Parameter(
torch.randn(n_input_proteins, n_batch)
)
self.background_pro_log_beta = torch.nn.Parameter(
torch.clamp(torch.randn(n_input_proteins, n_batch), -10, 1)
)
else:
self.background_pro_alpha = torch.nn.Parameter(
torch.randn(n_input_proteins)
)
self.background_pro_log_beta = torch.nn.Parameter(
torch.clamp(torch.randn(n_input_proteins), -10, 1)
)
if self.gene_dispersion == "gene":
self.px_r = torch.nn.Parameter(torch.randn(n_input_genes))
elif self.gene_dispersion == "gene-batch":
self.px_r = torch.nn.Parameter(torch.randn(n_input_genes, n_batch))
elif self.gene_dispersion == "gene-label":
self.px_r = torch.nn.Parameter(torch.randn(n_input_genes, n_labels))
else: # gene-cell
pass
if self.protein_dispersion == "protein":
self.py_r = torch.nn.Parameter(torch.ones(self.n_input_proteins))
elif self.protein_dispersion == "protein-batch":
self.py_r = torch.nn.Parameter(torch.ones(self.n_input_proteins, n_batch))
elif self.protein_dispersion == "protein-label":
self.py_r = torch.nn.Parameter(torch.ones(self.n_input_proteins, n_labels))
else: # protein-cell
pass
# z encoder goes from the n_input-dimensional data to an n_latent-d
# latent space representation
self.encoder = EncoderTOTALVI(
n_input_genes + self.n_input_proteins,
n_latent,
n_layers=n_layers_encoder,
n_cat_list=[n_batch] if encoder_batch else None,
n_hidden=n_hidden,
dropout_rate=dropout_rate_encoder,
distribution=latent_distribution,
)
self.decoder = DecoderTOTALVI(
n_latent,
n_input_genes,
self.n_input_proteins,
n_layers=n_layers_decoder,
n_cat_list=[n_batch],
n_hidden=n_hidden,
dropout_rate=dropout_rate_decoder,
)
def sample_from_posterior_z(
self,
x: torch.Tensor,
y: torch.Tensor,
batch_index: Optional[torch.Tensor] = None,
give_mean: bool = False,
n_samples: int = 5000,
) -> torch.Tensor:
"""
Access the tensor of latent values from the posterior.
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input_genes)``
y
tensor of values with shape ``(batch_size, n_input_proteins)``
batch_index
tensor of batch indices
give_mean
Whether to sample, or give mean of distribution
n_samples
Number of samples for monte carlo estimation
Returns
-------
type
tensor of shape ``(batch_size, n_latent)``
"""
if self.log_variational:
x = torch.log(1 + x)
y = torch.log(1 + y)
qz_m, qz_v, _, _, latent, _ = self.encoder(
torch.cat((x, y), dim=-1), batch_index
)
z = latent["z"]
if give_mean:
if self.latent_distribution == "ln":
samples = Normal(qz_m, qz_v.sqrt()).sample([n_samples])
z = self.encoder.z_transformation(samples)
z = z.mean(dim=0)
else:
z = qz_m
return z
def sample_from_posterior_l(
self,
x: torch.Tensor,
y: torch.Tensor,
batch_index: Optional[torch.Tensor] = None,
give_mean: bool = True,
) -> torch.Tensor:
"""
Provides the tensor of library size from the posterior.
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input_genes)``
y
tensor of values with shape ``(batch_size, n_input_proteins)``
batch_index
tensor of values with shape ``(batch_size, 1)``
give_mean
return mean of l or sample from it
Returns
-------
type
tensor of shape ``(batch_size, 1)``
"""
if self.log_variational:
x = torch.log(1 + x)
y = torch.log(1 + y)
_, _, ql_m, ql_v, latent, _ = self.encoder(
torch.cat((x, y), dim=-1), batch_index
)
library_gene = latent["l"]
if give_mean is True:
return torch.exp(ql_m + 0.5 * ql_v)
else:
return library_gene
def get_sample_dispersion(
self,
x: torch.Tensor,
y: torch.Tensor,
batch_index: Optional[torch.Tensor] = None,
label: Optional[torch.Tensor] = None,
n_samples: int = 1,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Returns the tensors of dispersions for genes and proteins.
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input_genes)``
y
tensor of values with shape ``(batch_size, n_input_proteins)``
batch_index
array that indicates which batch the cells belong to with shape ``batch_size``
label
tensor of cell-types labels with shape ``(batch_size, n_labels)``
n_samples
number of samples
Returns
-------
type
tensors of dispersions of the negative binomial distribution
"""
outputs = self.inference(
x, y, batch_index=batch_index, label=label, n_samples=n_samples
)
px_r = outputs["px_"]["r"]
py_r = outputs["py_"]["r"]
return px_r, py_r
def get_reconstruction_loss(
self,
x: torch.Tensor,
y: torch.Tensor,
px_dict: Dict[str, torch.Tensor],
py_dict: Dict[str, torch.Tensor],
pro_batch_mask_minibatch: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Compute reconstruction loss."""
px_ = px_dict
py_ = py_dict
# Reconstruction Loss
if self.gene_likelihood == "zinb":
reconst_loss_gene = (
-ZeroInflatedNegativeBinomial(
mu=px_["rate"], theta=px_["r"], zi_logits=px_["dropout"]
)
.log_prob(x)
.sum(dim=-1)
)
else:
reconst_loss_gene = (
-NegativeBinomial(mu=px_["rate"], theta=px_["r"])
.log_prob(x)
.sum(dim=-1)
)
reconst_loss_protein_full = -log_mixture_nb(
y, py_["rate_back"], py_["rate_fore"], py_["r"], None, py_["mixing"]
)
if pro_batch_mask_minibatch is not None:
temp_pro_loss_full = torch.zeros_like(reconst_loss_protein_full)
temp_pro_loss_full.masked_scatter_(
pro_batch_mask_minibatch.bool(), reconst_loss_protein_full
)
reconst_loss_protein = temp_pro_loss_full.sum(dim=-1)
else:
reconst_loss_protein = reconst_loss_protein_full.sum(dim=-1)
return reconst_loss_gene, reconst_loss_protein
def inference(
self,
x: torch.Tensor,
y: torch.Tensor,
batch_index: Optional[torch.Tensor] = None,
label: Optional[torch.Tensor] = None,
n_samples=1,
transform_batch: Optional[int] = None,
) -> Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]]:
"""
Internal helper function to compute necessary inference quantities.
We use the dictionary ``px_`` to contain the parameters of the ZINB/NB for genes.
The rate refers to the mean of the NB, dropout refers to Bernoulli mixing parameters.
`scale` refers to the quanity upon which differential expression is performed. For genes,
this can be viewed as the mean of the underlying gamma distribution.
We use the dictionary ``py_`` to contain the parameters of the Mixture NB distribution for proteins.
`rate_fore` refers to foreground mean, while `rate_back` refers to background mean. ``scale`` refers to
foreground mean adjusted for background probability and scaled to reside in simplex.
``back_alpha`` and ``back_beta`` are the posterior parameters for ``rate_back``. ``fore_scale`` is the scaling
factor that enforces `rate_fore` > `rate_back`.
``px_["r"]`` and ``py_["r"]`` are the inverse dispersion parameters for genes and protein, respectively.
"""
x_ = x
y_ = y
if self.log_variational:
x_ = torch.log(1 + x_)
y_ = torch.log(1 + y_)
# Sampling - Encoder gets concatenated genes + proteins
qz_m, qz_v, ql_m, ql_v, latent, untran_latent = self.encoder(
torch.cat((x_, y_), dim=-1), batch_index
)
z = latent["z"]
library_gene = latent["l"]
untran_z = untran_latent["z"]
untran_l = untran_latent["l"]
if n_samples > 1:
qz_m = qz_m.unsqueeze(0).expand((n_samples, qz_m.size(0), qz_m.size(1)))
qz_v = qz_v.unsqueeze(0).expand((n_samples, qz_v.size(0), qz_v.size(1)))
untran_z = Normal(qz_m, qz_v.sqrt()).sample()
z = self.encoder.z_transformation(untran_z)
ql_m = ql_m.unsqueeze(0).expand((n_samples, ql_m.size(0), ql_m.size(1)))
ql_v = ql_v.unsqueeze(0).expand((n_samples, ql_v.size(0), ql_v.size(1)))
untran_l = Normal(ql_m, ql_v.sqrt()).sample()
library_gene = self.encoder.l_transformation(untran_l)
if self.gene_dispersion == "gene-label":
# px_r gets transposed - last dimension is nb genes
px_r = F.linear(one_hot(label, self.n_labels), self.px_r)
elif self.gene_dispersion == "gene-batch":
px_r = F.linear(one_hot(batch_index, self.n_batch), self.px_r)
elif self.gene_dispersion == "gene":
px_r = self.px_r
px_r = torch.exp(px_r)
if self.protein_dispersion == "protein-label":
# py_r gets transposed - last dimension is n_proteins
py_r = F.linear(one_hot(label, self.n_labels), self.py_r)
elif self.protein_dispersion == "protein-batch":
py_r = F.linear(one_hot(batch_index, self.n_batch), self.py_r)
elif self.protein_dispersion == "protein":
py_r = self.py_r
py_r = torch.exp(py_r)
# Background regularization
if self.n_batch > 0:
py_back_alpha_prior = F.linear(
one_hot(batch_index, self.n_batch), self.background_pro_alpha
)
py_back_beta_prior = F.linear(
one_hot(batch_index, self.n_batch),
torch.exp(self.background_pro_log_beta),
)
else:
py_back_alpha_prior = self.background_pro_alpha
py_back_beta_prior = torch.exp(self.background_pro_log_beta)
self.back_mean_prior = Normal(py_back_alpha_prior, py_back_beta_prior)
if transform_batch is not None:
batch_index = torch.ones_like(batch_index) * transform_batch
px_, py_, log_pro_back_mean = self.decoder(z, library_gene, batch_index, label)
px_["r"] = px_r
py_["r"] = py_r
return dict(
px_=px_,
py_=py_,
qz_m=qz_m,
qz_v=qz_v,
z=z,
untran_z=untran_z,
ql_m=ql_m,
ql_v=ql_v,
library_gene=library_gene,
untran_l=untran_l,
log_pro_back_mean=log_pro_back_mean,
)
def forward(
self,
x: torch.Tensor,
y: torch.Tensor,
local_l_mean_gene: torch.Tensor,
local_l_var_gene: torch.Tensor,
batch_index: Optional[torch.Tensor] = None,
label: Optional[torch.Tensor] = None,
) -> Tuple[
torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor
]:
"""
Returns the reconstruction loss and the Kullback divergences.
Parameters
----------
x
tensor of values with shape ``(batch_size, n_input_genes)``
y
tensor of values with shape ``(batch_size, n_input_proteins)``
local_l_mean_gene
tensor of means of the prior distribution of latent variable l
with shape ``(batch_size, 1)````
local_l_var_gene
tensor of variancess of the prior distribution of latent variable l
with shape ``(batch_size, 1)``
batch_index
array that indicates which batch the cells belong to with shape ``batch_size``
label
tensor of cell-types labels with shape (batch_size, n_labels)
Returns
-------
type
the reconstruction loss and the Kullback divergences
"""
# Parameters for z latent distribution
outputs = self.inference(x, y, batch_index, label)
qz_m = outputs["qz_m"]
qz_v = outputs["qz_v"]
ql_m = outputs["ql_m"]
ql_v = outputs["ql_v"]
px_ = outputs["px_"]
py_ = outputs["py_"]
if self.protein_batch_mask is not None:
pro_batch_mask_minibatch = torch.zeros_like(y)
for b in np.arange(len(torch.unique(batch_index))):
b_indices = (batch_index == b).reshape(-1)
pro_batch_mask_minibatch[b_indices] = torch.tensor(
self.protein_batch_mask[b].astype(np.float32), device=y.device
)
else:
pro_batch_mask_minibatch = None
reconst_loss_gene, reconst_loss_protein = self.get_reconstruction_loss(
x, y, px_, py_, pro_batch_mask_minibatch
)
# KL Divergence
kl_div_z = kl(Normal(qz_m, torch.sqrt(qz_v)), Normal(0, 1)).sum(dim=1)
kl_div_l_gene = kl(
Normal(ql_m, torch.sqrt(ql_v)),
Normal(local_l_mean_gene, torch.sqrt(local_l_var_gene)),
).sum(dim=1)
kl_div_back_pro_full = kl(
Normal(py_["back_alpha"], py_["back_beta"]), self.back_mean_prior
)
if pro_batch_mask_minibatch is not None:
kl_div_back_pro = (pro_batch_mask_minibatch * kl_div_back_pro_full).sum(
dim=1
)
else:
kl_div_back_pro = kl_div_back_pro_full.sum(dim=1)
return (
reconst_loss_gene,
reconst_loss_protein,
kl_div_z,
kl_div_l_gene,
kl_div_back_pro,
)
|
/scArchest-0.0.1-py3-none-any.whl/scarches/models/scvi/totalvi.py
| 0.956012 | 0.525795 |
totalvi.py
|
pypi
|
from typing import Optional
import torch
import torch.nn as nn
from scarchest.models.trvae._utils import one_hot_encoder
from .activations import ACTIVATIONS
from .losses import mse, kl
import numpy as np
def dense_block(i, in_features, out_features, use_batchnorm, dropout_rate, activation):
model = nn.Sequential()
model.add_module(name=f"FC_{i}",
module=nn.Linear(in_features, out_features, bias=False))
if use_batchnorm:
model.add_module(f"BN_{i}", module=nn.BatchNorm1d(out_features, affine=True))
model.add_module(name=f"ACT_{i}", module=ACTIVATIONS[activation])
if dropout_rate > 0:
model.add_module(name=f"DR_{i}", module=nn.Dropout(p=dropout_rate))
return model
class MARS(nn.Module):
def __init__(self, x_dim: int,
conditions: Optional[list] = [],
architecture: list = [128, 32],
z_dim: int = 10,
alpha=1e-3,
activation: str = 'elu',
output_activation: str = 'relu',
use_batchnorm: bool = False,
dropout_rate: float = 0.2):
super(MARS, self).__init__()
self.x_dim = x_dim
self.conditions = conditions if isinstance(conditions, list) else []
self.n_conditions = len(self.conditions)
self.condition_encoder = {k: v for k, v in zip(self.conditions, range(self.n_conditions))}
self.z_dim = z_dim
self.alpha = alpha
self.architecture = architecture
self.use_batchnorm = use_batchnorm
self.dropout_rate = dropout_rate
self.activation = activation
self.output_activation = output_activation
self.encoder_architecture = [self.x_dim + self.n_conditions] + self.architecture
self.decoder_architecture = [self.z_dim + self.n_conditions] + list(reversed(self.architecture))
self.encoder = nn.Sequential(
*[dense_block(i, in_size, out_size, use_batchnorm, dropout_rate, activation) for i, (in_size, out_size) in
enumerate(zip(self.encoder_architecture[:-1], self.encoder_architecture[1:]))])
self.mean = nn.Linear(self.encoder_architecture[-1], self.z_dim)
self.log_var = nn.Linear(self.encoder_architecture[-1], self.z_dim)
self.decoder = nn.Sequential(
*[dense_block(i, in_size, out_size, use_batchnorm, dropout_rate, activation) for i, (in_size, out_size) in
enumerate(zip(self.decoder_architecture[:-1], self.decoder_architecture[1:]))])
self.decoder.add_module(name='X_hat',
module=dense_block('X_hat', self.decoder_architecture[-1], self.x_dim, use_batchnorm,
dropout_rate, self.output_activation))
def sampling(self, mu, log_var):
"""Samples from standard Normal distribution and applies re-parametrization trick.
It is actually sampling from latent space distributions with N(mu, var), computed by encoder.
Parameters
----------
mu: torch.Tensor
Torch Tensor of Means.
log_var: torch.Tensor
Torch Tensor of log. variances.
Returns
-------
Torch Tensor of sampled data.
"""
std = torch.exp(0.5 * log_var)
eps = torch.randn_like(std)
return eps.mul(std).add(mu)
def forward(self, x, c=None):
if c is not None:
c = one_hot_encoder(c, n_cls=self.n_conditions)
xc = torch.cat((x, c), dim=-1)
else:
xc = x
encoded = self.encoder(xc)
mean_encoded = self.mean(encoded)
log_var_encoded = self.log_var(encoded)
encoded = self.sampling(mean_encoded, log_var_encoded)
if c is not None:
ec = torch.cat((encoded, c), dim=-1)
else:
ec = encoded
decoded = self.decoder(ec)
kl_loss = kl(mean_encoded, log_var_encoded)
recon_loss = mse(decoded, x) # TODO: support other loss functions
loss = recon_loss + self.alpha * kl_loss
return encoded, decoded, loss, recon_loss, kl_loss
def get_latent(self, x, c=None):
x = torch.as_tensor(np.array(x).astype(np.float)).type(torch.float32)
if c is not None:
c = torch.as_tensor(np.array(c).astype(np.int))
c = one_hot_encoder(c, n_cls=self.n_conditions)
xc = torch.cat((x, c), dim=-1)
else:
xc = x
encoded = self.encoder(xc)
mean_encoded = self.mean(encoded)
log_var_encoded = self.log_var(encoded)
encoded = self.sampling(mean_encoded, log_var_encoded)
return encoded.cpu().data.numpy()
|
/scArchest-0.0.1-py3-none-any.whl/scarches/models/mars/mars.py
| 0.94285 | 0.396127 |
mars.py
|
pypi
|
import torch
import numpy as np
from functools import partial
from torch.autograd import Variable
from ._utils import partition
def _nan2inf(x):
return torch.where(torch.isnan(x), torch.zeros_like(x) + np.inf, x)
def _nan2zero(x):
return torch.where(torch.isnan(x), torch.zeros_like(x), x)
def kl(mu, logvar):
"""Computes KL loss between tensor of means, log. variances and zero mean, unit variance.
Parameters
----------
mu: Tensor
Torch Tensor of means
logvar: Tensor
Torch Tensor of log. variances
Returns
-------
KL loss value
"""
kl_loss = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp(), )
kl_loss = kl_loss / mu.size(0)
return kl_loss
def mse(recon_x, x):
"""Computes MSE loss between reconstructed data and ground truth data.
Parameters
----------
recon_x: Tensor
Torch Tensor of reconstructed data
x: Tensor
Torch Tensor of ground truth data
Returns
-------
MSE loss value
"""
mse_loss = torch.nn.functional.mse_loss(recon_x, x, reduction="mean")
return mse_loss
def nb(x, mu, theta, eps=1e-8, mean=True):
"""Computes negative binomial loss.
Parameters
----------
x: Tensor
Torch Tensor of ground truth data.
mu: Tensor
Torch Tensor of means of the negative binomial (has to be positive support).
theta: Tensor
Torch Tensor of inverse dispersion parameter (has to be positive support).
eps: Float
numerical stability constant.
mean: boolean
If 'True' NB loss value gets returned, if 'False' NB loss Tensor gets returned with same shape as 'x'
(needed for ZINB loss calculation).
Returns
-------
If 'mean' is 'True' NB loss value gets returned, otherwise Torch tensor of losses gets returned.
"""
if theta.ndimension() == 1:
theta = theta.view(1, theta.size(0)) # In this case, we reshape theta for broadcasting
t1 = torch.lgamma(theta + eps) + torch.lgamma(x + 1.0) - torch.lgamma(x + theta + eps)
t2 = (theta + x) * torch.log(1.0 + (mu / (theta + eps))) + (x * (torch.log(theta + eps) - torch.log(mu + eps)))
final = t1 + t2
final = _nan2inf(final)
if mean:
final = torch.mean(final)
return final
def zinb(x, mu, theta, pi, eps=1e-8, ridge_lambda=0.0, mean=True):
"""Computes zero inflated negative binomial loss.
Parameters
----------
x: Tensor
Torch Tensor of ground truth data.
mu: Tensor
Torch Tensor of means of the negative binomial (has to be positive support).
theta: Tensor
Torch Tensor of inverses dispersion parameter (has to be positive support).
pi: Tensor
Torch Tensor of logits of the dropout parameter (real support)
eps: Float
numerical stability constant.
ridge_lambda: Float
Ridge Coefficient.
mean: boolean
If 'True' NB loss value gets returned, if 'False' NB loss Tensor gets returned with same shape as 'x'
(needed for ZINB loss calculation).
Returns
-------
If 'mean' is 'True' ZINB loss value gets returned, otherwise Torch tensor of losses gets returned.
"""
nb_case = nb(x, mu, theta, mean=False) - torch.log(1.0 - pi + eps)
if theta.ndimension() == 1:
theta = theta.view(1, theta.size(0)) # In this case, we reshape theta for broadcasting
zero_nb = torch.pow(theta / (theta + mu + eps), theta)
zero_case = -torch.log(pi + ((1.0 - pi) * zero_nb) + eps)
result = torch.where((x < 1e-8), zero_case, nb_case)
ridge = ridge_lambda * torch.square(pi)
result += ridge
if mean:
result = torch.mean(result)
result = _nan2inf(result)
return result
def pairwise_distance(x, y):
if not len(x.shape) == len(y.shape) == 2:
raise ValueError('Both inputs should be matrices.')
if x.shape[1] != y.shape[1]:
raise ValueError('The number of features should be the same.')
x = x.view(x.shape[0], x.shape[1], 1)
y = torch.transpose(y, 0, 1)
output = torch.sum((x - y) ** 2, 1)
output = torch.transpose(output, 0, 1)
return output
def gaussian_kernel_matrix(x, y, sigmas):
"""Computes multiscale-RBF kernel between x and y.
Parameters
----------
x: Tensor
Tensor with shape [batch_size, z_dim].
y: Tensor
Tensor with shape [batch_size, z_dim].
sigmas: Tensor
Returns
-------
Returns the computed multiscale-RBF kernel between x and y.
"""
sigmas = sigmas.view(sigmas.shape[0], 1)
beta = 1. / (2. * sigmas)
dist = pairwise_distance(x, y).contiguous()
dist_ = dist.view(1, -1)
s = torch.matmul(beta, dist_)
return torch.sum(torch.exp(-s), 0).view_as(dist)
def maximum_mean_discrepancy(x, y, kernel=gaussian_kernel_matrix):
"""Computes Maximum Mean Discrepancy(MMD) between x and y.
Parameters
----------
x: Tensor
Tensor with shape [batch_size, z_dim]
y: Tensor
Tensor with shape [batch_size, z_dim]
kernel: gaussian_kernel_matrix
Returns
-------
Returns the computed MMD between x and y.
"""
cost = torch.mean(kernel(x, x))
cost += torch.mean(kernel(y, y))
cost -= 2 * torch.mean(kernel(x, y))
return cost
def mmd_loss_calc(source_features, target_features):
"""Initializes Maximum Mean Discrepancy(MMD) between source_features and target_features.
Parameters
----------
source_features: Tensor
Tensor with shape [batch_size, z_dim]
target_features: Tensor
Tensor with shape [batch_size, z_dim]
Returns
-------
Returns the computed MMD between x and y.
"""
sigmas = [
1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1, 5, 10, 15, 20, 25, 30, 35, 100,
1e3, 1e4, 1e5, 1e6
]
if torch.cuda.is_available():
gaussian_kernel = partial(
gaussian_kernel_matrix, sigmas=Variable(torch.cuda.FloatTensor(sigmas))
)
else:
gaussian_kernel = partial(
gaussian_kernel_matrix, sigmas=Variable(torch.FloatTensor(sigmas))
)
loss_value = maximum_mean_discrepancy(source_features, target_features, kernel=gaussian_kernel)
return loss_value
def mmd(n_conditions, beta, boundary):
"""Initializes Maximum Mean Discrepancy(MMD) between every different condition.
Parameters
----------
n_conditions: integer
Number of classes (conditions) the data contain.
beta: float
beta coefficient for MMD loss.
boundary: integer
If not 'None', mmd loss is only calculated on #new conditions.
y: Tensor
Torch Tensor of computed latent data.
c: Tensor
Torch Tensor of labels
Returns
-------
Returns MMD loss.
"""
def mmd_loss(y, c):
# partition separates y into num_cls subsets w.r.t. their labels c
conditions_mmd = partition(y, c, n_conditions)
loss = 0.0
if boundary is not None:
for i in range(boundary):
for j in range(boundary, n_conditions):
if conditions_mmd[i].size(0) < 2 or conditions_mmd[j].size(0) < 2:
continue
loss += mmd_loss_calc(conditions_mmd[i], conditions_mmd[j])
else:
for i in range(len(conditions_mmd)):
if conditions_mmd[i].size(0) < 1:
continue
for j in range(i):
if conditions_mmd[j].size(0) < 1 or i == j:
continue
loss += mmd_loss_calc(conditions_mmd[i], conditions_mmd[j])
return beta * loss
return mmd_loss
|
/scArchest-0.0.1-py3-none-any.whl/scarches/models/trvae/losses.py
| 0.952386 | 0.853547 |
losses.py
|
pypi
|
import torch
import torch.nn as nn
from ._utils import one_hot_encoder
class CondLayers(nn.Module):
def __init__(
self,
n_in: int,
n_out: int,
n_cond: int,
bias: bool = True,
):
super().__init__()
self.n_cond = n_cond
self.expr_L = nn.Linear(n_in, n_out, bias=bias)
if self.n_cond != 0:
self.cond_L = nn.Linear(self.n_cond, n_out, bias=False)
def forward(self, x: torch.Tensor):
if self.n_cond == 0:
out = self.expr_L(x)
else:
expr, cond = torch.split(x, x.shape[1] - self.n_cond, dim=1)
out = self.expr_L(expr) + self.cond_L(cond)
return out
class Encoder(nn.Module):
"""Scnet Encoder class. Constructs the encoder sub-network of scNet. It will transform primary space input to means
and log. variances of latent space with n_dimensions = z_dimension.
Parameters
----------
layer_sizes: List
List of first and hidden layer sizes
latent_dim: Integer
Bottleneck layer (z) size.
use_bn: Boolean
If `True` batch normalization will applied to layers.
use_dr: Boolean
If `True` dropout will applied to layers.
dr_rate: Float
Dropput rate applied to all layers, if `dr_rate`==0 no dropput will be applied.
num_classes: Integer
Number of classes (conditions) the data contain. if `None` the model will be a normal VAE instead of
conditional VAE.
Returns
-------
"""
def __init__(self, layer_sizes, latent_dim,
use_bn, use_dr, dr_rate, num_classes=None):
super().__init__()
self.n_classes = 0
if num_classes is not None:
self.n_classes = num_classes
self.FC = None
if len(layer_sizes) > 1:
print("Encoder Architecture:")
self.FC = nn.Sequential()
for i, (in_size, out_size) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):
if i == 0:
print("\tInput Layer in, out and cond:", in_size, out_size, self.n_classes)
self.FC.add_module(name="L{:d}".format(i), module=CondLayers(in_size,
out_size,
self.n_classes,
bias=False))
else:
print("\tHidden Layer", i, "in/out:", in_size, out_size)
self.FC.add_module(name="L{:d}".format(i), module=nn.Linear(in_size, out_size, bias=False))
if use_bn:
self.FC.add_module("B{:d}".format(i), module=nn.BatchNorm1d(out_size, affine=True))
self.FC.add_module(name="A{:d}".format(i), module=nn.ReLU())
if use_dr:
self.FC.add_module(name="D{:d}".format(i), module=nn.Dropout(p=dr_rate))
print("\tMean/Var Layer in/out:", layer_sizes[-1], latent_dim)
self.mean_encoder = nn.Linear(layer_sizes[-1], latent_dim)
self.log_var_encoder = nn.Linear(layer_sizes[-1], latent_dim)
def forward(self, x, c=None):
if c is not None:
c = one_hot_encoder(c, n_cls=self.n_classes)
x = torch.cat((x, c), dim=-1)
if self.FC is not None:
x = self.FC(x)
means = self.mean_encoder(x)
log_vars = self.log_var_encoder(x)
return means, log_vars
class Decoder(nn.Module):
"""Scnet Decoder class. Constructs the decoder sub-network of scNet. It will transform constructed latent space to
the previous space of data with n_dimensions = x_dimension.
Parameters
----------
layer_sizes: List
List of hidden and last layer sizes
latent_dim: Integer
Bottleneck layer (z) size.
recon_loss: String
Definition of Reconstruction-Loss-Method, 'mse', 'nb' or 'zinb'.
use_bn: Boolean
If `True` batch normalization will applied to layers.
use_dr: Boolean
If `True` dropout will applied to layers.
dr_rate: Float
Dropput rate applied to all layers, if `dr_rate`==0 no dropput will be applied.
use_mmd: boolean
If `True` then MMD will be applied to first decoder layer.
num_classes: Integer
Number of classes (conditions) the data contain. if `None` the model will be a normal VAE instead of
conditional VAE.
output_active: String
Defines the Activation for the last layer of decoder if 'recon_loss' is 'mse'.
Returns
-------
"""
def __init__(self, layer_sizes, latent_dim, recon_loss, use_bn, use_dr, dr_rate, use_mmd=False, num_classes=None):
super().__init__()
self.use_mmd = use_mmd
self.use_bn = use_bn
self.use_dr = use_dr
self.recon_loss = recon_loss
self.n_classes = 0
if num_classes is not None:
self.n_classes = num_classes
layer_sizes = [latent_dim] + layer_sizes
print("Decoder Architecture:")
# Create first Decoder layer
self.FirstL = nn.Sequential()
print("\tFirst Layer in/out: ", layer_sizes[0], layer_sizes[1])
self.FirstL.add_module(name="L0", module=CondLayers(layer_sizes[0], layer_sizes[1], self.n_classes, bias=False))
if self.use_bn:
self.FirstL.add_module("B0", module=nn.BatchNorm1d(layer_sizes[1], affine=True))
self.FirstL.add_module(name="A0", module=nn.ReLU())
if self.use_dr:
self.FirstL.add_module(name="D0", module=nn.Dropout(p=dr_rate))
# Create all Decoder hidden layers
if len(layer_sizes) > 2:
self.HiddenL = nn.Sequential()
for i, (in_size, out_size) in enumerate(zip(layer_sizes[1:-1], layer_sizes[2:])):
if i+3 < len(layer_sizes):
print("\tHidden Layer", i+1, "in/out:", in_size, out_size)
self.HiddenL.add_module(name="L{:d}".format(i+1), module=nn.Linear(in_size, out_size, bias=False))
if self.use_bn:
self.HiddenL.add_module("B{:d}".format(i+1), module=nn.BatchNorm1d(out_size, affine=True))
self.HiddenL.add_module(name="A{:d}".format(i+1), module=nn.ReLU())
if self.use_dr:
self.HiddenL.add_module(name="D{:d}".format(i+1), module=nn.Dropout(p=dr_rate))
else:
self.HiddenL = None
# Create Output Layers
print("\tOutput Layer in/out: ", layer_sizes[-2], layer_sizes[-1], "\n")
if self.recon_loss == "mse":
self.OutputLayer = nn.Sequential()
self.OutputLayer.add_module(name="outputL", module=nn.Linear(layer_sizes[-2], layer_sizes[-1]))
self.OutputLayer.add_module(name="outputA", module=nn.ReLU())
if self.recon_loss == "zinb":
# mean gamma
self.mean_decoder = nn.Linear(layer_sizes[-2], layer_sizes[-1])
# dispersion: here we only deal with gene-cell dispersion case
self.disp_decoder = nn.Sequential(nn.Linear(layer_sizes[-2], layer_sizes[-1]), nn.Softplus())
# dropout
self.dropout_decoder = nn.Sequential(nn.Linear(layer_sizes[-2], layer_sizes[-1]), nn.Sigmoid())
if self.recon_loss == "nb":
# mean gamma
self.mean_decoder = nn.Linear(layer_sizes[-2], layer_sizes[-1])
# dispersion: here we only deal with gene-cell dispersion case
self.disp_decoder = nn.Sequential(nn.Linear(layer_sizes[-2], layer_sizes[-1]), nn.Softplus())
def forward(self, z, c=None):
# Add Condition Labels to Decoder Input
if c is not None:
c = one_hot_encoder(c, n_cls=self.n_classes)
z_cat = torch.cat((z, c), dim=-1)
dec_latent = self.FirstL(z_cat)
else:
dec_latent = self.FirstL(z)
# Compute Hidden Output
if self.HiddenL is not None:
x = self.HiddenL(dec_latent)
else:
x = dec_latent
# Compute Decoder Output
if self.recon_loss == "mse":
output = self.OutputLayer(x)
return output, dec_latent
if self.recon_loss == "zinb":
# Parameters for ZINB and NB
dec_mean_gamma = self.mean_decoder(x)
dec_mean_gamma = torch.clamp(torch.exp(dec_mean_gamma), min=1e-4, max=1e4)
dec_disp = self.disp_decoder(x)
dec_disp = torch.clamp(dec_disp, min=1e-6, max=1e6)
dec_dropout = self.dropout_decoder(x)
return dec_mean_gamma, dec_dropout, dec_disp, dec_latent
if self.recon_loss == "nb":
# Parameters for ZINB and NB
dec_mean_gamma = self.mean_decoder(x)
dec_mean_gamma = torch.clamp(torch.exp(dec_mean_gamma), min=1e-4, max=1e4)
dec_disp = self.disp_decoder(x)
dec_disp = torch.clamp(dec_disp, min=1e-6, max=1e6)
return dec_mean_gamma, dec_disp, dec_latent
|
/scArchest-0.0.1-py3-none-any.whl/scarches/models/trvae/modules.py
| 0.954276 | 0.410756 |
modules.py
|
pypi
|
from typing import Optional
import torch
import torch.nn as nn
from .modules import Encoder, Decoder
from .losses import mse, mmd, zinb, nb, kl
class trVAE(nn.Module):
"""scNet class. This class contains the implementation of Conditional Variational Auto-encoder.
Parameters
----------
input_dim: integer
Number of input features (i.e. gene in case of scRNA-seq).
conditions: integer
Number of classes (conditions) the data contain. if `None` the model will be a normal VAE instead of
conditional VAE.
encoder_layer_sizes: List
A list of hidden layer sizes for encoder network.
latent_dim: integer
Bottleneck layer (z) size.
decoder_layer_sizes: List
A list of hidden layer sizes for decoder network.
recon_loss: String
Definition of Reconstruction-Loss-Method, 'mse', 'nb' or 'zinb'.
alpha: float
Alpha coefficient for KL loss.
use_batch_norm: boolean
If `True` batch normalization will applied to hidden layers.
dr_rate: float
Dropput rate applied to all layers, if `dr_rate`==0 no dropput will be applied.
use_mmd: boolean
If `True` then MMD will be applied to first decoder layer.
beta: float
beta coefficient for MMD loss.
eta: float
Eta coefficient for Reconstruction loss.
calculate_mmd: String
Defines the layer which the mmd loss is calculated on, 'y' for first layer of decoder or 'z' for bottleneck
layer.
"""
def __init__(self,
input_dim: int,
conditions: list,
encoder_layer_sizes: list = [256, 64],
latent_dim: int = 32,
decoder_layer_sizes: list = [64, 256],
dr_rate: float = 0.05,
use_batch_norm: bool = False,
calculate_mmd: Optional[str] = 'z',
mmd_boundary: Optional[int] = None,
recon_loss: Optional[str] = 'zinb',
alpha: Optional[float] = 0.0005,
beta: Optional[float] = 200,
eta: Optional[float] = 5000):
super().__init__()
assert isinstance(encoder_layer_sizes, list)
assert isinstance(latent_dim, int)
assert isinstance(decoder_layer_sizes, list)
assert isinstance(conditions, list)
assert recon_loss in ["mse", "nb", "zinb"], "'recon_loss' must be 'mse', 'nb' or 'zinb'"
assert calculate_mmd in [None, "y", "z"], "'calculate_mmd' must be None, 'y' or 'z'"
print("\nINITIALIZING NEW NETWORK..............")
self.input_dim = input_dim
self.latent_dim = latent_dim
self.n_conditions = len(conditions)
self.conditions = conditions
self.condition_encoder = {k: v for k, v in zip(conditions, range(len(conditions)))}
self.recon_loss = recon_loss
self.alpha = alpha
self.beta = beta
self.eta = eta
self.dr_rate = dr_rate
if self.dr_rate > 0:
self.use_dr = True
else:
self.use_dr = False
self.use_bn = use_batch_norm
self.calculate_mmd = calculate_mmd
self.mmd_boundary = mmd_boundary
self.use_mmd = True if self.calculate_mmd in ['z', 'y'] else False
self.enc_layer_sizes = encoder_layer_sizes.copy()
self.dec_layer_sizes = decoder_layer_sizes.copy()
encoder_layer_sizes.insert(0, self.input_dim)
decoder_layer_sizes.append(self.input_dim)
self.encoder = Encoder(encoder_layer_sizes, self.latent_dim,
self.use_bn, self.use_dr, self.dr_rate, self.n_conditions)
self.decoder = Decoder(decoder_layer_sizes, self.latent_dim, self.recon_loss, self.use_bn, self.use_dr,
self.dr_rate, self.use_mmd, self.n_conditions)
self.freeze = False
def sampling(self, mu, log_var):
"""Samples from standard Normal distribution and applies re-parametrization trick.
It is actually sampling from latent space distributions with N(mu, var), computed by encoder.
Parameters
----------
mu: torch.Tensor
Torch Tensor of Means.
log_var: torch.Tensor
Torch Tensor of log. variances.
Returns
-------
Torch Tensor of sampled data.
"""
std = torch.exp(0.5 * log_var)
eps = torch.randn_like(std)
return eps.mul(std).add(mu)
def generate_with_condition(self, n_samples, c=None):
z = torch.randn([n_samples, self.latent_dim])
if c is not None:
c = torch.ones([n_samples, 1], device=self.device) * c
output = self.decoder(z, c)
# If recon Loss is zinb, how to get recon_x?
return output
def get_latent(self, x, c=None, mean=False):
"""Map `x` in to the latent space. This function will feed data in encoder and return z for each sample in
data.
Parameters
----------
x: numpy nd-array
Numpy nd-array to be mapped to latent space. `x` has to be in shape [n_obs, input_dim].
c: `numpy nd-array`
`numpy nd-array` of original desired labels for each sample.
mean: boolean
Returns
-------
Returns array containing latent space encoding of 'x'.
"""
if c is not None:
c = torch.tensor(c, device=self.device)
x = torch.tensor(x, device=self.device)
z_mean, z_log_var = self.encoder(x, c)
latent = self.sampling(z_mean, z_log_var)
if mean:
return z_mean
return latent.cpu().data.numpy()
def get_y(self, x, c=None):
"""Map `x` in to the y dimension (First Layer of Decoder). This function will feed data in encoder and return
y for each sample in data.
Parameters
----------
x: numpy nd-array
Numpy nd-array to be mapped to latent space. `x` has to be in shape [n_obs, input_dim].
c: `numpy nd-array`
`numpy nd-array` of original desired labels for each sample.
Returns
-------
Returns array containing latent space encoding of 'x'
"""
if c is not None:
c = torch.tensor(c).to(self.device)
x = torch.tensor(x).to(self.device)
z_mean, z_log_var = self.encoder(x, c)
latent = self.sampling(z_mean, z_log_var)
output = self.decoder(latent, c)
return output[-1].cpu().data.numpy()
def calc_recon_binomial_loss(self, outputs, x_raw, size_factor):
dec_mean_gamma = outputs["dec_mean_gamma"]
size_factor_view = size_factor.unsqueeze(1).expand(dec_mean_gamma.size(0), dec_mean_gamma.size(1))
dec_mean = dec_mean_gamma * size_factor_view
if outputs["dec_dropout"] is None:
recon_loss = nb(x_raw, dec_mean, outputs["dec_disp"])
else:
recon_loss = zinb(x_raw, dec_mean, outputs["dec_disp"], outputs["dec_dropout"])
return recon_loss
def inference(self, x, c=None):
z1_mean, z1_log_var = self.encoder(x, c)
z1 = self.sampling(z1_mean, z1_log_var)
outputs = self.decoder(z1, c)
recon_x = dec_mean_gamma = dec_dropout = dec_disp = y1 = None
if self.recon_loss == "mse":
recon_x, y1 = outputs
if self.recon_loss == "zinb":
dec_mean_gamma, dec_dropout, dec_disp, y1 = outputs
if self.recon_loss == "nb":
dec_mean_gamma, dec_disp, y1 = outputs
return dict(
z1_mean=z1_mean,
z1_log_var=z1_log_var,
z1=z1,
y1=y1,
recon_x=recon_x,
dec_mean_gamma=dec_mean_gamma,
dec_dropout=dec_dropout,
dec_disp=dec_disp,
)
def forward(self, x=None, raw=None, f=None, c=None, y=None):
outputs = self.inference(x, c)
if outputs["recon_x"] is not None:
recon_loss = mse(outputs["recon_x"], x)
else:
recon_loss = self.calc_recon_binomial_loss(outputs, raw, f)
recon_loss *= self.eta
kl_div = kl(outputs["z1_mean"], outputs["z1_log_var"])
kl_loss = self.alpha * kl_div
mmd_loss = 0
if self.calculate_mmd is not None:
mmd_calculator = mmd(self.n_conditions, self.beta, self.mmd_boundary)
if self.calculate_mmd == "z":
mmd_loss = mmd_calculator(outputs["z1"], c)
else:
mmd_loss = mmd_calculator(outputs["y1"], c)
return recon_loss, kl_loss, mmd_loss
|
/scArchest-0.0.1-py3-none-any.whl/scarches/models/trvae/trvae.py
| 0.970219 | 0.704795 |
trvae.py
|
pypi
|
import numpy as np
from typing import Union
import torch
import torch.nn as nn
import anndata
from scvi.data import get_from_registry
from scarchest.models import scVI, scANVI
from scarchest.trainers import scVITrainer, scANVITrainer, UnlabelledScanviTrainer
def weight_update_check(old_network, op_network):
for op_name, op_p in op_network.named_parameters():
for name, p in old_network.named_parameters():
if op_name == name:
comparison = torch.eq(p, op_p)
if False in comparison:
print("UPDATED WEIGHTS", op_name)
for name, module in op_network.named_modules():
if isinstance(module, nn.BatchNorm1d):
if module.affine == False and module.track_running_stats == False:
print("FROZEN BATCHNORM:", name)
def scvi_operate(
network: Union[scVI, scANVI],
data: anndata.AnnData,
labels_per_class: int = 0,
n_epochs: int = 50,
freeze: bool = True,
freeze_expression: bool = True,
remove_dropout: bool = False,
) -> [Union[scVI, scANVI], Union[scVITrainer, scANVITrainer], anndata.AnnData]:
"""Transfer Learning function for new data. Uses old trained Network and expands it for new conditions.
Parameters
----------
network: VAE_M, SCANVI_M
A Scvi/Scanvi model object.
data: GeneExpressionDataset
GeneExpressionDataset object.
labels_per_class: Integer
Number of labelled Samples used for Retraining
n_epochs: Integer
Number of epochs for training the network on query data.
freeze: Boolean
If 'True' freezes every part of the network except the first layers of encoder/decoder.
freeze_expression: Boolean
If 'True' freeze every weight in first layers except the condition weights.
remove_dropout: Boolean
If 'True' remove Dropout for Transfer Learning.
Returns
-------
op_network: VAE_M, SCANVI_M
Newly network that got trained on query data.
op_trainer: UnsupervisedTrainer, SemiSupervisedTrainer
Trainer for the newly network.
data: GeneExpressionDataset
GeneExpressionDataset object with updated batch labels.
"""
early_stopping_kwargs = {
"early_stopping_metric": "elbo",
"save_best_state_metric": "elbo",
"patience": 15,
"threshold": 0,
"reduce_lr_on_plateau": True,
"lr_patience": 8,
"lr_factor": 0.1,
}
early_stopping_kwargs_scanvi = {
"early_stopping_metric": "accuracy",
"save_best_state_metric": "accuracy",
"on": "full_dataset",
"patience": 15,
"threshold": 0.001,
"reduce_lr_on_plateau": True,
"lr_patience": 8,
"lr_factor": 0.1,
}
# Update DR Rate
new_dr = network.dropout_rate
if remove_dropout:
new_dr = 0.0
n_new_conditions = data.uns["_scvi"]["summary_stats"]["n_batch"]
adata = data.copy()
adata.obs['_scvi_batch'] = get_from_registry(adata, "batch_indices").astype(np.int8) + network.n_batch
n_conditions = network.n_batch + n_new_conditions
if type(network) is scVI:
print("Create new VAE....")
op_network = scVI(
n_input=network.n_input,
n_batch=n_conditions,
n_hidden=network.n_hidden,
n_latent=network.n_latent,
n_layers=network.n_layers,
dropout_rate=new_dr,
dispersion=network.dispersion,
log_variational=network.log_variational,
gene_likelihood=network.gene_likelihood,
latent_distribution=network.latent_distribution,
modified=network.modified,
)
elif type(network) is scANVI:
print("Create new SCANVI....")
op_network = scANVI(
n_input=network.n_input,
n_batch=n_conditions,
n_labels=network.n_labels,
n_hidden=network.n_hidden,
n_latent=network.n_latent,
n_layers=network.n_layers,
dropout_rate=new_dr,
dispersion=network.dispersion,
log_variational=network.log_variational,
gene_likelihood=network.gene_likelihood,
y_prior=network.y_prior,
labels_groups=network.labels_groups,
use_labels_groups=network.use_labels_groups,
classifier_parameters=network.cls_parameters,
modified=network.modified,
)
else:
print("Please use a compatible model for this operate function")
exit()
op_network.new_conditions = n_new_conditions
if network.modified:
# Expand first Layer weights of z encoder of old network by new conditions
encoder_input_weights = network.z_encoder.encoder.fc_layers.Layer0.L.cond_L.weight
to_be_added_encoder_input_weights = np.random.randn(encoder_input_weights.size()[0], n_new_conditions) * \
np.sqrt(2 / (encoder_input_weights.size()[0] + 1 +
encoder_input_weights.size()[1]))
to_be_added_encoder_input_weights = torch.tensor(
to_be_added_encoder_input_weights,
device=encoder_input_weights.get_device()).float()
network.z_encoder.encoder.fc_layers.Layer0.L.cond_L.weight.data = torch.cat(
(network.z_encoder.encoder.fc_layers.Layer0.L.cond_L.weight, to_be_added_encoder_input_weights), 1)
# Expand first Layer weights of decoder of old network by new conditions
decoder_input_weights = network.decoder.px_decoder.fc_layers.Layer0.L.cond_L.weight
to_be_added_decoder_input_weights = np.random.randn(decoder_input_weights.size()[0], n_new_conditions) * \
np.sqrt(2 / (decoder_input_weights.size()[0] + 1 +
decoder_input_weights.size()[1]))
to_be_added_decoder_input_weights = torch.tensor(
to_be_added_decoder_input_weights,
device=decoder_input_weights.get_device()).float()
network.decoder.px_decoder.fc_layers.Layer0.L.cond_L.weight.data = torch.cat(
(network.decoder.px_decoder.fc_layers.Layer0.L.cond_L.weight, to_be_added_decoder_input_weights), 1)
else:
for layer in network.decoder.px_decoder.fc_layers:
decoder_input_weights = layer.L.cond_L.weight
to_be_added_decoder_input_weights = np.random.randn(decoder_input_weights.size()[0], n_new_conditions) * \
np.sqrt(2 / (decoder_input_weights.size()[0] + 1 +
decoder_input_weights.size()[1]))
to_be_added_decoder_input_weights = torch.tensor(
to_be_added_decoder_input_weights,
device=decoder_input_weights.get_device()).float()
layer.L.cond_L.weight.data = torch.cat(
(layer.L.cond_L.weight, to_be_added_decoder_input_weights), 1)
# Set the weights of new network to old network weights
op_network.load_state_dict(network.state_dict())
# Freeze parts of the network
if freeze:
op_network.freeze = True
for name, p in op_network.named_parameters():
p.requires_grad = False
if freeze_expression:
if network.modified:
if 'cond_L.weight' in name and ('z_encoder' in name or 'px_decoder' in name):
p.requires_grad = True
if 'l_encoder' in name:
p.requires_grad = True
else:
if 'cond_L.weight' in name and ('z_encoder' in name or 'px_decoder' in name):
p.requires_grad = True
if 'z_encoder' in name and 'Layer0' in name:
p.requires_grad = True
if 'l_encoder' in name:
p.requires_grad = True
else:
if network.modified:
if ('z_encoder' in name or 'px_decoder' in name) and 'Layer0' in name:
p.requires_grad = True
if 'l_encoder' in name:
p.requires_grad = True
else:
if 'z_encoder' in name and 'Layer0' in name:
p.requires_grad = True
if 'px_decoder' in name:
p.requires_grad = True
# Retrain Networks
if type(network) is scVI:
op_trainer = scVITrainer(
op_network,
adata,
train_size=0.9,
use_cuda=True,
frequency=1,
early_stopping_kwargs=early_stopping_kwargs
)
op_trainer.train(n_epochs=n_epochs, lr=1e-3)
if type(network) is scANVI:
if labels_per_class == 0:
op_trainer = UnlabelledScanviTrainer(
op_network,
adata,
n_labelled_samples_per_class=labels_per_class,
train_size=0.9,
use_cuda=True,
frequency=1,
early_stopping_kwargs=early_stopping_kwargs_scanvi
)
else:
op_trainer = scANVITrainer(
op_network,
adata,
n_labelled_samples_per_class=labels_per_class,
classification_ratio=50,
train_size=0.9,
use_cuda=True,
frequency=1,
early_stopping_kwargs=early_stopping_kwargs_scanvi
)
op_trainer.train(n_epochs=n_epochs, lr=1e-3)
weight_update_check(network, op_network)
return op_network, op_trainer, adata
|
/scArchest-0.0.1-py3-none-any.whl/scarches/surgery/scvi.py
| 0.883864 | 0.328893 |
scvi.py
|
pypi
|
import numpy as np
from typing import Union
import torch
from scarchest.models.trvae.trvae import trVAE
def trvae_operate(network: trVAE,
data_conditions: Union[list, str],
freeze: bool = True,
freeze_expression: bool = True,
remove_dropout: bool = True,
) -> trVAE:
"""Transfer Learning function for new data. Uses old trained Network and expands it for new conditions.
Parameters
----------
network: trVAE
A scNet model object.
data_conditions: list_str
List of Strings of new Conditions.
freeze: Boolean
If 'True' freezes every part of the network except the first layers of encoder/decoder.
remove_dropout: Boolean
If 'True' remove Dropout for Transfer Learning.
Returns
-------
new_network: trVAE
New expanded network with old weights for Transfer Learning.
"""
conditions = network.conditions
new_conditions = []
# Check if new conditions are already known
for item in data_conditions:
if item not in conditions:
new_conditions.append(item)
n_new_conditions = len(new_conditions)
# Add new conditions to overall conditions
for condition in new_conditions:
conditions.append(condition)
# Update DR Rate
new_dr = network.dr_rate
if remove_dropout:
new_dr = 0.0
new_network = trVAE(
network.input_dim,
conditions=conditions,
encoder_layer_sizes=network.enc_layer_sizes,
latent_dim=network.latent_dim,
decoder_layer_sizes=network.dec_layer_sizes,
recon_loss=network.recon_loss,
alpha=network.alpha,
use_batch_norm=network.use_bn,
dr_rate=new_dr,
beta=network.beta,
eta=network.eta,
calculate_mmd=network.calculate_mmd,
mmd_boundary=network.mmd_boundary
)
# Expand First Layer weights of encoder/decoder of old network by new conditions
encoder_input_weights = network.encoder.FC.L0.cond_L.weight
to_be_added_encoder_input_weights = np.random.randn(encoder_input_weights.size()[0], n_new_conditions) * np.sqrt(
2 / (encoder_input_weights.size()[0] + 1 + encoder_input_weights.size()[1]))
to_be_added_encoder_input_weights = torch.from_numpy(to_be_added_encoder_input_weights).float().to(network.device)
new_encoder_input_weights = torch.cat((encoder_input_weights, to_be_added_encoder_input_weights), 1)
network.encoder.FC.L0.cond_L.weight.data = new_encoder_input_weights
decoder_input_weights = network.decoder.FirstL.L0.cond_L.weight
to_be_added_decoder_input_weights = np.random.randn(decoder_input_weights.size()[0], n_new_conditions) * np.sqrt(
2 / (decoder_input_weights.size()[0] + 1 + decoder_input_weights.size()[1]))
to_be_added_decoder_input_weights = torch.from_numpy(to_be_added_decoder_input_weights).float().to(network.device)
new_decoder_input_weights = torch.cat((decoder_input_weights, to_be_added_decoder_input_weights), 1)
network.decoder.FirstL.L0.cond_L.weight.data = new_decoder_input_weights
# Set the weights of new network to old network weights
new_network.load_state_dict(network.state_dict())
# Freeze parts of the network
if freeze:
new_network.freeze = True
for name, p in new_network.named_parameters():
p.requires_grad = False
if freeze_expression:
if 'cond_L.weight' in name:
p.requires_grad = True
else:
if "L0" in name or "B0" in name:
p.requires_grad = True
return new_network
|
/scArchest-0.0.1-py3-none-any.whl/scarches/surgery/trvae.py
| 0.899817 | 0.526647 |
trvae.py
|
pypi
|
import numpy as np
from typing import Union
import torch
import scanpy as sc
from scarchest.models import MARS
from scarchest.trainers import MARSTrainer
def mars_operate(network: MARS,
new_adata: sc.AnnData,
new_tasks: Union[list, str],
meta_tasks: list,
n_clusters: int,
task_key: str,
cell_type_key: str,
tau: float = 0.2,
eta: float = 1.0,
freeze: bool = True,
remove_dropout: bool = True,
) -> MARS:
"""Transfer Learning function for new data. Uses old trained Network and expands it for new conditions.
Parameters
----------
network: MARS
A MARS model object.
new_tasks: list_str
List of Strings of new Conditions.
freeze: Boolean
If 'True' freezes every part of the network except the first layers of encoder/decoder.
remove_dropout: Boolean
If 'True' remove Dropout for Transfer Learning.
Returns
-------
new_network: MARS
New expanded network with old weights for Transfer Learning.
"""
conditions = network.conditions
new_conditions = []
# Check if new conditions are already known
for item in new_tasks:
if item not in conditions:
new_conditions.append(item)
n_new_conditions = len(new_conditions)
# Add new conditions to overall conditions
for condition in new_conditions:
conditions.append(condition)
# Update DR Rate
new_dr = network.dropout_rate
if remove_dropout:
new_dr = 0.0
new_network = MARS(
x_dim=network.x_dim,
architecture=network.architecture,
z_dim=network.z_dim,
conditions=conditions,
alpha=network.alpha,
activation=network.activation,
output_activation=network.output_activation,
use_batchnorm=network.use_batchnorm,
dropout_rate=new_dr,
)
# Expand First Layer weights of encoder/decoder of old network by new conditions
encoder_input_weights = network.encoder[0].FC_0.weight
to_be_added_encoder_input_weights = np.random.randn(encoder_input_weights.size()[0], n_new_conditions) * np.sqrt(
2 / (encoder_input_weights.size()[0] + 1 + encoder_input_weights.size()[1]))
to_be_added_encoder_input_weights = torch.from_numpy(to_be_added_encoder_input_weights).float().to(network.device)
new_encoder_input_weights = torch.cat((encoder_input_weights, to_be_added_encoder_input_weights), 1)
network.encoder[0].FC_0.weight.data = new_encoder_input_weights
decoder_input_weights = network.decoder[0].FC_0.weight
to_be_added_decoder_input_weights = np.random.randn(decoder_input_weights.size()[0], n_new_conditions) * np.sqrt(
2 / (decoder_input_weights.size()[0] + 1 + decoder_input_weights.size()[1]))
to_be_added_decoder_input_weights = torch.from_numpy(to_be_added_decoder_input_weights).float().to(network.device)
new_decoder_input_weights = torch.cat((decoder_input_weights, to_be_added_decoder_input_weights), 1)
network.decoder[0].FC_0.weight.data = new_decoder_input_weights
# Set the weights of new network to old network weights
new_network.load_state_dict(network.state_dict())
# Freeze parts of the network
if freeze:
for name, p in new_network.named_parameters():
if "FC_0" not in name:
p.requires_grad = False
new_trainer = MARSTrainer(model=new_network,
adata=new_adata,
task_key=task_key,
meta_test_tasks=meta_tasks,
cell_type_key=cell_type_key,
n_clusters=n_clusters,
tau=tau,
eta=eta,
)
return new_network, new_trainer
|
/scArchest-0.0.1-py3-none-any.whl/scarches/surgery/mars.py
| 0.888475 | 0.432962 |
mars.py
|
pypi
|
import numpy as np
class EarlyStopping(object):
def __init__(self,
mode: str = 'min',
early_stopping_metric: str = 'val_loss',
save_best_state_metric: str = 'val_loss',
benchmark: bool = False,
threshold: int = 3,
patience: int = 50):
self.benchmark = benchmark
self.patience = patience
self.threshold = threshold
self.epoch = 0
self.wait = 0
self.mode = mode
self.save_best_state_metric = save_best_state_metric
self.early_stopping_metric = early_stopping_metric
self.current_performance = np.inf
self.best_performance = np.inf
self.best_performance_state = np.inf
if self.mode == "max":
self.best_performance *= -1
self.current_performance *= -1
if patience == 0:
self.is_better = lambda a, b: True
self.step = lambda a: False
def step(self, scalar):
self.epoch += 1
if self.benchmark or self.epoch < self.patience:
continue_training = True
elif self.wait >= self.patience:
continue_training = False
else:
# Shift
self.current_performance = scalar
improvement = 0
# Compute improvement
if self.mode == "max":
improvement = self.current_performance - self.best_performance
elif self.mode == "min":
improvement = self.best_performance - self.current_performance
# updating best performance
if improvement > 0:
self.best_performance = self.current_performance
if improvement < self.threshold:
self.wait += 1
else:
self.wait = 0
continue_training = True
if not continue_training:
print("\nStopping early: no improvement of more than " + str(self.threshold) +
" nats in " + str(self.patience) + " epochs")
print("If the early stopping criterion is too strong, "
"please instantiate it with different parameters in the train method.")
return continue_training
def update_state(self, scalar):
improved = ((self.mode == "max" and scalar - self.best_performance_state > 0) or
(self.mode == "min" and self.best_performance_state - scalar > 0))
if improved:
self.best_performance_state = scalar
return improved
|
/scArchest-0.0.1-py3-none-any.whl/scarches/utils/monitor.py
| 0.825449 | 0.201971 |
monitor.py
|
pypi
|
import numpy as np
from scipy.stats import itemfreq, entropy
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score, adjusted_rand_score, normalized_mutual_info_score
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import LabelEncoder
from scarchest.dataset.trvae.data_handling import remove_sparsity
def __entropy_from_indices(indices):
return entropy(np.array(itemfreq(indices)[:, 1].astype(np.int32)))
def entropy_batch_mixing(adata, label_key='batch',
n_neighbors=50, n_pools=50, n_samples_per_pool=100):
"""Computes Entory of Batch mixing metric for ``adata`` given the batch column name.
Parameters
----------
adata: :class:`~anndata.AnnData`
Annotated dataset.
label_key: str
Name of the column which contains information about different studies in ``adata.obs`` data frame.
n_neighbors: int
Number of nearest neighbors.
n_pools: int
Number of EBM computation which will be averaged.
n_samples_per_pool: int
Number of samples to be used in each pool of execution.
Returns
-------
score: float
EBM score. A float between zero and one.
"""
adata = remove_sparsity(adata)
neighbors = NearestNeighbors(n_neighbors=n_neighbors + 1).fit(adata.X)
indices = neighbors.kneighbors(adata.X, return_distance=False)[:, 1:]
batch_indices = np.vectorize(lambda i: adata.obs[label_key].values[i])(indices)
entropies = np.apply_along_axis(__entropy_from_indices, axis=1, arr=batch_indices)
# average n_pools entropy results where each result is an average of n_samples_per_pool random samples.
if n_pools == 1:
score = np.mean(entropies)
else:
score = np.mean([
np.mean(entropies[np.random.choice(len(entropies), size=n_samples_per_pool)])
for _ in range(n_pools)
])
return score
def asw(adata, label_key):
"""Computes Average Silhouette Width (ASW) metric for ``adata`` given the batch column name.
Parameters
----------
adata: :class:`~anndata.AnnData`
Annotated dataset.
label_key: str
Name of the column which contains information about different studies in ``adata.obs`` data frame.
Returns
-------
score: float
ASW score. A float between -1 and 1.
"""
adata = remove_sparsity(adata)
labels = adata.obs[label_key].values
labels_encoded = LabelEncoder().fit_transform(labels)
return silhouette_score(adata.X, labels_encoded)
def ari(adata, label_key):
"""Computes Adjusted Rand Index (ARI) metric for ``adata`` given the batch column name.
Parameters
----------
adata: :class:`~anndata.AnnData`
Annotated dataset.
label_key: str
Name of the column which contains information about different studies in ``adata.obs`` data frame.
Returns
-------
score: float
ARI score. A float between 0 and 1.
"""
adata = remove_sparsity(adata)
n_labels = len(adata.obs[label_key].unique().tolist())
kmeans = KMeans(n_labels, n_init=200)
labels_pred = kmeans.fit_predict(adata.X)
labels = adata.obs[label_key].values
labels_encoded = LabelEncoder().fit_transform(labels)
return adjusted_rand_score(labels_encoded, labels_pred)
def nmi(adata, label_key):
"""Computes Normalized Mutual Information (NMI) metric for ``adata`` given the batch column name.
Parameters
----------
adata: :class:`~anndata.AnnData`
Annotated dataset.
label_key: str
Name of the column which contains information about different studies in ``adata.obs`` data frame.
Returns
-------
score: float
NMI score. A float between 0 and 1.
"""
adata = remove_sparsity(adata)
n_labels = len(adata.obs[label_key].unique().tolist())
kmeans = KMeans(n_labels, n_init=200)
labels_pred = kmeans.fit_predict(adata.X)
labels = adata.obs[label_key].values
labels_encoded = LabelEncoder().fit_transform(labels)
return normalized_mutual_info_score(labels_encoded, labels_pred)
def knn_purity(adata, label_key, n_neighbors=30):
"""Computes KNN Purity metric for ``adata`` given the batch column name.
Parameters
----------
adata: :class:`~anndata.AnnData`
Annotated dataset.
label_key: str
Name of the column which contains information about different studies in ``adata.obs`` data frame.
n_neighbors: int
Number of nearest neighbors.
Returns
-------
score: float
KNN purity score. A float between 0 and 1.
"""
adata = remove_sparsity(adata)
labels = LabelEncoder().fit_transform(adata.obs[label_key].to_numpy())
nbrs = NearestNeighbors(n_neighbors=n_neighbors + 1).fit(adata.X)
indices = nbrs.kneighbors(adata.X, return_distance=False)[:, 1:]
neighbors_labels = np.vectorize(lambda i: labels[i])(indices)
# pre cell purity scores
scores = ((neighbors_labels - labels.reshape(-1, 1)) == 0).mean(axis=1)
res = [
np.mean(scores[labels == i]) for i in np.unique(labels)
] # per cell-type purity
return np.mean(res)
|
/scArchest-0.0.1-py3-none-any.whl/scarches/metrics/metrics.py
| 0.939401 | 0.779028 |
metrics.py
|
pypi
|
from scvi.data import get_from_registry
from scarchest.metrics.metrics import entropy_batch_mixing, knn_purity
from scarchest.models import scVI, scANVI
from scarchest.trainers import scVITrainer, scANVITrainer
import numpy as np
import scanpy as sc
import torch
from typing import Union
import anndata
import matplotlib.pyplot as plt
sc.settings.set_figure_params(dpi=100, frameon=False)
sc.set_figure_params(dpi=100)
torch.set_printoptions(precision=3, sci_mode=False, edgeitems=7)
np.set_printoptions(precision=2, edgeitems=7)
class SCVI_EVAL:
def __init__(
self,
model: Union[scVI, scANVI],
trainer: Union[scVITrainer, scANVITrainer],
adata: anndata.AnnData,
cell_type_key: str,
batch_key: str,
):
self.model = model
self.trainer = trainer
self.adata = adata
self.modified = model.modified
self.annotated = type(model) is scANVI
self.post_adata_2 = None
self.predictions = None
if self.trainer.use_cuda:
self.device = torch.device('cuda')
else:
self.device = torch.device('cpu')
self.x_tensor = torch.tensor(self.adata.X, device=self.device)
self.labels = get_from_registry(self.adata, "labels").astype(np.int8)
self.label_tensor = torch.tensor(self.labels, device=self.device)
self.cell_types = self.adata.obs[cell_type_key].tolist()
self.batch_indices = get_from_registry(self.adata, "batch_indices").astype(np.int8)
self.batch_tensor = torch.tensor(self.batch_indices, device=self.device)
self.batch_names = self.adata.obs[batch_key].tolist()
self.post_adata = self.latent_as_anndata()
def latent_as_anndata(self):
if self.modified:
latents = self.model.get_latents(
self.x_tensor,
y=self.label_tensor,
batch_index=self.batch_tensor
)
else:
latents = self.model.get_latents(
self.x_tensor,
y=self.label_tensor,
)
if self.annotated:
latent = latents[0].cpu().detach().numpy()
latent2 = latents[1].cpu().detach().numpy()
post_adata_2 = sc.AnnData(latent2)
post_adata_2.obs['cell_type'] = self.cell_types
post_adata_2.obs['batch'] = self.batch_names
self.post_adata_2 = post_adata_2
else:
latent = latents[0].cpu().detach().numpy()
post_adata = sc.AnnData(latent)
post_adata.obs['cell_type'] = self.cell_types
post_adata.obs['batch'] = self.batch_names
return post_adata
def get_model_arch(self):
for name, p in self.model.named_parameters():
print(name, " - ", p.size(0), p.size(-1))
def plot_latent(self, n_neighbors=8):
sc.pp.neighbors(self.post_adata, n_neighbors=n_neighbors)
sc.tl.umap(self.post_adata)
sc.pl.umap(self.post_adata, color=['cell_type', 'batch'], frameon=False, wspace=0.6)
def plot_latent_ann(self, n_neighbors=8):
if self.annotated:
sc.pp.neighbors(self.post_adata_2, n_neighbors=n_neighbors)
sc.tl.umap(self.post_adata_2)
sc.pl.umap(self.post_adata_2, color=['cell_type', 'batch'], frameon=False, wspace=0.6)
else:
print("Second latent space not available for scVI models")
def plot_history(self, n_epochs):
if self.annotated:
elbo_full = self.trainer.history["elbo_full_dataset"]
x_1 = np.linspace(0, len(elbo_full), len(elbo_full))
fig, axs = plt.subplots(2, 1)
axs[0].plot(x_1, elbo_full, label="Full")
accuracy_labelled_set = self.trainer.history["accuracy_labelled_set"]
accuracy_unlabelled_set = self.trainer.history["accuracy_unlabelled_set"]
if len(accuracy_labelled_set) != 0:
x_2 = np.linspace(0, len(accuracy_labelled_set), (len(accuracy_labelled_set)))
axs[1].plot(x_2, accuracy_labelled_set, label="accuracy labelled")
if len(accuracy_unlabelled_set) != 0:
x_3 = np.linspace(0, len(accuracy_unlabelled_set), (len(accuracy_unlabelled_set)))
axs[1].plot(x_3, accuracy_unlabelled_set, label="accuracy unlabelled")
axs[0].set_xlabel('Epochs')
axs[0].set_ylabel('ELBO')
axs[1].set_xlabel('Epochs')
axs[1].set_ylabel('Accuracy')
plt.legend()
plt.show()
else:
elbo_train = self.trainer.history["elbo_train_set"]
elbo_test = self.trainer.history["elbo_test_set"]
x = np.linspace(0, len(elbo_train), len(elbo_train))
plt.plot(x, elbo_train, label="train")
plt.plot(x, elbo_test, label="test")
plt.ylim(min(elbo_train) - 50, min(elbo_train) + 1000)
plt.legend()
plt.show()
def get_ebm(self, n_neighbors=50, n_pools=50, n_samples_per_pool=100, verbose=True):
ebm_score = entropy_batch_mixing(
adata=self.post_adata,
label_key='batch',
n_neighbors=n_neighbors,
n_pools=n_pools,
n_samples_per_pool=n_samples_per_pool
)
if verbose:
print("Entropy of Batchmixing-Score:", ebm_score)
return ebm_score
def get_knn_purity(self, n_neighbors=50, verbose=True):
knn_score = knn_purity(
adata=self.post_adata,
label_key='cell_type',
n_neighbors=n_neighbors
)
if verbose:
print("KNN Purity-Score:", knn_score)
return knn_score
def get_latent_score(self):
ebm = self.get_ebm(verbose=False)
knn = self.get_knn_purity(verbose=False)
score = ebm + knn
print("Latent-Space Score (KNN + EBM):", score)
return score
def get_classification_accuracy(self):
if self.annotated:
if self.modified:
predictions = self.model.classify(self.x_tensor, batch_index=self.batch_tensor)
else:
predictions = self.model.classify(self.x_tensor)
self.predictions = predictions.cpu().detach().numpy()
self.predictions = np.argmax(self.predictions, axis=1)
class_check = np.array(np.expand_dims(self.predictions, axis=1) == self.labels)
accuracy = np.sum(class_check) / class_check.shape[0]
print("Classification Accuracy: %0.2f" % accuracy)
return accuracy
else:
print("Classification ratio not available for scVI models")
|
/scArchest-0.0.1-py3-none-any.whl/scarches/plotting/scvi_eval.py
| 0.814791 | 0.278508 |
scvi_eval.py
|
pypi
|
import numpy as np
import logging
import torch
from torch.nn import functional as F
from scvi.data._anndata import get_from_registry
from scvi import _CONSTANTS
from scarchest.trainers.scvi import Trainer, scVITrainer
from scarchest.dataset.scvi import AnnotationDataLoader
logger = logging.getLogger(__name__)
class ClassifierTrainer(Trainer):
"""Class for training a classifier either on the raw data or on top of the latent space of another model.
Parameters
----------
model
A model instance from class ``VAE``, ``VAEC``, ``SCANVI``
gene_dataset
A gene_dataset instance like ``CortexDataset()``
train_size
The train size, a float between 0 and 1 representing proportion of dataset to use for training
to use Default: ``0.9``.
test_size
The test size, a float between 0 and 1 representing proportion of dataset to use for testing
to use Default: ``None``.
sampling_model
Model with z_encoder with which to first transform data.
sampling_zl
Transform data with sampling_model z_encoder and l_encoder and concat.
**kwargs
Other keywords arguments from the general Trainer class.
Examples
--------
>>> gene_dataset = CortexDataset()
>>> vae = VAE(gene_dataset.nb_genes, n_batch=gene_dataset.n_batches * False,
... n_labels=gene_dataset.n_labels)
>>> classifier = Classifier(vae.n_latent, n_labels=cortex_dataset.n_labels)
>>> trainer = ClassifierTrainer(classifier, gene_dataset, sampling_model=vae, train_size=0.5)
>>> trainer.train(n_epochs=20, lr=1e-3)
>>> trainer.test_set.accuracy()
"""
def __init__(
self,
*args,
train_size=0.9,
test_size=None,
sampling_model=None,
sampling_zl=False,
use_cuda=True,
**kwargs
):
train_size = float(train_size)
if train_size > 1.0 or train_size <= 0.0:
raise ValueError(
"train_size needs to be greater than 0 and less than or equal to 1"
)
self.sampling_model = sampling_model
self.sampling_zl = sampling_zl
super().__init__(*args, use_cuda=use_cuda, **kwargs)
self.train_set, self.test_set, self.validation_set = self.train_test_validation(
self.model,
self.adata,
train_size=train_size,
test_size=test_size,
type_class=AnnotationDataLoader,
)
self.train_set.to_monitor = ["accuracy"]
self.test_set.to_monitor = ["accuracy"]
self.validation_set.to_monitor = ["accuracy"]
self.train_set.model_zl = sampling_zl
self.test_set.model_zl = sampling_zl
self.validation_set.model_zl = sampling_zl
@property
def scvi_data_loaders_loop(self):
return ["train_set"]
def __setattr__(self, key, value):
if key in ["train_set", "test_set"]:
value.sampling_model = self.sampling_model
super().__setattr__(key, value)
def loss(self, tensors_labelled):
x = tensors_labelled[_CONSTANTS.X_KEY]
labels_train = tensors_labelled[_CONSTANTS.LABELS_KEY]
if hasattr(self.sampling_model, "classify"):
if self.sampling_model.modified:
batch_index = tensors_labelled[_CONSTANTS.BATCH_KEY]
return F.cross_entropy(
self.sampling_model.classify(x, batch_index), labels_train.view(-1)
)
return F.cross_entropy(
self.sampling_model.classify(x), labels_train.view(-1)
)
else:
if self.sampling_model.log_variational:
x = torch.log(1 + x)
if self.sampling_zl:
if self.sampling_model.modified:
batch_index = tensors_labelled[_CONSTANTS.BATCH_KEY]
x_z = self.sampling_model.z_encoder(x, batch_index)[0]
x_l = self.sampling_model.l_encoder(x, batch_index)[0]
else:
x_z = self.sampling_model.z_encoder(x)[0]
x_l = self.sampling_model.l_encoder(x)[0]
x = torch.cat((x_z, x_l), dim=-1)
else:
if self.sampling_model.modified:
batch_index = tensors_labelled[_CONSTANTS.BATCH_KEY]
x = self.sampling_model.z_encoder(x, batch_index)[0]
else:
x = self.sampling_model.z_encoder(x)[0]
return F.cross_entropy(self.model(x), labels_train.view(-1))
def create_scvi_dl(
self,
model=None,
adata=None,
shuffle=False,
indices=None,
type_class=AnnotationDataLoader,
):
return super().create_scvi_dl(model, adata, shuffle, indices, type_class)
class scANVITrainer(scVITrainer):
"""Class for the semi-supervised training of an autoencoder.
This parent class can be inherited to specify the different training schemes for semi-supervised learning
Parameters
----------
n_labelled_samples_per_class
number of labelled samples per class
"""
def __init__(
self,
model,
adata,
n_labelled_samples_per_class=50,
n_epochs_classifier=1,
lr_classification=5 * 1e-3,
classification_ratio=50,
seed=0,
**kwargs
):
super().__init__(model, adata, **kwargs)
self.model = model
self.adata = adata
self.n_epochs_classifier = n_epochs_classifier
self.lr_classification = lr_classification
self.classification_ratio = classification_ratio
n_labelled_samples_per_class_array = [
n_labelled_samples_per_class
] * self.adata.uns["_scvi"]["summary_stats"]["n_labels"]
labels = np.array(get_from_registry(self.adata, _CONSTANTS.LABELS_KEY)).ravel()
np.random.seed(seed=seed)
permutation_idx = np.random.permutation(len(labels))
labels = labels[permutation_idx]
indices = []
current_nbrs = np.zeros(len(n_labelled_samples_per_class_array))
for idx, (label) in enumerate(labels):
label = int(label)
if current_nbrs[label] < n_labelled_samples_per_class_array[label]:
indices.insert(0, idx)
current_nbrs[label] += 1
else:
indices.append(idx)
indices = np.array(indices)
total_labelled = sum(n_labelled_samples_per_class_array)
indices_labelled = permutation_idx[indices[:total_labelled]]
indices_unlabelled = permutation_idx[indices[total_labelled:]]
self.classifier_trainer = ClassifierTrainer(
model.classifier,
self.adata,
metrics_to_monitor=[],
silent=True,
frequency=0,
sampling_model=self.model,
)
self.full_dataset = self.create_scvi_dl(shuffle=True)
self.labelled_set = self.create_scvi_dl(indices=indices_labelled)
self.unlabelled_set = self.create_scvi_dl(indices=indices_unlabelled)
for scdl in [self.labelled_set, self.unlabelled_set]:
scdl.to_monitor = ["reconstruction_error", "accuracy"]
@property
def scvi_data_loaders_loop(self):
return ["full_dataset", "labelled_set"]
def __setattr__(self, key, value):
if key == "labelled_set":
self.classifier_trainer.train_set = value
super().__setattr__(key, value)
def loss(self, tensors_all, tensors_labelled):
loss = super().loss(tensors_all, feed_labels=False)
sample_batch = tensors_labelled[_CONSTANTS.X_KEY]
y = tensors_labelled[_CONSTANTS.LABELS_KEY]
if self.model.modified:
batch_index = tensors_labelled[_CONSTANTS.BATCH_KEY]
classification_loss = F.cross_entropy(
self.model.classify(sample_batch, batch_index), y.view(-1)
)
else:
classification_loss = F.cross_entropy(
self.model.classify(sample_batch), y.view(-1)
)
loss += classification_loss * self.classification_ratio
return loss
def on_epoch_end(self):
self.model.eval()
self.classifier_trainer.train(
self.n_epochs_classifier, lr=self.lr_classification
)
self.model.train()
return super().on_epoch_end()
def create_scvi_dl(
self,
model=None,
adata=None,
shuffle=False,
indices=None,
type_class=AnnotationDataLoader,
):
return super().create_scvi_dl(model, adata, shuffle, indices, type_class)
class UnlabelledScanviTrainer(scANVITrainer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def loss(self, all_tensor):
return scVITrainer.loss(self, all_tensor, feed_labels=False)
@property
def scvi_data_loaders_loop(self):
return ["full_dataset"]
|
/scArchest-0.0.1-py3-none-any.whl/scarches/trainers/scvi/annotation.py
| 0.901531 | 0.458955 |
annotation.py
|
pypi
|
from typing import Union
import anndata
import logging
import torch
from scvi import _CONSTANTS
from scvi.core.modules import Classifier
from scvi.core.modules.utils import one_hot
from scarchest.models.scvi import totalVI
from scarchest.trainers.scvi import scVITrainer
from scarchest.dataset.scvi import TotalDataLoader
logger = logging.getLogger(__name__)
default_early_stopping_kwargs = {
"early_stopping_metric": "elbo",
"save_best_state_metric": "elbo",
"patience": 45,
"threshold": 0,
"reduce_lr_on_plateau": True,
"lr_patience": 30,
"lr_factor": 0.6,
"scvi_data_loader_class": TotalDataLoader,
}
def _unpack_tensors(tensors):
x = tensors[_CONSTANTS.X_KEY]
local_l_mean = tensors[_CONSTANTS.LOCAL_L_MEAN_KEY]
local_l_var = tensors[_CONSTANTS.LOCAL_L_VAR_KEY]
batch_index = tensors[_CONSTANTS.BATCH_KEY]
labels = tensors[_CONSTANTS.LABELS_KEY]
y = tensors[_CONSTANTS.PROTEIN_EXP_KEY]
return x, local_l_mean, local_l_var, batch_index, labels, y
class totalTrainer(scVITrainer):
"""
Unsupervised training for totalVI using variational inference.
Parameters
----------
model
A model instance from class ``TOTALVAE``
adata
A registered AnnData object
train_size
The train size, a float between 0 and 1 representing proportion of dataset to use for training
to use Default: ``0.90``.
test_size
The test size, a float between 0 and 1 representing proportion of dataset to use for testing
to use Default: ``0.10``. Note that if train and test do not add to 1 the remainder is placed in a validation set
pro_recons_weight
Scaling factor on the reconstruction loss for proteins. Default: ``1.0``.
n_epochs_kl_warmup
Number of epochs for annealing the KL terms for `z` and `mu` of the ELBO (from 0 to 1). If None, no warmup performed, unless
`n_iter_kl_warmup` is set.
n_iter_kl_warmup
Number of minibatches for annealing the KL terms for `z` and `mu` of the ELBO (from 0 to 1). If set to "auto", the number
of iterations is equal to 75% of the number of cells. `n_epochs_kl_warmup` takes precedence if it is not None. If both are None, then
no warmup is performed.
discriminator
Classifier used for adversarial training scheme
use_adversarial_loss
Whether to use adversarial classifier to improve mixing
kappa
Scaling factor for adversarial loss. If None, follow inverse of kl warmup schedule.
early_stopping_kwargs
Keyword args for early stopping. If "auto", use totalVI defaults. If None, disable early stopping.
"""
default_metrics_to_monitor = ["elbo"]
def __init__(
self,
model: totalVI,
dataset: anndata.AnnData,
train_size: float = 0.90,
test_size: float = 0.10,
pro_recons_weight: float = 1.0,
n_epochs_kl_warmup: int = None,
n_iter_kl_warmup: Union[str, int] = "auto",
discriminator: Classifier = None,
use_adversarial_loss: bool = False,
kappa: float = None,
early_stopping_kwargs: Union[dict, str, None] = "auto",
**kwargs,
):
train_size = float(train_size)
if train_size > 1.0 or train_size <= 0.0:
raise ValueError(
"train_size needs to be greater than 0 and less than or equal to 1"
)
self.n_genes = model.n_input_genes
self.n_proteins = model.n_input_proteins
self.use_adversarial_loss = use_adversarial_loss
self.kappa = kappa
self.pro_recons_weight = pro_recons_weight
if early_stopping_kwargs == "auto":
early_stopping_kwargs = default_early_stopping_kwargs
super().__init__(
model,
dataset,
n_epochs_kl_warmup=n_epochs_kl_warmup,
n_iter_kl_warmup=0.75 * len(dataset)
if n_iter_kl_warmup == "auto"
else n_iter_kl_warmup,
early_stopping_kwargs=early_stopping_kwargs,
**kwargs,
)
if use_adversarial_loss is True and discriminator is None:
discriminator = Classifier(
n_input=self.model.n_latent,
n_hidden=32,
n_labels=self.adata.uns["_scvi"]["summary_stats"]["n_batch"],
n_layers=2,
logits=True,
)
self.discriminator = discriminator
if self.use_cuda and self.discriminator is not None:
self.discriminator.cuda()
if isinstance(self, totalTrainer):
(
self.train_set,
self.test_set,
self.validation_set,
) = self.train_test_validation(
model, dataset, train_size, test_size, type_class=TotalDataLoader
)
self.train_set.to_monitor = []
self.test_set.to_monitor = ["elbo"]
self.validation_set.to_monitor = ["elbo"]
def loss(self, tensors):
(
sample_batch_x,
local_l_mean,
local_l_var,
batch_index,
label,
sample_batch_y,
) = _unpack_tensors(tensors)
(
reconst_loss_gene,
reconst_loss_protein,
kl_div_z,
kl_div_l_gene,
kl_div_back_pro,
) = self.model(
sample_batch_x,
sample_batch_y,
local_l_mean,
local_l_var,
batch_index,
label,
)
loss = torch.mean(
reconst_loss_gene
+ self.pro_recons_weight * reconst_loss_protein
+ self.kl_weight * kl_div_z
+ kl_div_l_gene
+ self.kl_weight * kl_div_back_pro
)
return loss
def loss_discriminator(
self, z, batch_index, predict_true_class=True, return_details=True
):
n_classes = self.adata.uns["_scvi"]["summary_stats"]["n_batch"]
cls_logits = torch.nn.LogSoftmax(dim=1)(self.discriminator(z))
if predict_true_class:
cls_target = one_hot(batch_index, n_classes)
else:
one_hot_batch = one_hot(batch_index, n_classes)
cls_target = torch.zeros_like(one_hot_batch)
# place zeroes where true label is
cls_target.masked_scatter_(
~one_hot_batch.bool(), torch.ones_like(one_hot_batch) / (n_classes - 1)
)
l_soft = cls_logits * cls_target
loss = -l_soft.sum(dim=1).mean()
return loss
def _get_z(self, tensors):
(
sample_batch_x,
local_l_mean,
local_l_var,
batch_index,
label,
sample_batch_y,
) = _unpack_tensors(tensors)
z = self.model.sample_from_posterior_z(
sample_batch_x, sample_batch_y, batch_index, give_mean=False
)
return z
def train(self, n_epochs=500, lr=4e-3, eps=0.01, params=None):
super().train(n_epochs=n_epochs, lr=lr, eps=eps, params=params)
def on_training_loop(self, tensors_dict):
if self.use_adversarial_loss:
if self.kappa is None:
kappa = 1 - self.kl_weight
else:
kappa = self.kappa
batch_index = tensors_dict[0][_CONSTANTS.BATCH_KEY]
if kappa > 0:
z = self._get_z(*tensors_dict)
# Train discriminator
d_loss = self.loss_discriminator(z.detach(), batch_index, True)
d_loss *= kappa
self.d_optimizer.zero_grad()
d_loss.backward()
self.d_optimizer.step()
# Train generative model to fool discriminator
fool_loss = self.loss_discriminator(z, batch_index, False)
fool_loss *= kappa
# Train generative model
self.optimizer.zero_grad()
self.current_loss = loss = self.loss(*tensors_dict)
if kappa > 0:
(loss + fool_loss).backward()
else:
loss.backward()
self.optimizer.step()
else:
self.current_loss = loss = self.loss(*tensors_dict)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
def training_extras_init(self, lr_d=1e-3, eps=0.01):
if self.discriminator is not None:
self.discriminator.train()
d_params = filter(
lambda p: p.requires_grad, self.discriminator.parameters()
)
self.d_optimizer = torch.optim.Adam(d_params, lr=lr_d, eps=eps)
def training_extras_end(self):
if self.discriminator is not None:
self.discriminator.eval()
|
/scArchest-0.0.1-py3-none-any.whl/scarches/trainers/scvi/total_inference.py
| 0.934947 | 0.289862 |
total_inference.py
|
pypi
|
import logging
import time
import numpy as np
import torch
import torch.nn as nn
import anndata
from abc import abstractmethod
from collections import defaultdict, OrderedDict
from itertools import cycle
from typing import List
from sklearn.model_selection._split import _validate_shuffle_split
from torch.utils.data.sampler import SubsetRandomSampler
from scvi._utils import track
from scvi import _CONSTANTS
from scarchest.dataset.scvi import ScviDataLoader
logger = logging.getLogger(__name__)
class Trainer:
"""The abstract Trainer class for training a PyTorch model and monitoring its statistics.
It should be inherited at least with a ``.loss()`` function to be optimized in the training loop.
Parameters
----------
model :
A model instance from class ``VAE``, ``VAEC``, ``SCANVI``
adata:
A registered anndata object
use_cuda :
Default: ``True``.
metrics_to_monitor :
A list of the metrics to monitor. If not specified, will use the
``default_metrics_to_monitor`` as specified in each . Default: ``None``.
benchmark :
if True, prevents statistics computation in the training. Default: ``False``.
frequency :
The frequency at which to keep track of statistics. Default: ``None``.
early_stopping_metric :
The statistics on which to perform early stopping. Default: ``None``.
save_best_state_metric :
The statistics on which we keep the network weights achieving the best store, and
restore them at the end of training. Default: ``None``.
on :
The data_loader name reference for the ``early_stopping_metric`` and ``save_best_state_metric``, that
should be specified if any of them is. Default: ``None``.
show_progbar :
If False, disables progress bar.
seed :
Random seed for train/test/validate split
Returns
-------
"""
default_metrics_to_monitor = []
def __init__(
self,
model,
adata: anndata.AnnData,
use_cuda: bool = True,
metrics_to_monitor: List = None,
benchmark: bool = False,
frequency: int = None,
weight_decay: float = 1e-6,
early_stopping_kwargs: dict = None,
data_loader_kwargs: dict = None,
silent: bool = False,
batch_size: int = 128,
seed: int = 0,
max_nans: int = 10,
):
# Model, dataset management
self.model = model
self.adata = adata
self._scvi_data_loaders = OrderedDict()
self.seed = seed # For train/test splitting
self.use_cuda = use_cuda and torch.cuda.is_available()
if self.use_cuda:
self.model.cuda()
# Data loader attributes
self.batch_size = batch_size
self.data_loader_kwargs = {"pin_memory": use_cuda}
data_loader_kwargs = data_loader_kwargs if data_loader_kwargs else dict()
self.data_loader_kwargs.update(data_loader_kwargs)
# Optimization attributes
self.optimizer = None
self.weight_decay = weight_decay
self.n_epochs = None
self.epoch = -1 # epoch = self.epoch + 1 in compute metrics
self.training_time = 0
self.n_iter = 0
# Training NaNs handling
self.max_nans = max_nans
self.current_loss = None # torch.Tensor training loss
self.previous_loss_was_nan = False
self.nan_counter = 0 # Counts occuring NaNs during training
# Metrics and early stopping
self.compute_metrics_time = None
if metrics_to_monitor is not None:
self.metrics_to_monitor = set(metrics_to_monitor)
else:
self.metrics_to_monitor = set(self.default_metrics_to_monitor)
early_stopping_kwargs = (
early_stopping_kwargs if early_stopping_kwargs else dict()
)
self.early_stopping = EarlyStopping(**early_stopping_kwargs)
self.benchmark = benchmark
self.frequency = frequency if not benchmark else None
self.history = defaultdict(list)
self.best_state_dict = self.model.state_dict()
self.best_epoch = self.epoch
if self.early_stopping.early_stopping_metric:
self.metrics_to_monitor.add(self.early_stopping.early_stopping_metric)
self.silent = silent
@torch.no_grad()
def compute_metrics(self):
begin = time.time()
epoch = self.epoch + 1
if self.frequency and (
epoch == 0 or epoch == self.n_epochs or (epoch % self.frequency == 0)
):
with torch.set_grad_enabled(False):
self.model.eval()
logger.debug("\nEPOCH [%d/%d]: " % (epoch, self.n_epochs))
for name, scdl in self._scvi_data_loaders.items():
message = " ".join([s.capitalize() for s in name.split("_")[-2:]])
if scdl.n_cells < 5:
logging.debug(
message + " is too small to track metrics (<5 samples)"
)
continue
if hasattr(scdl, "to_monitor"):
for metric in scdl.to_monitor:
if metric not in self.metrics_to_monitor:
logger.debug(message)
result = getattr(scdl, metric)()
self.history[metric + "_" + name] += [result]
for metric in self.metrics_to_monitor:
result = getattr(scdl, metric)()
self.history[metric + "_" + name] += [result]
self.model.train()
self.compute_metrics_time += time.time() - begin
def train(self, n_epochs=400, lr=1e-3, eps=0.01, params=None, **extras_kwargs):
begin = time.time()
self.model.train()
if params is None:
params = filter(lambda p: p.requires_grad, self.model.parameters())
if len(list(params)) == 0:
return
else:
params = filter(lambda p: p.requires_grad, self.model.parameters())
self.optimizer = torch.optim.Adam(
params, lr=lr, eps=eps, weight_decay=self.weight_decay
)
# Initialization of other model's optimizers
self.training_extras_init(**extras_kwargs)
self.compute_metrics_time = 0
self.n_epochs = n_epochs
self.compute_metrics()
self.on_training_begin()
for self.epoch in track(
range(n_epochs), description="Training...", disable=self.silent
):
self.on_epoch_begin()
for tensors_dict in self.data_loaders_loop():
if tensors_dict[0][_CONSTANTS.X_KEY].shape[0] < 3:
continue
self.on_iteration_begin()
# Update the model's parameters after seeing the data
self.on_training_loop(tensors_dict)
# Checks the training status, ensures no nan loss
self.on_iteration_end()
# Computes metrics and controls early stopping
if not self.on_epoch_end():
break
if self.early_stopping.save_best_state_metric is not None:
self.model.load_state_dict(self.best_state_dict)
self.compute_metrics()
self.model.eval()
self.training_extras_end()
self.training_time += (time.time() - begin) - self.compute_metrics_time
self.on_training_end()
def on_training_loop(self, tensors_dict):
if self.model.freeze:
for name, module in self.model.named_modules():
if isinstance(module, nn.BatchNorm1d):
if not module.weight.requires_grad:
module.affine = False
module.track_running_stats = False
self.current_loss = loss = self.loss(*tensors_dict)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
def training_extras_init(self, **extras_kwargs):
"""Other necessary models to simultaneously train."""
pass
def training_extras_end(self):
"""Place to put extra models in eval mode, etc."""
pass
def on_training_begin(self):
pass
def on_epoch_begin(self):
# Epochs refer to a pass through the entire dataset (in minibatches)
pass
def on_epoch_end(self):
self.compute_metrics()
on = self.early_stopping.on
early_stopping_metric = self.early_stopping.early_stopping_metric
save_best_state_metric = self.early_stopping.save_best_state_metric
if save_best_state_metric is not None and on is not None:
if self.early_stopping.update_state(
self.history[save_best_state_metric + "_" + on][-1]
):
self.best_state_dict = self.model.state_dict()
self.best_epoch = self.epoch
continue_training = True
if early_stopping_metric is not None and on is not None:
continue_training, reduce_lr = self.early_stopping.update(
self.history[early_stopping_metric + "_" + on][-1]
)
if reduce_lr:
logger.info("Reducing LR on epoch {}.".format(self.epoch))
for param_group in self.optimizer.param_groups:
param_group["lr"] *= self.early_stopping.lr_factor
return continue_training
def on_iteration_begin(self):
# Iterations refer to minibatches
pass
def on_iteration_end(self):
self.check_training_status()
self.n_iter += 1
def on_training_end(self):
pass
def check_training_status(self):
"""
Checks if loss is admissible.
If not, training is stopped after max_nans consecutive inadmissible loss
loss corresponds to the training loss of the model.
`max_nans` is the maximum number of consecutive NaNs after which a ValueError will be
"""
loss_is_nan = torch.isnan(self.current_loss).item()
if loss_is_nan:
logger.warning("Model training loss was NaN")
self.nan_counter += 1
self.previous_loss_was_nan = True
else:
self.nan_counter = 0
self.previous_loss_was_nan = False
if self.nan_counter >= self.max_nans:
raise ValueError(
"Loss was NaN {} consecutive times: the model is not training properly. "
"Consider using a lower learning rate.".format(self.max_nans)
)
@property
@abstractmethod
def scvi_data_loaders_loop(self):
pass
def data_loaders_loop(self):
"""Returns an zipped iterable corresponding to loss signature."""
data_loaders_loop = [
self._scvi_data_loaders[name] for name in self.scvi_data_loaders_loop
]
return zip(
data_loaders_loop[0],
*[cycle(data_loader) for data_loader in data_loaders_loop[1:]]
)
def register_data_loader(self, name, value):
name = name.strip("_")
self._scvi_data_loaders[name] = value
def __getattr__(self, name):
if "_scvi_data_loaders" in self.__dict__:
_scvi_data_loaders = self.__dict__["_scvi_data_loaders"]
if name.strip("_") in _scvi_data_loaders:
return _scvi_data_loaders[name.strip("_")]
return object.__getattribute__(self, name)
def __delattr__(self, name):
if name.strip("_") in self._scvi_data_loaders:
del self._scvi_data_loaders[name.strip("_")]
else:
object.__delattr__(self, name)
def __setattr__(self, name, value):
if isinstance(value, ScviDataLoader):
name = name.strip("_")
self.register_data_loader(name, value)
else:
object.__setattr__(self, name, value)
def train_test_validation(
self,
model=None,
adata=None,
train_size=0.9,
test_size=None,
type_class=ScviDataLoader,
):
"""
Creates data loaders ``train_set``, ``test_set``, ``validation_set``.
If ``train_size + test_size < 1`` then ``validation_set`` is non-empty.
Parameters
----------
train_size :
float, or None (default is 0.9)
test_size :
float, or None (default is None)
model :
(Default value = None)
adata:
(Default value = None)
type_class :
(Default value = ScviDataLoader)
"""
train_size = float(train_size)
if train_size > 1.0 or train_size <= 0.0:
raise ValueError(
"train_size needs to be greater than 0 and less than or equal to 1"
)
model = self.model if model is None and hasattr(self, "model") else model
# what to do here if it has the attribute modle
adata = self.adata if adata is None and hasattr(self, "model") else adata
n = len(adata)
try:
n_train, n_test = _validate_shuffle_split(n, test_size, train_size)
except ValueError:
if train_size != 1.0:
raise ValueError(
"Choice of train_size={} and test_size={} not understood".format(
train_size, test_size
)
)
n_train, n_test = n, 0
random_state = np.random.RandomState(seed=self.seed)
permutation = random_state.permutation(n)
indices_test = permutation[:n_test]
indices_train = permutation[n_test: (n_test + n_train)]
indices_validation = permutation[(n_test + n_train):]
return (
self.create_scvi_dl(
model, adata, indices=indices_train, type_class=type_class
),
self.create_scvi_dl(
model, adata, indices=indices_test, type_class=type_class
),
self.create_scvi_dl(
model, adata, indices=indices_validation, type_class=type_class
),
)
def create_scvi_dl(
self,
model=None,
adata: anndata.AnnData = None,
shuffle=False,
indices=None,
type_class=ScviDataLoader,
):
model = self.model if model is None and hasattr(self, "model") else model
adata = self.adata if adata is None and hasattr(self, "model") else adata
return type_class(
model,
adata,
shuffle=shuffle,
indices=indices,
use_cuda=self.use_cuda,
batch_size=self.batch_size,
data_loader_kwargs=self.data_loader_kwargs,
)
class SequentialSubsetSampler(SubsetRandomSampler):
def __init__(self, indices):
self.indices = np.sort(indices)
def __iter__(self):
return iter(self.indices)
class EarlyStopping:
def __init__(
self,
early_stopping_metric: str = None,
save_best_state_metric: str = None,
on: str = "test_set",
patience: int = 15,
threshold: int = 3,
benchmark: bool = False,
reduce_lr_on_plateau: bool = False,
lr_patience: int = 10,
lr_factor: float = 0.5,
scvi_data_loader_class=ScviDataLoader,
):
self.benchmark = benchmark
self.patience = patience
self.threshold = threshold
self.epoch = 0
self.wait = 0
self.wait_lr = 0
self.mode = (
getattr(scvi_data_loader_class, early_stopping_metric).mode
if early_stopping_metric is not None
else None
)
# We set the best to + inf because we're dealing with a loss we want to minimize
self.current_performance = np.inf
self.best_performance = np.inf
self.best_performance_state = np.inf
# If we want to maximize, we start at - inf
if self.mode == "max":
self.best_performance *= -1
self.current_performance *= -1
self.mode_save_state = (
getattr(ScviDataLoader, save_best_state_metric).mode
if save_best_state_metric is not None
else None
)
if self.mode_save_state == "max":
self.best_performance_state *= -1
self.early_stopping_metric = early_stopping_metric
self.save_best_state_metric = save_best_state_metric
self.on = on
self.reduce_lr_on_plateau = reduce_lr_on_plateau
self.lr_patience = lr_patience
self.lr_factor = lr_factor
def update(self, scalar):
self.epoch += 1
if self.benchmark:
continue_training = True
reduce_lr = False
elif self.wait >= self.patience:
continue_training = False
reduce_lr = False
else:
# Check if we should reduce the learning rate
if not self.reduce_lr_on_plateau:
reduce_lr = False
elif self.wait_lr >= self.lr_patience:
reduce_lr = True
self.wait_lr = 0
else:
reduce_lr = False
# Shift
self.current_performance = scalar
# Compute improvement
if self.mode == "max":
improvement = self.current_performance - self.best_performance
elif self.mode == "min":
improvement = self.best_performance - self.current_performance
else:
raise NotImplementedError("Unknown optimization mode")
# updating best performance
if improvement > 0:
self.best_performance = self.current_performance
if improvement < self.threshold:
self.wait += 1
self.wait_lr += 1
else:
self.wait = 0
self.wait_lr = 0
continue_training = True
if not continue_training:
# FIXME: log total number of epochs run
logger.info(
"\nStopping early: no improvement of more than "
+ str(self.threshold)
+ " nats in "
+ str(self.patience)
+ " epochs"
)
logger.info(
"If the early stopping criterion is too strong, "
"please instantiate it with different parameters in the train method."
)
return continue_training, reduce_lr
def update_state(self, scalar):
improved = (
self.mode_save_state == "max" and scalar - self.best_performance_state > 0
) or (
self.mode_save_state == "min" and self.best_performance_state - scalar > 0
)
if improved:
self.best_performance_state = scalar
return improved
|
/scArchest-0.0.1-py3-none-any.whl/scarches/trainers/scvi/trainer.py
| 0.919665 | 0.415017 |
trainer.py
|
pypi
|
import time
import torch
from sklearn.cluster import KMeans
from torch.utils.data import DataLoader
from scarchest.dataset.mars import MetaAnnotatedDataset
from scarchest.dataset.trvae import AnnotatedDataset
from scarchest.models import MARS
from ._utils import split_meta_train_tasks, euclidean_dist, print_meta_progress
from .meta import MetaTrainer
import scanpy as sc
class MARSTrainer(MetaTrainer):
def __init__(self, model: MARS, adata: sc.AnnData, task_key: str, cell_type_key: str, n_clusters: int,
meta_test_tasks: list,
tau: float = 0.2, eta: float = 1.0, **kwargs):
super().__init__(model, adata, task_key, **kwargs)
self.cell_type_key = cell_type_key
self.n_clusters = n_clusters
self.meta_test_tasks = meta_test_tasks
self.tau = tau
self.eta = eta
self.pre_train_n_epochs = kwargs.pop('pre_train_n_epochs', 100)
self.pre_train_batch_size = kwargs.pop('pre_train_batch_size', 128)
def on_training_begin(self):
self.meta_adata = MetaAnnotatedDataset(adata=self.adata,
task_key=self.task_key,
meta_test_task=self.meta_test_tasks[0],
cell_type_key=self.cell_type_key,
task_encoder=self.model.condition_encoder,
)
self.meta_train_data_loaders_tr, self.meta_train_data_loaders_ts = split_meta_train_tasks(self.meta_adata,
self.train_frac,
stratify=True,
batch_size=self.batch_size,
num_workers=self.n_workers)
self.meta_test_data_loader = pre_train_data_loader = DataLoader(dataset=self.meta_adata.meta_test_task_adata,
batch_size=self.pre_train_batch_size,
num_workers=self.n_workers)
self.pre_train_with_meta_test(pre_train_data_loader)
self.meta_train_landmarks, self.meta_test_landmarks = self.initialize_landmarks()
self.optimizer = torch.optim.Adam(params=list(self.model.encoder.parameters()), lr=self.learning_rate)
self.meta_test_landmark_optimizer = torch.optim.Adam(params=[self.meta_test_landmarks], lr=self.learning_rate)
self.lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer=self.optimizer,
gamma=self.lr_gamma,
step_size=self.lr_step_size)
def pre_train_with_meta_test(self, pre_train_data_loader):
pre_train_optimizer = torch.optim.Adam(params=list(self.model.parameters()), lr=self.pre_train_learning_rate)
for _ in range(self.pre_train_n_epochs):
for _, batch_data in enumerate(pre_train_data_loader):
x = batch_data['x'].to(self.device)
c = batch_data['c'].to(self.device)
_, decoded, loss, recon_loss, kl_loss = self.model(x, c)
pre_train_optimizer.zero_grad()
loss.backward()
if self.clip_value > 0:
torch.nn.utils.clip_grad_value_(self.model.parameters(), self.clip_value)
pre_train_optimizer.step()
def initialize_landmarks(self):
def k_means_initalization(dataset: AnnotatedDataset, n_clusters):
encoded = self.model.get_latent(dataset.data, dataset.conditions)
k_means = KMeans(n_clusters=n_clusters, random_state=0).fit(encoded)
return torch.tensor(k_means.cluster_centers_, device=self.device)
meta_train_landmarks = [
torch.zeros(size=(len(adataset.unique_cell_types), self.model.z_dim), requires_grad=True,
device=self.device) for adataset in self.meta_adata.meta_train_tasks_adata]
meta_test_landmarks = torch.zeros(size=(self.n_clusters, self.model.z_dim), requires_grad=True,
device=self.device)
k_means_init_train = [k_means_initalization(adataset, n_clusters=len(adataset.unique_cell_types))
for adataset in self.meta_adata.meta_train_tasks_adata]
k_means_init_test = k_means_initalization(self.meta_adata.meta_test_task_adata,
n_clusters=self.n_clusters)
with torch.no_grad():
[landmark.copy_(k_means_init_train[idx]) for idx, landmark in enumerate(meta_train_landmarks)]
meta_test_landmarks.copy_(k_means_init_test)
return meta_train_landmarks, meta_test_landmarks
def train(self,
n_epochs=400,
evaluate_on_meta_test=True,
):
begin = time.time()
# Initialize Train/Val Data, Optimizer, Sampler, and Dataloader
self.on_training_begin()
for self.epoch in range(n_epochs):
self.on_epoch_begin()
loss, acc = self.on_epoch()
# Validation of Model, Monitoring, Early Stopping
if evaluate_on_meta_test:
valid_loss, valid_acc, test_accuracy = self.on_epoch_end(evaluate_on_meta_test)
else:
valid_loss, valid_acc = self.on_epoch_end(evaluate_on_meta_test)
if self.use_early_stopping:
if not self.check_early_stop():
break
logs = {
'loss': [loss],
'acc': [acc],
'val_loss': [valid_loss],
'val_acc': [valid_acc],
}
if evaluate_on_meta_test:
logs['test_accuracy'] = [test_accuracy]
if self.monitor:
print_meta_progress(self.epoch, logs, n_epochs)
if hasattr(self, 'best_state_dict') and self.best_state_dict is not None:
print("Saving best state of network...")
print("Best State was in Epoch", self.best_epoch)
self.model.load_state_dict(self.best_state_dict)
self.model.eval()
self.training_time += (time.time() - begin)
# Empty at the moment
self.on_training_end()
def on_epoch(self): # EM step perfomed on each epoch
self.model.train()
# Update Landmarks
for param in self.model.parameters():
param.requires_grad = False
self.meta_test_landmarks.requires_grad = False
self.meta_test_landmark_optimizer.zero_grad()
for idx, task_data_loader_tr in enumerate(self.meta_train_data_loaders_tr):
for task_data in task_data_loader_tr:
X = task_data['x'].to(self.device)
c = task_data['c'].to(self.device)
y = task_data['y'].to(self.device)
encoded, _, _, _, _ = self.model(X, c)
current_meta_train_landmarks = self.update_meta_train_landmarks(encoded, y,
self.meta_train_landmarks[idx],
self.tau)
self.meta_train_landmarks[idx] = current_meta_train_landmarks.data
self.meta_test_landmarks.requires_grad = True
for task_data in self.meta_test_data_loader:
X = task_data['x'].to(self.device)
c = task_data['c'].to(self.device)
encoded, _, loss, _, _ = self.model(X, c)
loss = self.eta * loss + self.test_loss(encoded, self.meta_test_landmarks, self.tau)
loss.backward()
self.meta_test_landmark_optimizer.step()
# Update Encoder
for param in self.model.parameters():
param.requires_grad = True
self.meta_test_landmarks.requires_grad = False
self.optimizer.zero_grad()
loss = torch.tensor(0.0)
acc = torch.tensor(0.0)
for idx, task_data_loader_tr in enumerate(self.meta_train_data_loaders_tr):
for batch_data in task_data_loader_tr:
X = batch_data['x'].to(self.device)
c = batch_data['c'].to(self.device)
y = batch_data['y'].to(self.device)
encoded, _, loss, _, _ = self.model(X, c)
task_loss, task_acc = self.task_loss(encoded, y, self.meta_train_landmarks[idx])
loss = self.eta * loss + task_loss
acc += task_acc
n_tasks = len(self.meta_train_data_loaders_tr)
acc /= n_tasks
for batch_data in self.meta_test_data_loader:
X = batch_data['x'].to(self.device)
c = batch_data['c'].to(self.device)
encoded, _, loss, _, _ = self.model(X, c)
loss = self.eta * loss + self.test_loss(encoded, self.meta_test_landmarks, self.tau)
loss = loss / (n_tasks + 1)
loss.backward()
self.optimizer.step()
return loss, acc
def on_epoch_end(self, evaluate_on_meta_test=False):
self.model.eval()
n_tasks = len(self.meta_train_data_loaders_ts)
with torch.no_grad():
valid_loss, valid_acc = 0.0, 0.0
for idx, task_data_loader_tr in enumerate(self.meta_train_data_loaders_ts):
for task_data in task_data_loader_tr:
X = task_data['x'].to(self.device)
c = task_data['c'].to(self.device)
y = task_data['y'].to(self.device)
encoded, _, _, _, _ = self.model(X, c)
task_loss, task_acc = self.task_loss(encoded, y, self.meta_train_landmarks[idx])
valid_loss += task_loss
valid_acc += task_acc.item()
mean_accuracy = valid_acc / n_tasks
mean_loss = valid_loss / n_tasks
if evaluate_on_meta_test:
test_accuracy = 0.0
with torch.no_grad():
for batch_data in self.meta_test_data_loader:
X = batch_data['x'].to(self.device)
c = batch_data['c'].to(self.device)
y = batch_data['y'].to(self.device)
encoded, _, _, _, _ = self.model(X, c)
test_accuracy += self.evaluate_on_unannotated_dataset(encoded, y) * X.shape[0]
test_accuracy /= len(self.meta_test_data_loader.dataset)
return mean_loss, mean_accuracy, test_accuracy
else:
return mean_loss, mean_accuracy
def evaluate_on_unannotated_dataset(self, encoded, y_true):
distances = euclidean_dist(encoded, self.meta_test_landmarks)
_, y_pred = torch.max(-distances, dim=1)
accuracy = y_pred.eq(y_true).float().mean()
return accuracy
def task_loss(self, embeddings, labels, landmarks):
n_samples = embeddings.shape[0]
unique_labels = torch.unique(labels, sorted=True)
class_indices = list(map(lambda x: labels.eq(x).nonzero(), unique_labels))
for idx, value in enumerate(unique_labels):
labels[labels == value] = idx
distances = euclidean_dist(embeddings, landmarks)
loss = torch.stack(
[distances[indices, landmark_index].sum(0) for landmark_index, indices in
enumerate(class_indices)]).sum() / n_samples
_, y_pred = torch.max(-distances, dim=1)
accuracy = y_pred.eq(labels.squeeze()).float().mean()
return loss, accuracy
def test_loss(self, embeddings, landmarks, tau):
distances = euclidean_dist(embeddings, landmarks)
min_distances, y_hat = torch.min(distances, dim=1)
unique_predicted_labels = torch.unique(y_hat, sorted=True)
loss = torch.stack(
[min_distances[y_hat == unique_y_hat].mean(0) for unique_y_hat in unique_predicted_labels]).mean()
if tau > 0:
landmarks_distances = euclidean_dist(landmarks, landmarks)
n_landmarks = landmarks.shape[0]
loss -= torch.sum(landmarks_distances) * tau / (n_landmarks * (n_landmarks - 1))
return loss
def update_meta_train_landmarks(self, embeddings, labels, previous_landmarks, tau):
unique_labels = torch.unique(labels, sorted=True)
class_indices = list(map(lambda y: labels.eq(y).nonzero(), unique_labels))
landmarks_mean = torch.stack([embeddings[class_index].mean(0) for class_index in class_indices]).squeeze()
if previous_landmarks is None or tau == 0:
return landmarks_mean
previous_landmarks_sum = previous_landmarks.sum(0)
n_landmarks = previous_landmarks.shape[0]
landmarks_distance_partial = (tau / (n_landmarks - 1)) * torch.stack(
[previous_landmarks_sum - landmark for landmark in previous_landmarks])
landmarks = (1 / (1 - tau)) * (landmarks_mean - landmarks_distance_partial)
return landmarks
def on_epoch_begin(self):
pass
def on_iteration_begin(self):
pass
def on_iteration_end(self):
pass
def on_training_end(self):
pass
def check_early_stop(self):
return True
|
/scArchest-0.0.1-py3-none-any.whl/scarches/trainers/mars/mars_meta_trainer.py
| 0.842734 | 0.242301 |
mars_meta_trainer.py
|
pypi
|
import time
import scanpy as sc
import torch
from torch.utils.data import DataLoader
from scarchest.models import MARS
from scarchest.trainers.trvae._utils import make_dataset
from ._utils import print_meta_progress
from .meta import MetaTrainer
class MARSPreTrainer(MetaTrainer):
def __init__(self, model: MARS, adata: sc.AnnData, task_key: str,
**kwargs):
super().__init__(model, adata, task_key, **kwargs)
def on_training_begin(self):
self.train_dataset, self.valid_dataset = make_dataset(self.adata,
train_frac=self.train_frac,
use_stratified_split=True,
condition_key=self.task_key,
cell_type_key=None,
size_factor_key=None,
condition_encoder=self.model.condition_encoder,
)
self.train_data_loader = DataLoader(dataset=self.train_dataset,
batch_size=self.batch_size,
num_workers=self.n_workers)
self.valid_data_loader = DataLoader(dataset=self.valid_dataset,
batch_size=len(self.valid_dataset),
num_workers=1)
self.optimizer = torch.optim.Adam(params=list(self.model.parameters()), lr=self.learning_rate)
self.lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer=self.optimizer,
gamma=self.lr_gamma,
step_size=self.lr_step_size)
def train(self,
n_epochs=400,
):
begin = time.time()
# Initialize Train/Val Data, Optimizer, Sampler, and Dataloader
self.on_training_begin()
for self.epoch in range(n_epochs):
self.on_epoch_begin()
loss, recon_loss, kl_loss = self.on_epoch()
# Validation of Model, Monitoring, Early Stopping
valid_loss, valid_recon_loss, valid_kl_loss = self.on_epoch_end()
if self.use_early_stopping:
if not self.check_early_stop():
break
logs = {
'loss': [loss],
'recon_loss': [recon_loss],
'kl_loss': [kl_loss],
'val_loss': [valid_loss],
'val_recon_loss': [valid_recon_loss],
'val_kl_loss': [valid_kl_loss],
}
if self.monitor:
print_meta_progress(self.epoch, logs, n_epochs)
if hasattr(self, 'best_state_dict') and self.best_state_dict is not None:
print("Saving best state of network...")
print("Best State was in Epoch", self.best_epoch)
self.model.load_state_dict(self.best_state_dict)
self.model.eval()
self.training_time += (time.time() - begin)
# Empty at the moment
self.on_training_end()
def on_epoch(self):
self.model.train()
loss = torch.tensor(0.0)
recon_loss = torch.tensor(0.0)
kl_loss = torch.tensor(0.0)
for batch_data in self.train_data_loader:
x = batch_data['x'].to(self.device)
c = batch_data['c'].to(self.device)
_, decoded, batch_loss, batch_recon_loss, batch_kl_loss = self.model(x, c)
loss += batch_loss * len(batch_data)
kl_loss += batch_kl_loss * len(batch_data)
recon_loss += batch_recon_loss * len(batch_data)
self.optimizer.zero_grad()
batch_loss.backward()
if self.clip_value > 0:
torch.nn.utils.clip_grad_value_(self.model.parameters(), self.clip_value)
self.optimizer.step()
loss /= len(self.train_dataset)
recon_loss /= len(self.train_dataset)
kl_loss /= len(self.train_dataset)
return loss, recon_loss, kl_loss
def on_epoch_end(self, evaluate_on_meta_test=False):
self.model.eval()
with torch.no_grad():
valid_loss, valid_recon_loss, valid_kl_loss = 0.0, 0.0, 0.0
for valid_data in self.valid_data_loader:
x = valid_data['x'].to(self.device)
c = valid_data['c'].to(self.device)
_, _, batch_loss, batch_recon_loss, batch_kl_loss = self.model(x, c)
valid_loss += batch_loss * len(valid_data)
valid_recon_loss += batch_recon_loss * len(valid_data)
valid_kl_loss += batch_kl_loss * len(valid_data)
valid_loss /= len(self.valid_dataset)
valid_kl_loss /= len(self.valid_dataset)
valid_recon_loss /= len(self.valid_dataset)
return valid_loss, valid_recon_loss, valid_kl_loss
def on_epoch_begin(self):
pass
def on_iteration_begin(self):
pass
def on_iteration_end(self):
pass
def on_training_end(self):
pass
def check_early_stop(self):
return True
|
/scArchest-0.0.1-py3-none-any.whl/scarches/trainers/mars/unsupervised.py
| 0.848157 | 0.1779 |
unsupervised.py
|
pypi
|
import torch
import numpy as np
from torch.utils.data import DataLoader, SubsetRandomSampler
from scarchest.dataset.mars import MetaAnnotatedDataset
from scarchest.trainers.trvae._utils import _print_progress_bar
def print_meta_progress(epoch, logs, n_epochs=10000):
"""Creates Message for '_print_progress_bar'.
Parameters
----------
epoch: Integer
Current epoch iteration.
logs: dict
List of all current losses.
n_epochs: Integer
Maximum value of epochs.
Returns
-------
"""
message = f' - loss: {logs["loss"][-1]:.4f}'
train_keys = [key for key in sorted(list(logs.keys())) if (not key.startswith('val_') and not key.startswith('test_') and key != 'loss')]
for key in train_keys:
message += f' - {key}: {logs[key][-1]:.4f}'
message += f' - val_loss: {logs["val_loss"][-1]:.4f}'
valid_keys = [key for key in sorted(list(logs.keys())) if (key.startswith('val_') and key != 'val_loss')]
for key in valid_keys:
message += f' - {key}: {logs[key][-1]:.4f}'
test_keys = [key for key in sorted(list(logs.keys())) if (key.startswith('test_'))]
for key in test_keys:
message += f' - {key}: {logs[key][-1]:.4f}'
_print_progress_bar(epoch + 1, n_epochs, prefix='', suffix=message, decimals=1, length=20)
def split_meta_train_tasks(meta_adata: MetaAnnotatedDataset,
train_fraction: float = 0.8,
stratify: bool = False,
batch_size: int = 32,
num_workers=6):
train_data_loaders, valid_data_loaders = [], []
for idx, meta_train_dataset in enumerate(meta_adata.meta_train_tasks_adata):
np.random.seed(2020 * idx)
n_samples = len(meta_train_dataset)
indices = np.arange(n_samples)
np.random.shuffle(indices)
train_idx = indices[:int(train_fraction * n_samples)]
valid_idx = indices[int(train_fraction * n_samples):]
train_data_loader = DataLoader(dataset=meta_train_dataset,
sampler=SubsetRandomSampler(train_idx),
num_workers=num_workers,
batch_size=batch_size,
pin_memory=True)
valid_data_loader = DataLoader(dataset=meta_train_dataset,
sampler=SubsetRandomSampler(valid_idx),
num_workers=num_workers,
batch_size=batch_size,
pin_memory=True)
train_data_loaders.append(train_data_loader)
valid_data_loaders.append(valid_data_loader)
return train_data_loaders, valid_data_loaders
def euclidean_dist(x, y):
'''
Compute euclidean distance between two tensors
'''
# x: N x D
# y: M x D
n = x.size(0)
m = y.size(0)
d = x.size(1)
if d != y.size(1):
raise Exception
x = x.unsqueeze(1).expand(n, m, d)
y = y.unsqueeze(0).expand(n, m, d)
return torch.pow(x - y, 2).sum(2)
|
/scArchest-0.0.1-py3-none-any.whl/scarches/trainers/mars/_utils.py
| 0.893675 | 0.331241 |
_utils.py
|
pypi
|
from abc import abstractmethod
import torch
import torch.nn as nn
from collections import defaultdict
import numpy as np
import time
from torch.utils.data import DataLoader
from torch.utils.data import WeightedRandomSampler
from scarchest.utils.monitor import EarlyStopping
from ._utils import make_dataset, custom_collate, print_progress
class Trainer:
def __init__(self,
model,
adata,
condition_key: str = None,
cell_type_key: str = None,
size_factor_key: str = None,
is_label_key: str = None,
clip_value: float = 0.0,
weight_decay: float = 0.04,
train_frac: float = 0.9,
early_stopping_kwargs: dict = None,
batch_size: int = 512,
n_samples: int = None,
n_workers: int = 0,
**kwargs):
self.adata = adata
self.condition_key = condition_key
self.cell_type_key = cell_type_key
self.size_factor_key = size_factor_key
self.is_label_key = is_label_key
self.clip_value = clip_value
self.weight_decay = weight_decay
self.train_frac = train_frac
early_stopping_kwargs = (early_stopping_kwargs if early_stopping_kwargs else dict())
self.batch_size = batch_size
self.n_workers = n_workers
self.seed = kwargs.pop("seed", 2020)
self.use_stratified_sampling = kwargs.pop("use_stratified_sampling", True)
self.use_early_stopping = kwargs.pop("use_early_stopping", True)
self.monitor = kwargs.pop("monitor", True)
self.use_stratified_split = kwargs.pop("use_stratified_split", False)
self.early_stopping = EarlyStopping(**early_stopping_kwargs)
torch.manual_seed(self.seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(self.seed)
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.model = model.to(self.device)
self.model.device = self.device
self.epoch = -1
self.iter = 0
self.best_epoch = None
self.best_state_dict = None
self.current_loss = None
self.previous_loss_was_nan = False
self.nan_counter = 0
self.optimizer = None
self.lr_scheduler = None
self.training_time = 0
self.train_data = None
self.valid_data = None
self.sampler = None
self.dataloader_train = None
self.dataloader_valid = None
self.n_samples = n_samples
self.iters_per_epoch = None
self.val_iters_per_epoch = None
self.iter_logs = defaultdict(list)
self.logs = defaultdict(list)
def on_training_begin(self):
"""
Initializes Train-/Test Data and Dataloaders with custom_collate and WeightedRandomSampler for Trainloader.
Returns:
"""
# Create Train/Valid AnnotatetDataset objects
self.train_data, self.valid_data = make_dataset(self.adata,
train_frac=self.train_frac,
use_stratified_split=self.use_stratified_split,
condition_key=self.condition_key,
cell_type_key=self.cell_type_key,
size_factor_key=self.size_factor_key,
condition_encoder=self.model.condition_encoder,
cell_type_encoder=None
)
print("Traindata:", len(self.train_data))
for i in range(len(self.train_data.unique_conditions)):
print("Condition:", i, "Counts in TrainData:", np.count_nonzero(self.train_data.conditions == i))
if self.n_samples is None or self.n_samples > len(self.train_data):
self.n_samples = len(self.train_data)
self.iters_per_epoch = int(np.ceil(self.n_samples / self.batch_size))
if self.use_stratified_sampling:
# Create Sampler and Dataloaders
stratifier_weights = torch.tensor(self.train_data.stratifier_weights, device=self.device)
self.sampler = WeightedRandomSampler(stratifier_weights,
num_samples=self.n_samples,
replacement=True)
self.dataloader_train = torch.utils.data.DataLoader(dataset=self.train_data,
batch_size=self.batch_size,
sampler=self.sampler,
collate_fn=custom_collate,
num_workers=self.n_workers)
else:
self.dataloader_train = torch.utils.data.DataLoader(dataset=self.train_data,
batch_size=self.batch_size,
shuffle=True,
collate_fn=custom_collate,
num_workers=self.n_workers)
if self.valid_data is not None:
print("Valid_data", len(self.valid_data))
for i in range(len(self.valid_data.unique_conditions)):
print("Condition:", i, "Counts in TrainData:", np.count_nonzero(self.valid_data.conditions == i))
val_batch_size = self.batch_size
if self.batch_size > len(self.valid_data):
val_batch_size = len(self.valid_data)
self.val_iters_per_epoch = int(np.ceil(len(self.valid_data) / self.batch_size))
self.dataloader_valid = torch.utils.data.DataLoader(dataset=self.valid_data,
batch_size=val_batch_size,
shuffle=True,
collate_fn=custom_collate,
num_workers=self.n_workers)
@abstractmethod
def on_epoch_begin(self):
pass
@abstractmethod
def loss(self, **kwargs):
pass
@abstractmethod
def on_iteration_begin(self):
pass
def on_iteration(self, batch_data):
# Dont update any weight on first layers except condition weights
if self.model.freeze:
for name, module in self.model.named_modules():
if isinstance(module, nn.BatchNorm1d):
if not module.weight.requires_grad:
module.affine = False
module.track_running_stats = False
# Calculate Loss depending on Trainer/Model
self.current_loss = loss = self.loss(**batch_data)
self.optimizer.zero_grad()
loss.backward()
# Gradient Clipping
if self.clip_value > 0:
torch.nn.utils.clip_grad_value_(self.model.parameters(), self.clip_value)
self.optimizer.step()
@abstractmethod
def on_iteration_end(self):
pass
def on_epoch_end(self):
# Get Train Epoch Logs
for key in self.iter_logs:
if "loss" in key:
self.logs["epoch_" + key].append(
sum(self.iter_logs[key][-self.iters_per_epoch:]) / self.iters_per_epoch)
# Validate Model
if self.valid_data is not None:
self.validate()
# Monitor Logs
if self.monitor:
print_progress(self.epoch, self.logs, self.n_epochs)
def check_early_stop(self):
# Calculate Early Stopping and best state
early_stopping_metric = self.early_stopping.early_stopping_metric
save_best_state_metric = self.early_stopping.save_best_state_metric
if save_best_state_metric is not None and self.early_stopping.update_state(
self.logs[save_best_state_metric][-1]):
self.best_state_dict = self.model.state_dict()
self.best_epoch = self.epoch
continue_training = True
if early_stopping_metric is not None and not self.early_stopping.step(self.logs[early_stopping_metric][-1]):
continue_training = False
return continue_training
# Update Learning Rate
self.lr_scheduler.step()
return continue_training
@abstractmethod
def on_training_end(self):
pass
@torch.no_grad()
def validate(self):
self.model.eval()
# Calculate Validation Losses
for val_iter, batch_data in enumerate(self.dataloader_valid):
for key1 in batch_data:
for key2, batch in batch_data[key1].items():
batch_data[key1][key2] = batch.to(self.device)
val_loss = self.loss(**batch_data)
# Get Validation Logs
for key in self.iter_logs:
if "loss" in key:
self.logs["val_" + key].append(
sum(self.iter_logs[key][-self.val_iters_per_epoch:]) / self.val_iters_per_epoch)
self.model.train()
def train(self,
n_epochs=400,
lr=1e-3,
lr_gamma=1.0,
lr_step_size=100,
eps=0.01):
begin = time.time()
self.model.train()
self.n_epochs = n_epochs
params = filter(lambda p: p.requires_grad, self.model.parameters())
self.optimizer = torch.optim.Adam(params, lr=lr, eps=eps, weight_decay=self.weight_decay)
self.lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer=self.optimizer,
gamma=lr_gamma,
step_size=lr_step_size)
# Initialize Train/Val Data, Sampler, Dataloader
self.on_training_begin()
for self.epoch in range(n_epochs):
# Empty at the moment
self.on_epoch_begin()
for self.iter, batch_data in enumerate(self.dataloader_train):
for key1 in batch_data:
for key2, batch in batch_data[key1].items():
batch_data[key1][key2] = batch.to(self.device)
# Empty at the moment
self.on_iteration_begin()
# Loss Calculation, Gradient Clipping, Freeze first layer, Optimizer Step
self.on_iteration(batch_data)
# Empty at the moment
self.on_iteration_end()
# Validation of Model, Monitoring, Early Stopping
self.on_epoch_end()
if self.use_early_stopping:
if not self.check_early_stop():
break
if self.best_state_dict is not None:
print("Saving best state of network...")
print("Best State was in Epoch", self.best_epoch)
self.model.load_state_dict(self.best_state_dict)
self.model.eval()
self.training_time += (time.time() - begin)
# Empty at the moment
self.on_training_end()
|
/scArchest-0.0.1-py3-none-any.whl/scarches/trainers/trvae/trainer.py
| 0.816882 | 0.21262 |
trainer.py
|
pypi
|
import sys
import numpy as np
import re
import torch
from torch._six import container_abcs
from torch.utils.data import DataLoader, SubsetRandomSampler
from scarchest.dataset.trvae import AnnotatedDataset
def print_progress(epoch, logs, n_epochs=10000):
"""Creates Message for '_print_progress_bar'.
Parameters
----------
epoch: Integer
Current epoch iteration.
logs: dict
Dictionary of all current losses.
n_epochs: Integer
Maximum value of epochs.
Returns
-------
"""
message = ""
for key in logs:
if "loss" in key and ("epoch_" in key or "val_" in key):
message += f" - {key:s}: {logs[key][-1]:7.0f}"
_print_progress_bar(epoch + 1, n_epochs, prefix='', suffix=message, decimals=1, length=20)
def _print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'):
"""Prints out message with a progress bar.
Parameters
----------
iteration: Integer
Current epoch.
total: Integer
Maximum value of epochs.
prefix: String
String before the progress bar.
suffix: String
String after the progress bar.
decimals: Integer
Digits after comma for all the losses.
length: Integer
Length of the progress bar.
fill: String
Symbol for filling the bar.
Returns
-------
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filled_len = int(length * iteration // total)
bar = fill * filled_len + '-' * (length - filled_len)
sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percent, '%', suffix)),
if iteration == total:
sys.stdout.write('\n')
sys.stdout.flush()
def train_test_split(adata, train_frac=0.85, condition_key=None):
"""Splits 'Anndata' object into training and validation data.
Parameters
----------
adata: `~anndata.AnnData`
`AnnData` object for training the model.
train_frac: float
Train-test split fraction. the model will be trained with train_frac for training
and 1-train_frac for validation.
Returns
-------
`AnnData` objects for training and validating the model.
"""
if train_frac == 1:
return adata, None
else:
indices = np.arange(adata.shape[0])
n_val_samples = int(adata.shape[0] * (1 - train_frac))
if condition_key is not None:
conditions = adata.obs[condition_key].unique().tolist()
n_conditions = len(conditions)
n_val_samples_per_condition = int(n_val_samples / n_conditions)
condition_indices_train = []
condition_indices_val = []
for i in range(n_conditions):
idx = indices[adata.obs[condition_key] == conditions[i]]
np.random.shuffle(idx)
condition_indices_val.append(idx[:n_val_samples_per_condition])
condition_indices_train.append(idx[n_val_samples_per_condition:])
train_idx = np.concatenate(condition_indices_train)
val_idx = np.concatenate(condition_indices_val)
else:
np.random.shuffle(indices)
val_idx = indices[:n_val_samples]
train_idx = indices[n_val_samples:]
train_data = adata[train_idx, :]
valid_data = adata[val_idx, :]
return train_data, valid_data
def make_dataset(adata,
train_frac=0.9,
use_stratified_split=False,
condition_key=None,
cell_type_key=None,
size_factor_key=None,
condition_encoder=None,
cell_type_encoder=None,
):
"""Splits 'adata' into train and validation data and converts them into 'CustomDatasetFromAdata' objects.
Parameters
----------
Returns
-------
Training 'CustomDatasetFromAdata' object, Validation 'CustomDatasetFromAdata' object
"""
if use_stratified_split:
train_adata, validation_adata = train_test_split(adata, train_frac, condition_key=condition_key)
else:
train_adata, validation_adata = train_test_split(adata, train_frac)
data_set_train = AnnotatedDataset(train_adata,
condition_key=condition_key,
cell_type_key=cell_type_key,
size_factors_key=size_factor_key,
condition_encoder=condition_encoder,
cell_type_encoder=cell_type_encoder,)
if train_frac == 1:
return data_set_train, None
else:
data_set_valid = AnnotatedDataset(validation_adata,
condition_key=condition_key,
cell_type_key=cell_type_key,
size_factors_key=size_factor_key,
condition_encoder=condition_encoder,
cell_type_encoder=cell_type_encoder,)
return data_set_train, data_set_valid
def custom_collate(batch):
r"""Puts each data field into a tensor with outer dimension batch size"""
np_str_obj_array_pattern = re.compile(r'[SaUO]')
default_collate_err_msg_format = (
"default_collate: batch must contain tensors, numpy arrays, numbers, "
"dicts or lists; found {}")
elem = batch[0]
elem_type = type(elem)
if isinstance(elem, torch.Tensor):
out = None
if torch.utils.data.get_worker_info() is not None:
# If we're in a background process, concatenate directly into a
# shared memory tensor to avoid an extra copy
numel = sum([x.numel() for x in batch])
storage = elem.storage()._new_shared(numel)
out = elem.new(storage)
return torch.stack(batch, 0, out=out)
elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' and elem_type.__name__ != 'string_':
elem = batch[0]
if elem_type.__name__ == 'ndarray' or elem_type.__name__ == 'memmap':
# array of string classes and object
if np_str_obj_array_pattern.search(elem.dtype.str) is not None:
raise TypeError(default_collate_err_msg_format.format(elem.dtype))
return custom_collate([torch.as_tensor(b) for b in batch])
elif elem.shape == (): # scalars
return torch.as_tensor(batch)
elif isinstance(elem, container_abcs.Mapping):
if "y" in elem:
output = dict(total_batch=dict(),
labelled_batch=dict())
for key in elem:
total_data = [d[key] for d in batch]
labelled_data = list()
for d in batch:
if d["y"] != -1:
labelled_data.append(d[key])
output["total_batch"][key] = custom_collate(total_data)
output["labelled_batch"][key] = custom_collate(labelled_data)
else:
output = dict(total_batch=dict())
output["total_batch"] = {key: custom_collate([d[key] for d in batch]) for key in elem}
return output
|
/scArchest-0.0.1-py3-none-any.whl/scarches/trainers/trvae/_utils.py
| 0.747339 | 0.317903 |
_utils.py
|
pypi
|
# scBC
scBC —— a single-cell transcriptome Bayesian biClustering framework.
This document will help you easily go through the scBC model.
## Installation
To install our package, run
```bash
conda install -c conda-forge scvi-tools #pip install scvi-tools
pip install scBC
```
## Quick start
To simply illustrate how one can run our scBC model, here we use the subsampled HEART dataset as an example. We have prepared four subsampled datasets in advance (HEART, PBMC, LUAD and BC), which can be downloaded locally with simple codes:
```python
from scBC import data
heart = data.load_data("HEART")
```
If you can't download the data automatically, you can also download them manually from our [repository](https://github.com/GYQ-form/scBC/tree/main/data) and place them in your working directory.
Now you are ready to set up the scBC model:
```python
from scBC.model import scBC
my_model = scBC(adata=heart,batch_key='cell_source')
```
Notice that `adata` must be an [AnnData](https://anndata.readthedocs.io/en/latest/generated/anndata.AnnData.html#anndata.AnnData) object. `batch_key` specify the specific column in adata.var to be used as batch annotation.
We first train the VAE model with the default setting:
```python
my_model.train_VI()
```
Then we can get the reconstructed data, we use 10 posterior samples to estimate the mean expression:
```python
my_model.get_reconst_data(n_samples=10)
```
Since scBC encourage prior information about genes' co-expression to be provided, before conducting biclustering, we first generate a prior edge. Thankfully, we have also provide an API for automatically generating prior edge from biomart database, just run with default setting:
```python
my_model.get_edge()
```
Now a edge array has been stored in my_model.edge. Run biclustering will automatically use it, we set the number of biclusters as 3 here:
```python
my_model.Biclustering(L=3)
```
Take a look at the results:
```python
my_model.S
```
Or maybe we are more interest in the strong classification result at cell level:
```python
my_model.strong_class()
```
## Parameter lists
Here we give some parameter lists for readers to use flexibly:
### model
#### scBC.model.scBC()
- **adata**: *AnnData object with an observed n $\times$ p matrix, p is the number of measurements and n is the number of subjects.*
- **layer**: *if not None, uses this as the key in adata.layers for raw count data.*
- **batch_key**: *key in adata.obs for batch information. Categories will automatically be converted into integer categories and saved to adata.obs['_scvi_batch']. If None, assigns the same batch to all the data.*
- **labels_key**: *key in adata.obs for label information. Categories will automatically be converted into integer categories and saved to adata.obs['_scvi_labels']. If None, assigns the same label to all the data.*
- **size_factor_key**: *key in adata.obs for size factor information. Instead of using library size as a size factor, the provided size factor column will be used as offset in the mean of the likelihood. Assumed to be on linear scale.*
- **categorical_covariate_keys**: *keys in adata.obs that correspond to categorical data. These covariates can be added in addition to the batch covariate and are also treated as nuisance factors (i.e., the model tries to minimize their effects on the latent space). Thus, these should not be used for biologically-relevant factors that you do not want to correct for.*
- **continuous_covariate_keys**: *keys in adata.obs that correspond to continuous data. These covariates can be added in addition to the batch covariate and are also treated as nuisance factors (i.e., the model tries to minimize their effects on the latent space). Thus, these should not be used for biologically-relevant factors that you do not want to correct for.*
#### Attributes
- `self.adata` - The AnnData used when initializing the scBC object.
- `self.p` - Number of measurements(genes) of the expression matrix
- `self.n` - Number of subjects(cells) of the expression matrx
- `self.vi_model` - The scvi model
- `self.reconst_data` - Reconstructed expression matrix with n $\times$ p
- `self.W` - **W** matrix after biclustering
- `self.Z` - **Z** matrix after biclustering
- `self.mu` - Parameter matrix $\pmb\mu$ after biclustering
- `self.convg_trail` - The converge trail of biclustering process (likelihood value)
- `self.S` - A list containing L dictionaries. The $i_{th}$ dictionary is the $i_{th}$ bicluster's results
- `self.niter` - Iteration time during biclustering
- `self.edge` - The prior edge array
---
### Methods
#### scBC.train_VI()
- **n_hidden**: Number of nodes per hidden layer.
- **n_latent**: Dimensionality of the latent space.
- **n_layers**: Number of hidden layers used for encoder and decoder NNs.
- **dropout_rate**: Dropout rate for neural networks.
- **dispersion**: One of the following:
- ``'gene'`` - dispersion parameter of NB is constant per gene across cells
- ``'gene-batch'`` - dispersion can differ between different batches
- ``'gene-label'`` - dispersion can differ between different labels
- ``'gene-cell'`` - dispersion can differ for every gene in every cell
- **gene_likelihood**: One of:
- ``'nb'`` - Negative binomial distribution
- ``'zinb'`` - Zero-inflated negative binomial distribution
- ``'poisson'`` - Poisson distribution
- **latent_distribution**: One of:
- ``'normal'`` - Normal distribution
- ``'ln'`` - Logistic normal distribution (Normal(0, I) transformed by softmax)
- **max_epochs**: Number of passes through the dataset. If `None`, defaults to `np.min([round((20000 / n_cells) * 400), 400])`
- **use_gpu**: Use default GPU if available (if None or True), or index of GPU to use (if int), or name of GPU (if `str`, e.g., `'cuda:0'`), or use CPU (if False).
- **batch_size**: Minibatch size to use during training.
- **early_stopping**: Perform early stopping.
---
#### scBC.get_reconst_data()
- **n_samples**: Number of posterior samples to use for estimation.
- **batch_size**: Minibatch size for data loading into model.
---
#### scBC.get_edge()
- **gene_list**: A list containing HGNC gene names used to find prior edge in hsapiens_gene_ensembl dataset. Different actions will be performed based on the data type you provide:
- `str` - take self.adata.var[gene_list] as the gene set
- `list` - use the provided list as the gene set to be searched
- `None(default)` --- use the variable names(self.adata.var_names) as the gene set
- **dataset**: The dataset to be used for extracting prior information. Default is <u>hsapiens\_gene\_ensembl</u>.
- **intensity**: A integer denoting the intensity of the prior. Generally speaking, the larger the number, the more prior information returned (the bigger the edge array is).
---
#### scBC.Biclustering()
- **L**: number of the maximum biclusters
- **mat**: a p x n numpy array used for biclustering. We will use the reconstructed data after calling scBC.get_reconst_data(). However, you can explicitly provide one rather than using the reconstructed data.
- **edge**: a 2-colounm matrix providing prior network information of some measurements. We prefer to use the edge given here, if not provided, we will use scBC.edge as a candidate. Edge can be automaticly generated using scBC.get_edge(). Running Biclustering() without any edge prior is also feasible.
- **dist_type**: a p-element vector, each element represents the distribution type of measurements. 0 is Gaussian, 1 is Binomial, 2 is Negative Binomial, 3 is Poisson. If not given, all measurements are deemed to follow Gaussian distribution.
- **param**: a p-element vector, each element is the required parameter for the correspondence distribution. $\zeta$ for Gaussian, $n_j$ for Binomial, $r_j$ for Negative Binomial, $N$ for Poisson. Default is set as a 1 vector.
- **initWZ**: select between "random" and "svd". If "random", randomly generated N(0,1) numbers are used, o.w. use SVD results for initialization.
- **maxiter**: allowed maximum number of iterations.
- **tol**: desired total difference of solutions.
---
## simulation
We also provide an API for simulation in scBC.data:
#### scBC.data.simulate_data()
- **L**: number of biclusters
- **p**: number of measurements(genes)
- **n**: number of objects(cells)
- **dropout**: dropout rate (between 0 and 1)
- **batch_num**: number of batches you want to simulate
#### return value
A dictionary containing several simulation results:
| key | word |
| :--: | :--------------------------------------------------: |
| W | The **W** matrix |
| Z | The **Z** matrix |
| dat | AnnData object with expression matrix (n $\times$ p) |
| S | The ground truth result |
| edge | Randomly generated prior edge array |
During simulation, the scale of the FGM increases adaptively with the size of the simulated dataset (actually the size of p). The parameter $\pmb\mu$ is computed by the multiplicative model $\pmb\mu = \pmb{WZ}$, where **W** is a p×L matrix and **Z** is an L×n matrix. The number of non-zero elements in each column of **W** is set as p/20, and the number of non-zero elements in each row of **Z** is set as n/10. The row indices of non-zero elements in **W** and the column indices of **Z** with non-zero elements are randomly drawn from 1 to p and 1 to n. The nonzero element values for both **W** and **Z** are generated from a normal distribution with mean 1.5 and standard deviation 0.1, and are randomly assigned to be positive or negative. The prior edge is generated along with W. When generating **X**, each element is generated from $NB(r_j,\frac1{1+e^{-\mu_{ij}}})$ , and the parameter is randomly drawn from 5 to 20. Finally, in order to simulate different batches, we divided the dataset into `batch_num` parts, each with different intensities of noise. The implementation of dropout is to perform Bernoulli censoring at each data point according to the given dropout rate parameter. The simulation data generation process is shown as follows.

|
/scBC-0.3.0.tar.gz/scBC-0.3.0/README.md
| 0.480722 | 0.956022 |
README.md
|
pypi
|
# scBayesDeconv
Package which allow the deconvolution of two added random variables using bayesian mixture approaches.
```
Z = X + Y
```
where `X` we call it the autofluorescence,`Y` the deconvolution and`Z` the convolution; which are random variables. If we have a sample of values from distribution `X` and `Z`, the package tryes to deconvolve the signal to obtain a distribution of `Y`. The kinds of bayesian mixtures are implemented:
1. Gaussian
2. Gamma
## Installation
The package can be installed from the PyPi repository with the command:
```shell
pip install scBayesDeconv
```
### Problems with nstallation from PyPi
In case of problems, you can always compile the package from the git repository. The requirements for installation are:
1. CMake
2. A C++ compiler and at least c++11 standard (g++, Visual Studio, Clang...)
3. The scikit-build library for python (if not, `pip install scikit-build`)
In the gaussian deconvolution folder, create the binary installation.
```shell
python setup.py bdist_wheel
```
This will generate a wheel in automatically created `dist` folder. Now, we can install it.
```shell
pip install ./dist/*
```
If everything is okey, you should be happily running the code after a few seconds of compilation ;)
## Small tutorial
The package behaves very similar to the [scikit-learn](https://scikit-learn.org/) package.
Consider that we have two arrays of data, one with some noise `dataNoise` and the second with the convolved data `dataConvolved`.
Import the package
```python
import scBayesDeconv as gd
```
Declare one of the two models. The models consider by default one gaussian for the noise and one gaussian for the convolved data. Consider that we want to fit the noise to one and the convolved data with three.
```python
model = gd.mcmcsampler(K=1, Kc=3)
```
or
```python
model = gd.nestedsampler(K=1, Kc=3)
```
Once declared, fit the model:
```python
model.fit(dataNoise,dataConvolved)
```
With the model fit, we can sample from the model
```python
model.sample_autofluorescence(size=100)
model.sample_deconvolution(size=100)
model.sample_convolution(size=100)
```
or evaluate at certain positions. This will return the mean value, as well as any specified percentiles (by default at 0.05 and 0.95).
```python
x = np.arange(0,1,0.1)
model.score_autofluorescence(x, percentiles=[0.05,0.5,0.95])
model.score_deconvolution(x, percentiles=[0.05,0.5,0.95])
model.score_convolution(x, percentiles=[0.05,0.5,0.95])
```
In addition, for the mcmcsampler, it is possible to obtain some resume statistics of the sampler in order to check if the sampling process has converged to the posterior.
```python
model.statistics()
```
An rhat close to 1 indicates that the posterior chains have mixed appropiately. neff is an indicator of the effective number of independent samples drawn from the model. For more information, have a look to the [Stan](https://mc-stan.org/) package and its associated bayesian statistics book, [Chaper 11](http://www.stat.columbia.edu/~gelman/book/).
### Which model should I use?
Both models correspond to the same posterior likelihood with the only difference on how samples from this posterior are drawn.
The **mcmc** sampler is based in Gibbs and MCMC markov chain steps with help of indicator variables. This are extensively explained in the book of [Gelman](http://www.stat.columbia.edu/~gelman/book/). Such sampler have the benefit of converging *fast* to a mode of the posterior and have the nice property of concentrating around *solutions with sparse number of components*. Howerver, the posterior distribution of the bayesian deconvolution model is multimodal and, for big noises, can lead to high degeneracies of the system. In such cases, samplers based in markov chains have severe dificulties to converge. Fro the above reasons, this sampler should be used mainly for exploratory purposes in order to have a general idea of the deconvolution as well as the number of components required to describe appropiately the posterior.
The **nested** sampler is based in the ideas of nested sampling introduced by [Skilling](https://projecteuclid.org/euclid.ba/1340370944). Such sampling methods have more power in order to explore complex distributions with multimodalities and complex degeneracies. The counterpart is that the sampler does not select component sparse regions of the space and the exploration becomes fast computationally expensive with the number of components. In order to speed the computation, we wrapped the well documented and recently published library for dynamic nested sampling [Dynesty](https://dynesty.readthedocs.io/en/latest/) around C++ in order to obtain reasonable sampling times for samples of data of the order of magnitude tipically encountered flow citometry datasets. The posteriors obtained through this sampling method capture better the complexity of the gaussian deconvolution in a non-prohibitive amount of time, in contrast to the mcmc sampler.
Overall, one should use the mcmc sampler for exploration and number of components selection and feed that information to a selected nested sampler model in order to obtain the most reliable results within reasonable computational time.
|
/scBayesDeconv-0.1.tar.gz/scBayesDeconv-0.1/README.md
| 0.554953 | 0.99406 |
README.md
|
pypi
|
import numpy as np
import pandas as pd
def _binarize_discarded(gene: pd.Series, *args):
"""Helper function for the binarization of discarded genes.
Not intended to be called directly. The inclusion of the variadic
argument *args was introduced to avoid type errors when calling it
from scboolseq.core.scBoolSeq"""
return pd.Series(np.nan, index=gene.index)
def _binarize_bimodal(gene: pd.Series, criteria: pd.DataFrame, *args):
"""Helper function for the binarization of bimodal genes.
Not intended to be called directly. The inclusion of the variadic
argument *args was introduced to avoid type errors when calling it
from scboolseq.core.scBoolSeq"""
_binary_gene = pd.Series(np.nan, index=gene.index)
_criterion = criteria.loc[gene.name, :]
bim_thresh_up = _criterion["bim_thresh_up"]
bim_thresh_down = _criterion["bim_thresh_down"]
_binary_gene[gene >= bim_thresh_up] = 1.0
_binary_gene[gene <= bim_thresh_down] = 0.0
return _binary_gene
def _binarize_unimodal_and_zeroinf(
gene: pd.Series, criteria: pd.DataFrame, alpha: float
):
"""Helper function for the binarization of unimodal and zero-inflated genes.
Not intended to be called directly."""
_binary_gene = pd.Series(np.nan, index=gene.index)
_criterion = criteria.loc[gene.name, :]
unim_thresh_up = _criterion["unimodal_high_quantile"] + alpha * _criterion["IQR"]
unim_thresh_down = _criterion["unimodal_low_quantile"] - alpha * _criterion["IQR"]
_binary_gene[gene > unim_thresh_up] = 1.0
_binary_gene[gene < unim_thresh_down] = 0.0
return _binary_gene
_binarization_function_by_category = {
"ZeroInf": _binarize_unimodal_and_zeroinf,
"Unimodal": _binarize_unimodal_and_zeroinf,
"Bimodal": _binarize_bimodal,
"Discarded": _binarize_discarded,
}
def _binarize_gene(gene: pd.Series, criteria: pd.DataFrame, alpha: float) -> pd.Series:
"""Helper function for the binarization of a single gene.
Not intended to be called directly. It is internally used by
scboolseq.binarization._binarize and scboolseq.binarization.binarize"""
return _binarization_function_by_category[criteria.loc[gene.name, "Category"]](
gene, criteria, alpha
)
def _binarize(criteria: pd.DataFrame, alpha: float, data: pd.DataFrame) -> pd.DataFrame:
"""binarize `data` according to `criteria`,
using `alpha` multiplier for the IQR, for Unimodal
and ZeroInf genes."""
return data.apply(_binarize_gene, args=[criteria, alpha])
def binarize(data: pd.DataFrame, criteria: pd.DataFrame, alpha: float) -> pd.DataFrame:
"""binarize `data` according to `criteria`,
using `alpha` multiplier for the IQR, for Unimodal and ZeroInf genes."""
return data.apply(_binarize_gene, args=[criteria, alpha])
def binarise(*args, **kwargs) -> pd.DataFrame:
"""alias for binarize. See scBoolSeq.binarization.binarize"""
return binarize(*args, **kwargs)
|
/scBoolSeq-0.8.3-py3-none-any.whl/scboolseq/binarization.py
| 0.87879 | 0.437523 |
binarization.py
|
pypi
|
__all__ = ["normalize", "normalise", "log_transform", "log_normalize", "log_normalise"]
import numpy as np
import pandas as pd
from typing import Optional
def normalize(raw_counts: pd.DataFrame, method: Optional[str] = None) -> pd.DataFrame:
"""
Normalize count matrix.
Parameters
----------
raw_counts_df: pandas.DataFrame
A raw count matrix containing the number of
reads per gene (row), per sample (column).
method: str, optional (default: "RPM")
Choose from : {
"RPM" or "CPM": Reads (counts) per million mapped reads (library-size correct)
* RPM does not consider the transcript length normalization.
* suitable for sequencing protocols where reads are generated irrespective of gene length
"RPKM", "TPM" : to be implemented
}
Returns
-------
a pandas.DataFrame, containing normalized read counts
"""
method = method or "RPM"
method = method.upper()
if method not in ["RPM", "CPM", "RPKM", "TPM"]:
raise ValueError(f"unrecognized method {method}")
if method == "RPM" or method == "CPM":
return raw_counts / raw_counts.sum() * 1e6
else:
raise NotImplementedError(
"\n".join(
[
"method {method} has not been implemented.",
"Feel free to open a pull request at :",
"https://github.com/bnediction/scBoolSeq",
]
)
)
def normalise(*args, **kwargs) -> pd.DataFrame:
"""alias for normalize. See help(normalize)"""
return normalize(*args, **kwargs)
def log_transform(
data: pd.DataFrame, base: Optional[int] = None, constant: Optional[int] = None
) -> pd.DataFrame:
"""
log transform expression data
Parameters
----------
data: pd.DataFrame
Annotated data matrix.
base: int, optional (default: 2)
The base used to calculate logarithm
constant: int, optional (default: 1)
The number to be added to all entries, to
prevent indetermination of the transformation
when a read is equal to zero.
Returns
-------
a pandas.DataFrame, containing log-transformed counts
np.log(data + constante) / np.log(base)
i.e.
np.log(data + 1) / np.log(2)
for default parameters
"""
base = base or 2
constant = constant or 1
return np.log(data + constant) / np.log(base)
def log_normalize(
data: pd.DataFrame,
method: Optional[str] = None,
base: Optional[int] = None,
constant: Optional[int] = None,
) -> pd.DataFrame:
"""
Chain the call to normalize and log_transform
Parameters
----------
data: pandas.DataFrame
raw expression counts
method: String
optional
"""
_normalized = normalize(data, method=method)
return log_transform(_normalized, base=base, constant=constant)
def log_normalise(*args, **kwargs) -> pd.DataFrame:
"""alias for log_normalize. See help(log_normalize)"""
return log_normalize(*args, **kwargs)
|
/scBoolSeq-0.8.3-py3-none-any.whl/scboolseq/utils/normalization.py
| 0.94843 | 0.499634 |
normalization.py
|
pypi
|
from pathlib import (
Path as _Path_,
PosixPath as _PosixPath_,
WindowsPath as _WindowsPath_,
)
import os
import argparse
from time import time
class Timer(object):
"""A simple timer class used to measure execution time,
without all the problems related to using timeit."""
def __init__(self, description):
self.description = description
self.start: float
self.end: float
def __enter__(self):
self.start = time()
def __exit__(self, exc_type, exc_value, exc_traceback):
self.end = time()
print(f"{self.description}: {round(self.end - self.start, 5)}", flush=True)
class Path(_Path_):
"""
Basically a wrapper for pathlib.Path,
created to modify pathlib.Path.glob's behaviour :
Added a method lglob() which returns a list instead of a generator.
Thanks to this tread on code review :
https://codereview.stackexchange.com/questions/162426/subclassing-pathlib-path
"""
def __new__(cls, *args, **kvps):
return super().__new__(
WindowsPath if os.name == "nt" else PosixPath, *args, **kvps
)
def lglob(self, expr: str):
return list(super().glob(expr))
@property
def abs(self):
return super().absolute().as_posix()
class WindowsPath(_WindowsPath_, Path):
"""Helper for Path, not to be directly initialized."""
class PosixPath(_PosixPath_, Path):
"""Helper for Path, not to be directly initialized."""
class ObjDict(dict):
"""
Instantiate a dictionary that allows accessing values
with object notation (as if they were attributes):
ex:
x.foo = 5
instead of
x['foo'] = 5
The best part is that both ways work !
Ideal for working with TOML files.
Additional features include :
* lkeys property : same as dict.keys() but returns a list directly.
* lvalues property : same as dict.values() but returns a list directly.
Original code snippet found here :
https://goodcode.io/articles/python-dict-object/
"""
@property
def lkeys(self):
return list(super().keys())
@property
def lvalues(self):
return list(super().values())
@property
def litems(self):
return super().items()
def __getattr__(self, name):
if name in self:
return self[name]
else:
raise AttributeError("No such attribute: " + name)
def __setattr__(self, name, value):
self[name] = value
def __delattr__(self, name):
if name in self:
del self[name]
else:
raise AttributeError("No such attribute: " + name)
class StoreDictKeyPair(argparse.Action):
"""Created this argparse action to save kwargs
to a dict, to be passed to pandas.read_csv()
this functionality will be developed in the future.
"""
def __init__(self, option_strings, dest, nargs=None, **kwargs):
self._nargs = nargs
super(StoreDictKeyPair, self).__init__(
option_strings, dest, nargs=nargs, **kwargs
)
def __call__(self, parser, namespace, values, option_string=None):
my_dict = {}
for kv in values:
k, v = kv.split("=")
my_dict[k] = v
setattr(namespace, self.dest, my_dict)
|
/scBoolSeq-0.8.3-py3-none-any.whl/scboolseq/utils/customobjs.py
| 0.847463 | 0.314327 |
customobjs.py
|
pypi
|
# scButterfly: single-cell cross-modality translation via multi-use dual-aligned variational autoencoders
## Installation
It's prefered to create a new environment for scButterfly
```
conda create scButterfly python==3.9
conda activate scButterfly
```
scButterfly is available on PyPI, and could be installed using
```
# CUDA 11.6
pip install scButterfly --extra-index-url https://download.pytorch.org/whl/cu116
# CUDA 11.3
pip install scButterfly --extra-index-url https://download.pytorch.org/whl/cu113
# CUDA 10.2
pip install scButterfly --extra-index-url https://download.pytorch.org/whl/cu102
# CPU only
pip install scButterfly --extra-index-url https://download.pytorch.org/whl/cpu
```
Installation via Github is also provided
```
git clone https://github.com/Biox-NKU/scButterfly
cd scButterfly
python setup.py install
```
## Quick Start
scButterfly could be easily used following 3 steps: Data Preprocessing, Model training, Predicting and evaluating.more details could be find in [scButterfly documents](http://scbutterfly.readthedocs.io/).
Generate a butterfly model first for following process:
```python
from scButterfly.butterfly import Butterfly
butterfly = Butterfly()
```
### 1. Data Preprocessing
* Before data preprocessing, you should load scRNA-seq and scATAC-seq data via `butterfly.load_data`:
```python
butterfly.load_data(RNA_data, ATAC_data, train_id, test_id, validation_id)
```
| Parameters | Description |
| ------------- | ------------------------------------------------------------------------------------------ |
| RNA_data | AnnData object of shape `n_obs` × `n_vars`. Rows correspond to cells and columns to genes. |
| ATAC_data | AnnData object of shape `n_obs` × `n_vars`. Rows correspond to cells and columns to peaks. |
| train_id | A list of cell IDs for training. |
| test_id | A list of cell IDs for testing. |
| validation_id | An optional list of cell IDs for validation, if setted None, butterfly will use a default setting of 20% cells in train_id. |
Anndata object is a Python object/container designed to store single-cell data in Python packege [**anndata**](https://anndata.readthedocs.io/en/latest/) which is seamlessly integrated with [**scanpy**](https://scanpy.readthedocs.io/en/stable/), a widely-used Python library for single-cell data analysis.
* For data preprocessing, you could use `butterfly.data_preprocessing`:
```python
butterfly.data_preprocessing()
```
You could save processed data or output process logging to a file using following parameters.
| Parameters | Description |
| ------------ | -------------------------------------------------------------------------------------------- |
| save_data | optional, choose save the processed data or not, default False. |
| file_path | optional, the path for saving processed data, only used if `save_data` is True, default None. |
| logging_path | optional, the path for output process logging, if not save, set it None, default None. |
scButterfly also support to refine this process using other parameters (more details on [scButterfly documents](http://scbutterfly.readthedocs.io/)), however, we strongly recommend the default settings to keep the best result for model.
### 2. Model training
* Before model training, you could choose to use data amplification or not. If using data amplification, scButterfly will generate some artificial training sample using cell type labels(if `cell_type` in `adata.obs`) or cluster labels get with Leiden algorithm and [**MultiVI**](https://docs.scvi-tools.org/en/stable/tutorials/notebooks/MultiVI_tutorial.html) method, a single-cell multi-omics data joint analysis method in Python packages [**scvi-tools**](https://docs.scvi-tools.org/en/stable/).
scButterfly provide data amplification API:
```python
butterfly.amplification(amp_type)
```
You could choose parameter `amp_type` from `cell_type_amplification` or `MultiVI_amplification`, this will cause more training time used, but promise better result for predicting.
* If you choose `cell_type_amplification`, scButterfly will try to find `cell_type` in `adata.obs`. If failed, it will automaticly transfer to `MultiVI_amplification`.
* If you choose `MultiVI_amplification`, scButterfly will train a MultiVI model first.
* If you just want to using truth data for training, set `amp_type = None`.
* You could construct a scButterfly model as following:
```python
butterfly.construct_model(chrom_list)
```
scButterfly need a list of peaks count for each chromosome, remember to sort peaks with chromosomes.
| Parameters | Description |
| ------------ | ---------------------------------------------------------------------------------------------- |
| chrom_list | a list of peaks count for each chromosome, remember to sort peaks with chromosomes. |
| logging_path | optional, the path for output model structure logging, if not save, set it None, default None. |
* scButterfly model could be easily trained as following:
```python
butterfly.train_model()
```
| Parameters | Description |
| ------------ | --------------------------------------------------------------------------------------- |
| output_path | optional, path for model check point, if None, using './model' as path, default None. |
| load_model | optional, the path for load pretrained model, if not load, set it None, default None. |
| logging_path | optional, the path for output training logging, if not save, set it None, default None. |
scButterfly also support to refine the model structure and training process using other parameters for `butterfly.construct_model()` and `butterfly.train_model()` (more details on [scButterfly documents](http://scbutterfly.readthedocs.io/)).
### 3. Predicting and evaluating
* scButterfly provide a predicting API, you could get both RNA and ATAC prediction as follow:
```python
A2R_predict, R2A_predict = butterly.test_model()
```
A series of evaluating method also be integrated in this function, you could get these evaluation using parameters:
| Parameters | Description |
| ------------- | ------------------------------------------------------------------------------------------- |
| output_path | optional, path for model evaluating output, if None, using './model' as path, default None. |
| load_model | optional, the path for load pretrained model, if not load, set it None, default False. |
| model_path | optional, the path for pretrained model, only used if `load_model` is True, default None. |
| test_relation | optional, test the correlation evaluation or not, including **Preason** and **Spearman** correlation for scRNA-seq prediction, **AUROC** and **AUPR** for scATAC-seq prediction, default False. |
| test_cluster | optional, test the correlation evaluation or not, including **ARI**, **AMI**, **NMI**, **HOM**, **COM**, default False. |
| test_figure | optional, draw the **tSNE** for prediction or not, default False. |
| output_data | optional, output the prediction to file or not, if True, output the prediction to `output_path/A2R_predict.h5ad` and `output_path/R2A_predict.h5ad`, default False. |
## Document and tutorial
### We provide a tutorial and richer document for scButterfly in [scButterfly documents](http://scbutterfly.readthedocs.io/), including more details of provided APIs for customing data preprocessing, model structure and training strategy.
|
/scButterfly-0.0.4.tar.gz/scButterfly-0.0.4/README.md
| 0.501709 | 0.902136 |
README.md
|
pypi
|
import argparse
from scCASE import run
if __name__ == '__main__':
def parse_args():
parser = argparse.ArgumentParser(description='Parameters')
parser.add_argument('--method', type=str, default='scCASE', help='scCASE or scCASER.')
parser.add_argument('--data_path', type=str,default=None, help='The path and file name of the target data.')
parser.add_argument('--ref_path', type=str, default=None, help='The path and file name of the reference data.')
parser.add_argument('--data_format', type=str, default="count matrix", help='The format of data and reference data, including count matrix(csv/txt/tsv) and h5ad. Default:count matrix')
parser.add_argument('--data_sep', type=str, default=",", help='The Separator of target data, only for count matrix file. Default:,')
parser.add_argument('--ref_sep', type=str, default=",", help='The Separator of reference data, only for count matrix file. Default:,')
parser.add_argument('--type_number_range', type=range, default=range(3, 15), help='The range of possible number of cell types. Default:(2:15)')
parser.add_argument('--output_path', type=str, default="./", help='The path of the result. Defalut:./')
parser.add_argument('--save_other_matrixs', type=bool, default=False, help='If save the matrices including Z,W and H. Default:False')
parser.add_argument('--obs_key', type=str, default=None, help='The key of cell name in adata.obs. Default:celltype')
parser.add_argument('--var_key', type=str, default=None, help='The key of peaks name in adata.var. Default:peaks')
parser.add_argument('--threshold', type=float, default=0.01 , help='The threshold of preprocessing. Default:0.01')
parser.add_argument('--saveZ', type=bool, default=False , help='If save the initialized matrix Z. If you need to use this method multiple times for the same data, with different parameters, please select True, which can significantly accelerate the speed')
parser.add_argument('--changeK', type=str, default="+0" , help='Change the parameter K.')
parser.add_argument('--changeK_ref', type=str, default="+0" , help='Change the parameter K of reference.')
return parser.parse_args()
args = parse_args()
method = args.method
data_path = args.data_path
ref_path = args.ref_path
data_format = args.data_format
data_sep = args.data_sep
ref_sep = args.ref_sep
type_number_range = args.type_number_range
output_path = args.output_path
save_other_matrixs_ = True #save_other_matrixs_
var_key = args.var_key
obs_key = args.obs_key
threshold = args.threshold
saveZ = args.saveZ
changeK = args.changeK
changeK_ref = args.changeK_ref
result = run(data_path,ref_path,method,data_format,data_sep,ref_sep,type_number_range,output_path,save_other_matrixs_,obs_key,var_key,threshold,saveZ,changeK,changeK_ref,True)
|
/scCASE-0.0.4-py3-none-any.whl/scCASE-0.0.4.data/scripts/scCASE.py
| 0.473657 | 0.191781 |
scCASE.py
|
pypi
|
# scCODA - Compositional analysis of single-cell data
This notebook serves as a tutorial for using the *scCODA* package ([Büttner, Ostner et al., 2021](https://www.nature.com/articles/s41467-021-27150-6)) to analyze changes in cell composition data.
The package is intended to be used with cell composition from single-cell RNA-seq experiments, however there are no technical
restrictions that prevent the use of data from other sources.
The data we use in the following example comes from [Haber et al., 2017](https://www.nature.com/articles/nature24489).
It contains samples from the small intestinal epithelium of mice with different conditions.
This tutorial is designed to be executed on a standard computer (any operating system) in a Python environment with scCODA, Jupyter notebook and all their dependencies installed.
Running the tutorial takes about 1.5 minutes on a 2020 Apple MacBook Pro (16GB RAM).
```
# Setup
import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import pickle as pkl
import matplotlib.pyplot as plt
from sccoda.util import comp_ana as mod
from sccoda.util import cell_composition_data as dat
from sccoda.util import data_visualization as viz
import sccoda.datasets as scd
```
### Data preparation
```
# Load data
cell_counts = scd.haber()
print(cell_counts)
```
Looking at the data, we see that we have 4 control samples, and 3 conditions with 2 samples each.
To use the models in *scCODA*, we first have to convert the data into an [anndata](https://github.com/theislab/anndata) object.
This can be done easily with the `sccoda.util.cell_composition_data` module.
The resulting object separates our data components: Cell counts are stored in `data.X`, covariates in `data.obs`.
```
# Convert data to anndata object
data_all = dat.from_pandas(cell_counts, covariate_columns=["Mouse"])
# Extract condition from mouse name and add it as an extra column to the covariates
data_all.obs["Condition"] = data_all.obs["Mouse"].str.replace(r"_[0-9]", "")
print(data_all)
```
For our first example, we want to look at how the Salmonella infection influences the cell composition.
Therefore, we subset our data.
```
# Select control and salmonella data
data_salm = data_all[data_all.obs["Condition"].isin(["Control", "Salm"])]
print(data_salm.obs)
```
Plotting the data, we can see that there is a large increase of Enterocytes in the infected sampes, while most other cell types slightly decrease.
Since scRNA-seq experiments are limited in the number of cells per sample, the count data is compositional, which leads to negative correlations between the cell types.
Thus, the slight decreases in many cell types might be fully caused by the increase in Enterocytes.
```
viz.boxplots(data_salm, feature_name="Condition")
plt.show()
```
*Note that the use of* anndata *in* scCODA *is different from the use in scRNA-seq pipelines, e.g.* scanpy.
*To convert* scanpy *objects to a scCODA dataset, have a look at `dat.from_scanpy.*
### Model setup and inference
We can now create the model and run inference on it. Creating a `sccoda.util.comp_ana.CompositionalAnalysis` class object
sets up the compositional model and prepares everxthing for parameter inference. It needs these informations:
- The data object from above.
- The `formula` parameter. It specifies how the covariates are used in the model.
It can process R-style formulas via the [patsy](https://patsy.readthedocs.io/en/latest/) package, e.g. `formula="Cov1 + Cov2 + Cov3"`.
Here, we simply use the "Condition" covariate of our dataset
- The `reference_cell_type` parameter is used to specify a cell type that is believed to be unchanged by the covariates in `formula`.
This is necessary, because compositional analysis must always be performed relative to a reference (See [Büttner, Ostner et al., 2021](https://www.nature.com/articles/s41467-021-27150-6) for a more thorough explanation).
If no knowledge about such a cell type exists prior to the analysis, taking a cell type that has a nearly constant relative abundance over all samples is often a good choice.
It is also possible to let scCODA find a suited reference cell type by using `reference_cell_type="automatic"`.
Here, we take Goblet cells as the reference.
```
model_salm = mod.CompositionalAnalysis(data_salm, formula="Condition", reference_cell_type="Goblet")
```
HMC sampling is then initiated by calling `model.sample_hmc()`, which produces a `sccoda.util.result_classes.CAResult` object.
```
# Run MCMC
sim_results = model_salm.sample_hmc()
```
### Result interpretation
Calling `summary()` on the results object, we can see the most relevant information for further analysis:
```
sim_results.summary()
```
**Model properties**
First, the summary shows an overview over the model properties:
* Number of samples/cell types
* The reference cell type.
* The formula used
The model has two types of parameters that are relevant for analysis - intercepts and effects.
These can be interpreted like in a standard regression model:
Intercepts show how the cell types are distributed without any active covariates, effects show ho the covariates influence the cell types.
**Intercepts**
The first column of the intercept summary shows the parameters determined by the MCMC inference.
The "Expected sample" column gives some context to the numerical values.
If we had a new sample (with no active covariates) with a total number of cells equal to the mean sampling depth of the dataset,
then this distribution over the cell types would be most likely.
**Effects**
For the effect summary, the first column again shows the inferred parameters for all combinations of covariates and cell types.
Most important is the distinctions between zero and non-zero entries
A value of zero means that no statistically credible effect was detected.
For a value other than zero, a credible change was detected. A positive sign indicates an increase, a negative sign a decrease in abundance.
Since the numerical values of the "Final parameter" columns are not straightforward to interpret, the "Expected sample" and "log2-fold change" columns give us an idea on the magnitude of the change.
The expected sample is calculated for each covariate separately (covariate value = 1, all other covariates = 0), with the same method as for the intercepts.
The log-fold change is then calculated between this expected sample and the expected sample with no active covariates from the intercept section.
Since the data is compositional, cell types for which no credible change was detected, are will change in abundance as well, as soon as a credible effect is detected on another cell type due to the sum-to-one constraint.
**Interpretation**
In the salmonella case, we see only a credible increase of Enterocytes, while all other cell types are unaffected by the disease.
The log-fold change of Enterocytes between control and infected samples with the same total cell count lies at about 1.54.
We can also easily filter out all credible effects:
```
print(sim_results.credible_effects())
```
### Adjusting the False discovery rate
scCODA selects credible effects based on their inclusion probability.
The cutoff between credible and non-credible effects depends on the desired false discovery rate (FDR).
A smaller FDR value will produce more conservative results, but might miss some effects,
while a larger FDR value selects more effects at the cost of a larger number of false discoveries.
The desired FDR level can be easily set after inference via `sim_results.set_fdr()`. Per default, the value is 0.05,
but we recommend to increase it if no effects are found at a more conservative level.
In our example, setting a desired FDR of 0.4 reveals effects on Endocrine and Enterocyte cells.
```
sim_results.set_fdr(est_fdr=0.4)
sim_results.summary()
```
### Saving results
The compositional analysis results can be saved as a pickle object via `results.save(<path_to_file>)`.
```
# saving
path = "test"
sim_results.save(path)
# loading
with open(path, "rb") as f:
sim_results_2 = pkl.load(f)
sim_results_2.summary()
```
|
/scCODA-0.1.9.tar.gz/scCODA-0.1.9/docs/source/getting_started.ipynb
| 0.516839 | 0.976736 |
getting_started.ipynb
|
pypi
|
# scCODA - Compositional analysis of single-cell data
This notebook serves as a tutorial for using the *scCODA* package ([Büttner, Ostner et al., 2021](https://www.nature.com/articles/s41467-021-27150-6)) to analyze changes in cell composition data.
The package is intended to be used with cell composition from single-cell RNA-seq experiments, however there are no technical
restrictions that prevent the use of data from other sources.
The data we use in the following example comes from [Haber et al., 2017](https://www.nature.com/articles/nature24489).
It contains samples from the small intestinal epithelium of mice with different conditions.
This tutorial is designed to be executed on a standard computer (any operating system) in a Python environment with scCODA, Jupyter notebook and all their dependencies installed.
Running the tutorial takes about 1.5 minutes on a 2020 Apple MacBook Pro (16GB RAM).
```
# Setup
import importlib
import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import pickle as pkl
import matplotlib.pyplot as plt
from sccoda.util import comp_ana as mod
from sccoda.util import cell_composition_data as dat
from sccoda.util import data_visualization as viz
import sccoda.datasets as scd
```
### Data preparation
```
# Load data
cell_counts = scd.haber()
print(cell_counts)
```
Looking at the data, we see that we have 4 control samples, and 3 conditions with 2 samples each.
To use the models in *scCODA*, we first have to convert the data into an [anndata](https://github.com/theislab/anndata) object.
This can be done easily with the `sccoda.util.cell_composition_data` module.
The resulting object separates our data components: Cell counts are stored in `data.X`, covariates in `data.obs`.
```
# Convert data to anndata object
data_all = dat.from_pandas(cell_counts, covariate_columns=["Mouse"])
# Extract condition from mouse name and add it as an extra column to the covariates
data_all.obs["Condition"] = data_all.obs["Mouse"].str.replace(r"_[0-9]", "", regex=True)
print(data_all)
```
For our first example, we want to look at how the Salmonella infection influences the cell composition.
Therefore, we subset our data.
```
# Select control and salmonella data
data_salm = data_all[data_all.obs["Condition"].isin(["Control", "Salm"])]
print(data_salm.obs)
```
Plotting the data, we can see that there is a large increase of Enterocytes in the infected sampes, while most other cell types slightly decrease.
Since scRNA-seq experiments are limited in the number of cells per sample, the count data is compositional, which leads to negative correlations between the cell types.
Thus, the slight decreases in many cell types might be fully caused by the increase in Enterocytes.
```
viz.boxplots(data_salm, feature_name="Condition")
plt.show()
```
*Note that the use of* anndata *in* scCODA *is different from the use in scRNA-seq pipelines, e.g.* scanpy.
*To convert* scanpy *objects to a scCODA dataset, have a look at `dat.from_scanpy.*
### Model setup and inference
We can now create the model and run inference on it. Creating a `sccoda.util.comp_ana.CompositionalAnalysis` class object
sets up the compositional model and prepares everxthing for parameter inference. It needs these informations:
- The data object from above.
- The `formula` parameter. It specifies how the covariates are used in the model.
It can process R-style formulas via the [patsy](https://patsy.readthedocs.io/en/latest/) package, e.g. `formula="Cov1 + Cov2 + Cov3"`.
Here, we simply use the "Condition" covariate of our dataset
- The `reference_cell_type` parameter is used to specify a cell type that is believed to be unchanged by the covariates in `formula`.
This is necessary, because compositional analysis must always be performed relative to a reference (See [Büttner, Ostner et al., 2021](https://www.nature.com/articles/s41467-021-27150-6) for a more thorough explanation).
If no knowledge about such a cell type exists prior to the analysis, taking a cell type that has a nearly constant relative abundance over all samples is often a good choice.
It is also possible to let scCODA find a suited reference cell type by using `reference_cell_type="automatic"`.
Here, we take Goblet cells as the reference.
```
model_salm = mod.CompositionalAnalysis(data_salm, formula="Condition", reference_cell_type="Goblet")
```
HMC sampling is then initiated by calling `model.sample_hmc()`, which produces a `sccoda.util.result_classes.CAResult` object.
```
# Run MCMC
sim_results = model_salm.sample_hmc()
```
### Result interpretation
Calling `summary()` on the results object, we can see the most relevant information for further analysis:
```
sim_results.summary()
```
**Model properties**
First, the summary shows an overview over the model properties:
* Number of samples/cell types
* The reference cell type.
* The formula used
The model has two types of parameters that are relevant for analysis - intercepts and effects.
These can be interpreted like in a standard regression model:
Intercepts show how the cell types are distributed without any active covariates, effects show ho the covariates influence the cell types.
**Intercepts**
The first column of the intercept summary shows the parameters determined by the MCMC inference.
The "Expected sample" column gives some context to the numerical values.
If we had a new sample (with no active covariates) with a total number of cells equal to the mean sampling depth of the dataset,
then this distribution over the cell types would be most likely.
**Effects**
For the effect summary, the first column again shows the inferred parameters for all combinations of covariates and cell types.
Most important is the distinctions between zero and non-zero entries
A value of zero means that no statistically credible effect was detected.
For a value other than zero, a credible change was detected. A positive sign indicates an increase, a negative sign a decrease in abundance.
Since the numerical values of the "Final Parameter" column are not straightforward to interpret, the "Expected sample" and "log2-fold change" columns give us an idea on the magnitude of the change.
The expected sample is calculated for each covariate separately (covariate value = 1, all other covariates = 0), with the same method as for the intercepts.
The log-fold change is then calculated between this expected sample and the expected sample with no active covariates from the intercept section.
Since the data is compositional, cell types for which no credible change was detected, can still change in abundance as well, as soon as a credible effect is detected on another cell type due to the sum-to-one constraint.
If there are no credible effects for a covariate, its expected sample will be identical to the intercept sample, therefore the log2-fold change is 0.
**Interpretation**
In the salmonella case, we see only a credible increase of Enterocytes, while all other cell types are unaffected by the disease.
The log-fold change of Enterocytes between control and infected samples with the same total cell count lies at about 1.54.
We can also easily filter out all credible effects:
```
print(sim_results.credible_effects())
```
### Adjusting the False discovery rate
scCODA selects credible effects based on their inclusion probability.
The cutoff between credible and non-credible effects depends on the desired false discovery rate (FDR).
A smaller FDR value will produce more conservative results, but might miss some effects,
while a larger FDR value selects more effects at the cost of a larger number of false discoveries.
The desired FDR level can be easily set after inference via `sim_results.set_fdr()`. Per default, the value is 0.05,
but we recommend to increase it if no effects are found at a more conservative level.
In our example, setting a desired FDR of 0.4 reveals effects on Endocrine and Enterocyte cells.
```
sim_results.set_fdr(est_fdr=0.4)
sim_results.summary()
```
### Saving results
The compositional analysis results can be saved as a pickle object via `results.save(<path_to_file>)`.
```
# saving
path = "test"
sim_results.save(path)
# loading
with open(path, "rb") as f:
sim_results_2 = pkl.load(f)
sim_results_2.summary()
```
|
/scCODA-0.1.9.tar.gz/scCODA-0.1.9/tutorials/getting_started.ipynb
| 0.502686 | 0.993944 |
getting_started.ipynb
|
pypi
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import cm, rcParams
from matplotlib.colors import ListedColormap
from anndata import AnnData
from typing import Optional, Tuple, Collection, Union, List
sns.set_style("ticks")
def stackbar(
y: np.ndarray,
type_names: List[str],
title: str,
level_names: List[str],
figsize: Optional[Tuple[int, int]] = None,
dpi: Optional[int] = 100,
cmap: Optional[ListedColormap] = cm.tab20,
plot_legend: Optional[bool] = True,
) -> plt.Subplot:
"""
Plots a stacked barplot for one (discrete) covariate
Typical use (only inside stacked_barplot): plot_one_stackbar(data.X, data.var.index, "xyz", data.obs.index)
Parameters
----------
y
The count data, collapsed onto the level of interest. i.e. a binary covariate has two rows, one for each group, containing the count
mean of each cell type
type_names
The names of all cell types
title
Plot title, usually the covariate's name
level_names
names of the covariate's levels
figsize
figure size
dpi
dpi setting
cmap
The color map for the barplot
plot_legend
If True, adds a legend
Returns
-------
Returns a plot
ax
a plot
"""
n_bars, n_types = y.shape
figsize = rcParams["figure.figsize"] if figsize is None else figsize
fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
r = np.array(range(n_bars))
sample_sums = np.sum(y, axis=1)
barwidth = 0.85
cum_bars = np.zeros(n_bars)
for n in range(n_types):
bars = [i / j * 100 for i, j in zip([y[k][n] for k in range(n_bars)], sample_sums)]
plt.bar(r, bars, bottom=cum_bars, color=cmap(n % cmap.N), width=barwidth, label=type_names[n], linewidth=0)
cum_bars += bars
ax.set_title(title)
if plot_legend:
ax.legend(loc='upper left', bbox_to_anchor=(1, 1), ncol=1)
ax.set_xticks(r)
ax.set_xticklabels(level_names, rotation=45)
ax.set_ylabel("Proportion")
return ax
def stacked_barplot(
data: AnnData,
feature_name: str,
figsize: Optional[Tuple[int, int]] = None,
dpi: Optional[int] = 100,
cmap: Optional[ListedColormap] = cm.tab20,
plot_legend: Optional[bool] = True,
level_order: List[str] = None
) -> plt.Subplot:
"""
Plots a stacked barplot for all levels of a covariate or all samples (if feature_name=="samples").
Usage: plot_feature_stackbars(data, ["cov1", "cov2", "cov3"])
Parameters
----------
data
A scCODA compositional data object
feature_name
The name of the covariate to plot. If feature_name=="samples", one bar for every sample will be plotted
figsize
figure size
dpi
dpi setting
cmap
The color map for the barplot
plot_legend
If True, adds a legend
level_order
Custom ordering of bars on the x-axis
Returns
-------
Returns a plot
g:
a plot
"""
# cell type names
type_names = data.var.index
# option to plot one stacked barplot per sample
if feature_name == "samples":
if level_order:
assert set(level_order) == set(data.obs.index), "level order is inconsistent with levels"
data = data[level_order]
g = stackbar(
data.X,
type_names=data.var.index,
title="samples",
level_names=data.obs.index,
figsize=figsize,
dpi=dpi,
cmap=cmap,
plot_legend=plot_legend,
)
else:
# Order levels
if level_order:
assert set(level_order) == set(data.obs[feature_name]), "level order is inconsistent with levels"
levels = level_order
elif hasattr(data.obs[feature_name], 'cat'):
levels = data.obs[feature_name].cat.categories.to_list()
else:
levels = pd.unique(data.obs[feature_name])
n_levels = len(levels)
feature_totals = np.zeros([n_levels, data.X.shape[1]])
for level in range(n_levels):
l_indices = np.where(data.obs[feature_name] == levels[level])
feature_totals[level] = np.sum(data.X[l_indices], axis=0)
g = stackbar(
feature_totals,
type_names=type_names,
title=feature_name,
level_names=levels,
figsize=figsize,
dpi=dpi,
cmap=cmap,
plot_legend=plot_legend,
)
return g
def boxplots(
data: AnnData,
feature_name: str,
y_scale: str = "relative",
plot_facets: bool = False,
add_dots: bool = False,
cell_types: Optional[list] = None,
args_boxplot: Optional[dict] = {},
args_swarmplot: Optional[dict] = {},
figsize: Optional[Tuple[int, int]] = None,
dpi: Optional[int] = 100,
cmap: Optional[str] = "Blues",
plot_legend: Optional[bool] = True,
level_order: List[str] = None
) -> Optional[Tuple[plt.Subplot, sns.axisgrid.FacetGrid]]:
"""\
Grouped boxplot visualization. The cell counts for each cell type are shown as a group of boxplots,
with intra--group separation by a covariate from data.obs.
The cell type groups can either be ordered along the x-axis of a single plot (plot_facets=False) or as plot facets (plot_facets=True).
Parameters
----------
data
A scCODA-compatible data object
feature_name
The name of the feature in data.obs to plot
y_scale
Transformation to of cell counts. Options: "relative" - Relative abundance, "log" - log(count), "count" - absolute abundance (cell counts)
plot_facets
If False, plot cell types on the x-axis. If True, plot as facets
add_dots
If True, overlay a scatterplot with one dot for each data point
cell_types
Subset of cell types that should be plotted
args_boxplot
Arguments passed to sns.boxplot
args_swarmplot
Arguments passed to sns.swarmplot
figsize
figure size
dpi
dpi setting
cmap
The seaborn color map for the barplot
plot_legend
If True, adds a legend
level_order
Custom ordering of bars on the x-axis
Returns
-------
Depending on `plot_facets`, returns a :class:`~plt.AxesSubplot` (`plot_facets = False`) or :class:`~sns.axisgrid.FacetGrid` (`plot_facets = True`) object
ax
if `plot_facets = False`
g
if `plot_facets = True`
"""
# y scale transformations
if y_scale == "relative":
sample_sums = np.sum(data.X, axis=1, keepdims=True)
X = data.X/sample_sums
value_name = "Proportion"
# add pseudocount 1 if using log scale (needs to be improved)
elif y_scale == "log":
X = np.log(data.X + 1)
value_name = "log(count)"
elif y_scale == "count":
X = data.X
value_name = "count"
else:
raise ValueError("Invalid y_scale transformation")
count_df = pd.DataFrame(X, columns=data.var.index, index=data.obs.index).\
merge(data.obs[feature_name], left_index=True, right_index=True)
plot_df = pd.melt(count_df, id_vars=feature_name, var_name="Cell type", value_name=value_name)
if cell_types is not None:
plot_df = plot_df[plot_df["Cell type"].isin(cell_types)]
if plot_facets:
if level_order is None:
level_order = pd.unique(plot_df[feature_name])
K = X.shape[1]
g = sns.FacetGrid(
plot_df,
col="Cell type",
sharey=False,
col_wrap=int(np.floor(np.sqrt(K))),
height=5,
aspect=2,
)
g.map(
sns.boxplot,
feature_name,
value_name,
palette=cmap,
order=level_order,
**args_boxplot
)
if add_dots:
if "hue" in args_swarmplot:
hue = args_swarmplot.pop("hue")
else:
hue = None
if hue is None:
g.map(
sns.swarmplot,
feature_name,
value_name,
color="black",
order=level_order,
**args_swarmplot
).set_titles("{col_name}")
else:
g.map(
sns.swarmplot,
feature_name,
value_name,
hue,
order=level_order,
**args_swarmplot
).set_titles("{col_name}")
return g
else:
if level_order:
args_boxplot["hue_order"] = level_order
args_swarmplot["hue_order"] = level_order
fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
sns.boxplot(x="Cell type", y=value_name, hue=feature_name, data=plot_df, fliersize=1,
palette=cmap, ax=ax, **args_boxplot)
if add_dots:
sns.swarmplot(
x="Cell type",
y=value_name,
data=plot_df,
hue=feature_name,
ax=ax,
dodge=True,
color="black",
**args_swarmplot
)
cell_types = pd.unique(plot_df["Cell type"])
ax.set_xticklabels(cell_types, rotation=90)
if plot_legend:
handles, labels = ax.get_legend_handles_labels()
handout = []
labelout = []
for h, l in zip(handles, labels):
if l not in labelout:
labelout.append(l)
handout.append(h)
ax.legend(handout, labelout, loc='upper left', bbox_to_anchor=(1, 1), ncol=1, title=feature_name)
plt.tight_layout()
return ax
def rel_abundance_dispersion_plot(
data: AnnData,
abundant_threshold: Optional[float] = 0.9,
default_color: Optional[str] = "Grey",
abundant_color: Optional[str] = "Red",
label_cell_types: bool = "True",
figsize: Optional[Tuple[int, int]] = None,
dpi: Optional[int] = 100,
) -> plt.Subplot:
"""
Plots total variance of relative abundance versus minimum relative abundance of all cell types for determination of a reference cell type.
If the count of the cell type is larger than 0 in more than abundant_threshold percent of all samples,
the cell type will be marked in a different color.
Parameters
----------
data
A scCODA compositional data object
abundant_threshold
Presence threshold for abundant cell types.
default_color
bar color for all non-minimal cell types, default: "Grey"
abundant_color
bar color for cell types with abundant percentage larger than abundant_threshold, default: "Red"
label_cell_types
boolean - label dots with cell type names
figsize
figure size
dpi
dpi setting
Returns
-------
Returns a plot
ax
a plot
"""
fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
rel_abun = data.X / np.sum(data.X, axis=1, keepdims=True)
percent_zero = np.sum(data.X == 0, axis=0) / data.X.shape[0]
nonrare_ct = np.where(percent_zero < 1-abundant_threshold)[0]
# select reference
cell_type_disp = np.var(rel_abun, axis=0) / np.mean(rel_abun, axis=0)
is_abundant = [x in nonrare_ct for x in range(data.X.shape[1])]
# Scatterplot
plot_df = pd.DataFrame({
"Total dispersion": cell_type_disp,
"Cell type": data.var.index,
"Presence": 1-percent_zero,
"Is abundant": is_abundant
})
if len(np.unique(plot_df["Is abundant"])) > 1:
palette = [default_color, abundant_color]
elif np.unique(plot_df["Is abundant"]) == [False]:
palette = [default_color]
else:
palette = [abundant_color]
sns.scatterplot(
data=plot_df,
x="Presence",
y="Total dispersion",
hue="Is abundant",
palette=palette
)
# Text labels for abundant cell types
abundant_df = plot_df.loc[plot_df["Is abundant"] == True, :]
def label_point(x, y, val, ax):
a = pd.concat({'x': x, 'y': y, 'val': val}, axis=1)
for i, point in a.iterrows():
ax.text(point['x'] + .02*ax.get_xlim()[1], point['y'], str(point['val']))
if label_cell_types:
label_point(
abundant_df["Presence"],
abundant_df["Total dispersion"],
abundant_df["Cell type"],
plt.gca()
)
ax.legend(loc='upper left', bbox_to_anchor=(1, 1), ncol=1, title="Is abundant")
plt.tight_layout()
return ax
|
/scCODA-0.1.9.tar.gz/scCODA-0.1.9/sccoda/util/data_visualization.py
| 0.895177 | 0.622717 |
data_visualization.py
|
pypi
|
import numpy as np
import arviz as az
import pandas as pd
import pickle as pkl
from typing import Optional, Tuple, Collection, Union, List
class CAResultConverter(az.data.io_dict.DictConverter):
"""
Helper class for result conversion into arviz's format
"""
def to_result_data(self, sampling_stats, model_specs):
post = self.posterior_to_xarray()
ss = self.sample_stats_to_xarray()
postp = self.posterior_predictive_to_xarray()
prior = self.prior_to_xarray()
ssp = self.sample_stats_prior_to_xarray()
prip = self.prior_predictive_to_xarray()
obs = self.observed_data_to_xarray()
return CAResult(
sampling_stats, model_specs,
**{
"posterior": post,
"sample_stats": ss,
"posterior_predictive": postp,
"prior": prior,
"sample_stats_prior": ssp,
"prior_predictive": prip,
"observed_data": obs,
}
)
class CAResult(az.InferenceData):
"""
Result class for scCODA, extends the arviz framework for inference data.
The CAResult class is an extension of az.InferenceData, that adds some information about the compositional model
and is able to print humanly readable results.
It supports all functionality from az.InferenceData.
"""
def __init__(
self,
sampling_stats: dict,
model_specs: dict,
**kwargs
):
"""
Gathers sampling information from a compositional model and converts it to a ``az.InferenceData`` object.
The following attributes are added during class initialization:
``self.sampling_stats``: dict - see below
``self.model_specs``: dict - see below
``self.intercept_df``: Intercept dataframe from ``CAResult.summary_prepare``
``self.effect_df``: Effect dataframe from ``CAResult.summary_prepare``
Parameters
----------
sampling_stats
Information and statistics about the MCMC sampling procedure.
Default keys:
- "chain_length": Length of MCMC chain (with burnin samples)
- "num_burnin": Number of burnin samples
- "acc_rate": MCMC Acceptance rate
- "duration": Duration of MCMC sampling
model_specs
All information and statistics about the model specifications.
Default keys:
- "formula": Formula string
- "reference": int - identifier of reference cell type
Added during class initialization:
- "threshold_prob": Threshold for inclusion probability that separates significant from non-significant effects
kwargs
passed to az.InferenceData. This includes the MCMC chain states and statistics for eachs MCMC sample.
"""
super(self.__class__, self).__init__(**kwargs)
self.sampling_stats = sampling_stats
self.model_specs = model_specs
if "ind" in list(self.posterior.data_vars):
self.is_sccoda = True
else:
self.is_sccoda = False
intercept_df, effect_df = self.summary_prepare()
self.intercept_df = intercept_df
self.effect_df = effect_df
def summary_prepare(
self,
est_fdr: float = 0.05,
*args,
**kwargs
) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""
Generates summary dataframes for intercepts and slopes.
This function builds on and supports all functionalities from ``az.summary``.
Parameters
----------
est_fdr
Desired FDR value
args
Passed to ``az.summary``
kwargs
Passed to ``az.summary``
Returns
-------
Intercept and effect DataFrames
intercept_df -- pandas df
Summary of intercept parameters. Contains one row per cell type.
Columns:
- Final Parameter: Final intercept model parameter
- HDI X%: Upper and lower boundaries of confidence interval (width specified via hdi_prob=)
- SD: Standard deviation of MCMC samples
- Expected sample: Expected cell counts for a sample with no present covariates. See the tutorial for more explanation
effect_df -- pandas df
Summary of effect (slope) parameters. Contains one row per covariate/cell type combination.
Columns:
- Final Parameter: Final effect model parameter. If this parameter is 0, the effect is not significant, else it is.
- HDI X%: Upper and lower boundaries of confidence interval (width specified via hdi_prob=)
- SD: Standard deviation of MCMC samples
- Expected sample: Expected cell counts for a sample with only the current covariate set to 1. See the tutorial for more explanation
- log2-fold change: Log2-fold change between expected cell counts with no covariates and with only the current covariate
- Inclusion probability: Share of MCMC samples, for which this effect was not set to 0 by the spike-and-slab prior.
"""
# initialize summary df from arviz and separate into intercepts and effects.
summ = az.summary(self, *args, **kwargs, kind="stats", var_names=["alpha", "beta"])
effect_df = summ.loc[summ.index.str.match("|".join(["beta"]))].copy()
intercept_df = summ.loc[summ.index.str.match("|".join(["alpha"]))].copy()
# Build neat index
cell_types = self.posterior.coords["cell_type"].values
covariates = self.posterior.coords["covariate"].values
intercept_df.index = pd.Index(cell_types, name="Cell Type")
effect_df.index = pd.MultiIndex.from_product([covariates, cell_types],
names=["Covariate", "Cell Type"])
# Calculation of columns that are not from az.summary
intercept_df = self.complete_alpha_df(intercept_df)
effect_df = self.complete_beta_df(intercept_df, effect_df, est_fdr)
# Give nice column names, remove unnecessary columns
hdis = intercept_df.columns[intercept_df.columns.str.contains("hdi")]
hdis_new = hdis.str.replace("hdi_", "HDI ")
# Credible interval
if self.is_sccoda is True:
ind_post = self.posterior["ind"]
b_raw_sel = self.posterior["b_raw"] * ind_post.where(ind_post >= 1e-3)
res = az.convert_to_inference_data(b_raw_sel)
summary_sel = az.summary(res, kind="stats", var_names=["x"], skipna=True, *args, **kwargs)
ref_index = self.model_specs["reference"]
n_conditions = len(self.posterior.coords["covariate"])
n_cell_types = len(self.posterior.coords["cell_type"])
def insert_row(idx, df, df_insert):
return pd.concat([df.iloc[:idx, ], df_insert, df.iloc[idx:, ]]).reset_index(drop=True)
for i in range(n_conditions):
summary_sel = insert_row((i*n_cell_types) + ref_index, summary_sel,
pd.DataFrame.from_dict(data={"mean": [0], "sd": [0], hdis[0]: [0], hdis[1]: [0]}))
effect_df.loc[:, hdis[0]] = list(summary_sel[hdis[0]])
effect_df.loc[:, hdis[1]] = list(summary_sel.loc[:, hdis[1]])
intercept_df = intercept_df.loc[:, ["final_parameter", hdis[0], hdis[1], "sd", "expected_sample"]].copy()
intercept_df = intercept_df.rename(columns=dict(zip(
intercept_df.columns,
["Final Parameter", hdis_new[0], hdis_new[1], "SD", "Expected Sample"]
)))
effect_df = effect_df.loc[:, ["final_parameter", hdis[0], hdis[1], "sd", "inclusion_prob",
"expected_sample", "log_fold"]].copy()
effect_df = effect_df.rename(columns=dict(zip(
effect_df.columns,
["Final Parameter", hdis_new[0], hdis_new[1], "SD", "Inclusion probability",
"Expected Sample", "log2-fold change"]
)))
return intercept_df, effect_df
def complete_beta_df(
self,
intercept_df: pd.DataFrame,
effect_df: pd.DataFrame,
target_fdr: float=0.05,
) -> pd.DataFrame:
"""
Evaluation of MCMC results for effect parameters. This function is only used within self.summary_prepare.
This function also calculates the posterior inclusion probability for each effect and decides whether effects are significant.
Parameters
----------
intercept_df
Intercept summary, see ``self.summary_prepare``
effect_df
Effect summary, see ``self.summary_prepare``
target_fdr
Desired FDR value
Returns
-------
effect DataFrame
effect_df
DataFrame with inclusion probability, final parameters, expected sample
"""
beta_inc_prob = []
beta_nonzero_mean = []
beta_raw = np.array(self.posterior["beta"])[0]
# Calculate inclusion prob, nonzero mean for every effect
for j in range(beta_raw.shape[1]):
for i in range(beta_raw.shape[2]):
beta_i_raw = beta_raw[:, j, i]
beta_i_raw_nonzero = np.where(np.abs(beta_i_raw) > 1e-3)[0]
prob = beta_i_raw_nonzero.shape[0] / beta_i_raw.shape[0]
beta_inc_prob.append(prob)
if len(beta_i_raw[beta_i_raw_nonzero]) > 0:
beta_nonzero_mean.append(beta_i_raw[beta_i_raw_nonzero].mean())
else:
beta_nonzero_mean.append(0)
effect_df.loc[:, "inclusion_prob"] = beta_inc_prob
effect_df.loc[:, "mean_nonzero"] = beta_nonzero_mean
# Inclusion prob threshold value. Direct posterior probability approach cf. Newton et al. (2004)
if self.is_sccoda is True:
def opt_thresh(result, alpha):
incs = np.array(result.loc[result["inclusion_prob"] > 0, "inclusion_prob"])
incs[::-1].sort()
for c in np.unique(incs):
fdr = np.mean(1 - incs[incs >= c])
if fdr < alpha:
# ceiling with 3 decimals precision
c = np.floor(c * 10 ** 3) / 10 ** 3
return c, fdr
return 1., 0
threshold, fdr_ = opt_thresh(effect_df, target_fdr)
self.model_specs["threshold_prob"] = threshold
# Decide whether betas are significant or not, set non-significant ones to 0
effect_df.loc[:, "final_parameter"] = np.where(effect_df.loc[:, "inclusion_prob"] >= threshold,
effect_df.loc[:, "mean_nonzero"],
0)
else:
effect_df.loc[:, "final_parameter"] = effect_df.loc[:, "mean_nonzero"]
# Get expected sample, log-fold change
D = len(effect_df.index.levels[0])
K = len(effect_df.index.levels[1])
y_bar = np.mean(np.sum(np.array(self.observed_data.y), axis=1))
alpha_par = intercept_df.loc[:, "final_parameter"]
alphas_exp = np.exp(alpha_par)
alpha_sample = (alphas_exp / np.sum(alphas_exp) * y_bar).values
beta_mean = alpha_par
beta_sample = []
log_sample = []
for d in range(D):
beta_d = effect_df.loc[:, "final_parameter"].values[(d*K):((d+1)*K)]
beta_d = (beta_mean + beta_d)
beta_d = np.exp(beta_d)
beta_d = beta_d / np.sum(beta_d) * y_bar
beta_sample = np.append(beta_sample, beta_d)
log_sample = np.append(log_sample, np.log2(beta_d/alpha_sample))
effect_df.loc[:, "expected_sample"] = beta_sample
effect_df.loc[:, "log_fold"] = log_sample
return effect_df
def complete_alpha_df(
self,
intercept_df: pd.DataFrame
) -> pd.DataFrame:
"""
Evaluation of MCMC results for intercepts. This function is only used within self.summary_prepare.
Parameters
----------
intercept_df
Intercept summary, see self.summary_prepare
Returns
-------
intercept DataFrame
intercept_df
Summary DataFrame with expected sample, final parameters
"""
intercept_df = intercept_df.rename(columns={"mean": "final_parameter"})
# Get expected sample
y_bar = np.mean(np.sum(np.array(self.observed_data.y), axis=1))
alphas_exp = np.exp(intercept_df.loc[:, "final_parameter"])
alpha_sample = (alphas_exp / np.sum(alphas_exp) * y_bar).values
intercept_df.loc[:, "expected_sample"] = alpha_sample
return intercept_df
def summary(
self,
*args,
**kwargs
):
"""
Printing method for scCODA's summary.
Usage: ``result.summary()``
Parameters
----------
args
Passed to az.summary
kwargs
Passed to az.summary
Returns
-------
prints to console
"""
# If other than default values for e.g. confidence interval are specified,
# recalculate them for intercept and effect DataFrames
if args or kwargs:
intercept_df, effect_df = self.summary_prepare(*args, **kwargs)
else:
intercept_df = self.intercept_df
effect_df = self.effect_df
# Get number of samples, cell types
if self.sampling_stats["y_hat"] is not None:
data_dims = self.sampling_stats["y_hat"].shape
else:
data_dims = (10, 5)
# Cut down DataFrames to relevant info
alphas_print = intercept_df.loc[:, ["Final Parameter", "Expected Sample"]]
betas_print = effect_df.loc[:, ["Final Parameter", "Expected Sample", "log2-fold change"]]
# Print everything neatly
print("Compositional Analysis summary:")
print("")
print("Data: %d samples, %d cell types" % data_dims)
print("Reference index: %s" % str(self.model_specs["reference"]))
print("Formula: %s" % self.model_specs["formula"])
print("")
print("Intercepts:")
print(alphas_print)
print("")
print("")
print("Effects:")
print(betas_print)
def summary_extended(
self,
*args,
**kwargs
):
"""
Extended (diagnostic) printing function that shows more info about the sampling result
Parameters
----------
args
Passed to az.summary
kwargs
Passed to az.summary
Returns
-------
Prints to console
"""
# If other than default values for e.g. confidence interval are specified,
# recalculate them for intercept and effect DataFrames
if args or kwargs:
intercept_df, effect_df = self.summary_prepare(*args, **kwargs)
else:
intercept_df = self.intercept_df
effect_df = self.effect_df
# Get number of samples, cell types
data_dims = self.sampling_stats["y_hat"].shape
# Print everything
print("Compositional Analysis summary (extended):")
print("")
print("Data: %d samples, %d cell types" % data_dims)
print("Reference index: %s" % str(self.model_specs["reference"]))
print("Formula: %s" % self.model_specs["formula"])
if self.is_sccoda:
print("Spike-and-slab threshold: {threshold:.3f}".format(threshold=self.model_specs["threshold_prob"]))
print("")
print("MCMC Sampling: Sampled {num_results} chain states ({num_burnin} burnin samples) in {duration:.3f} sec. "
"Acceptance rate: {ar:.1f}%".format(num_results=self.sampling_stats["chain_length"],
num_burnin=self.sampling_stats["num_burnin"],
duration=self.sampling_stats["duration"],
ar=(100*self.sampling_stats["acc_rate"])))
print("")
print("Intercepts:")
print(intercept_df)
print("")
print("")
print("Effects:")
print(effect_df)
def compare_parameters_to_truth(
self,
b_true: pd.Series,
w_true: pd.Series,
*args,
**kwargs
) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""
Extends data frames from summary_prepare by a comparison to some ground truth slope and intercept values that are
assumed to be from the same generative model (e.g. in data_generation)
Parameters
----------
b_true
Ground truth slope values. Length must be same as number of cell types
w_true
Ground truth intercept values. Length must be same as number of cell types*number of covariates
args
Passed to az.summary
kwargs
Passed to az.summary
Returns
-------
Extends intercept and effect DataFrames
intercept_df
Summary DataFrame for intercepts
effect_df
Summary DataFrame for effects
"""
intercept_df, effect_df = self.summary_prepare(*args, **kwargs)
intercept_df.columns = intercept_df.columns.str.replace('final_parameter', 'predicted')
effect_df.columns = effect_df.columns.str.replace('final_parameter', 'predicted')
# Get true params, join to calculated parameters
b_true = b_true.rename("truth")
intercept_df = intercept_df.join(b_true)
w_true = w_true.rename("truth")
effect_df = effect_df.join(w_true)
# decide whether effects are found correctly
intercept_df['dist_to_truth'] = intercept_df['truth'] - intercept_df['predicted']
intercept_df['effect_correct'] = ((intercept_df['truth'] == 0) == (intercept_df['predicted'] == 0))
effect_df['dist_to_truth'] = effect_df['truth'] - effect_df['predicted']
effect_df['effect_correct'] = ((effect_df['truth'] == 0) == (effect_df['predicted'] == 0))
return intercept_df, effect_df
def distance_to_truth(self) -> pd.DataFrame:
"""
Compares real cell count matrix to the posterior mode cell count matrix that arises from the calculated parameters
Returns
-------
DataFrame with distances
ret
DataFrame
"""
# Get absolute (counts) and relative error matrices
y = np.array(self.observed_data.y)
y_hat = self.sampling_stats["y_hat"]
err = np.abs(y_hat - y)
err_rel = err / y
err_rel[np.isinf(err_rel)] = 1.
err_rel[np.isnan(err_rel)] = 0.
# Calculate mean errors for each cell type and overall
avg_abs_cell_type_error = np.mean(err, axis=0, dtype=np.float64)
avg_rel_cell_type_error = np.mean(err_rel, axis=0, dtype=np.float64)
avg_abs_total_error = np.mean(err, dtype=np.float64)
avg_rel_total_error = np.mean(err_rel, dtype=np.float64)
ret = pd.DataFrame({'Cell Type': np.arange(y.shape[1] + 1),
'Absolute Error': np.append(avg_abs_total_error, avg_abs_cell_type_error),
'Relative Error': np.append(avg_rel_total_error, avg_rel_cell_type_error),
'Actual Means': np.append(np.mean(y, axis=(0, 1)), np.mean(y, axis=0)),
'Predicted Means': np.append(np.mean(y_hat, axis=(0, 1)), np.mean(y_hat, axis=0))})
ret['Cell Type'][0] = 'Total'
return ret
def credible_effects(
self,
est_fdr=None
) -> pd.Series:
"""
Decides which effects of the scCODA model are credible based on an adjustable inclusion probability threshold.
Parameters
----------
est_fdr
Estimated false discovery rate. Must be between 0 and 1
Returns
-------
Credible effect decision series
out
Boolean values whether effects are credible under inc_prob_threshold
"""
if type(est_fdr) == float:
if est_fdr < 0 or est_fdr > 1:
raise ValueError("est_fdr must be between 0 and 1!")
else:
_, eff_df = self.summary_prepare(est_fdr=est_fdr)
else:
eff_df = self.effect_df
out = eff_df["Final Parameter"] != 0
out.rename("credible change")
return out
def save(
self,
path_to_file: str
):
"""
Function to save scCODA results to disk via pickle. Caution: Files can quickly become very large!
Parameters
----------
path_to_file
saving location on disk
Returns
-------
"""
with open(path_to_file, "wb") as f:
pkl.dump(self, file=f, protocol=4)
def set_fdr(
self,
est_fdr: float,
*args,
**kwargs):
"""
Direct posterior probability approach to calculate credible effects while keeping the expected FDR at a certain level
Parameters
----------
est_fdr
Desired FDR value
args
passed to self.summary_prepare
kwargs
passed to self.summary_prepare
Returns
-------
Adjusts self.intercept_df and self.effect_df
"""
intercept_df, effect_df = self.summary_prepare(est_fdr=est_fdr, *args, **kwargs)
self.intercept_df = intercept_df
self.effect_df = effect_df
|
/scCODA-0.1.9.tar.gz/scCODA-0.1.9/sccoda/util/result_classes.py
| 0.89069 | 0.580233 |
result_classes.py
|
pypi
|
import numpy as np
import anndata as ad
import pandas as pd
from scipy.special import softmax
from anndata import AnnData
from typing import Optional, Tuple, Collection, Union, List
def generate_case_control(
cases: int = 1,
K: int = 5,
n_total: int = 1000,
n_samples: List[any] = [5, 5],
sigma: Optional[np.ndarray] = None,
b_true: Optional[np.ndarray] = None,
w_true: Optional[np.ndarray] = None
) -> AnnData:
"""
Generates compositional data with binary covariates.
Parameters
----------
cases
number of covariates.
This will lead to D=2**cases columns in X, one for each combination of active/inactive covariates.
K
Number of cell types
n_total
number of cells per sample
n_samples
Number of samples per case combination. len(n_samples)=[2**cases]
sigma
correlation matrix for cell types,size KxK
b_true
bias coefficients, size K
w_true
Effect matrix, size DxK
Returns
-------
compositional data
data
Anndata object
"""
D = cases**2
# Uniform intercepts if none are specifed
if b_true is None:
b_true = np.random.uniform(-3, 3, size=K).astype(np.float64) # bias (alpha)
# Randomly select covariates that should correlate if none are specified
if w_true is None:
n_d = np.random.choice(range(D), size=1)
n_k = np.random.choice(range(K), size=1)
w_true = sparse_effect_matrix(D, K, n_d, n_k)
# Sigma is identity if not specified else
if sigma is None:
sigma = np.identity(K) * 0.05
# noise = noise_std_true * np.random.randn(N, 1).astype(np.float64)
# Initialize x, y
x = np.zeros((sum(n_samples), cases))
y = np.zeros((sum(n_samples), K))
c = 0
# Binary representation of a number x as list of fixed length
def binary(num, length):
return [int(x_n) for x_n in bin(num)[2:].zfill(length)]
# For all combinations of cases
for i in range(2**cases):
# For each sample with this combination
for j in range(n_samples[i]):
# row of x is binary representation
x[c+j] = binary(i, cases)
# Generate y
alpha = np.random.multivariate_normal(mean=x[c+j, :].T @ w_true + b_true, cov=sigma).astype(
np.float64)
concentration = softmax(alpha).astype(np.float64)
z = np.random.multinomial(n_total, concentration)
y[c+j] = z
c = c+n_samples[i]
x = x.astype(np.float64)
y = y.astype(np.float64)
x_names = ["x_" + str(n) for n in range(x.shape[1])]
x_df = pd.DataFrame(x, columns=x_names)
x_df.index = x_df.index.astype(str)
data = ad.AnnData(X=y, obs=x_df, uns={"b_true": b_true, "w_true": w_true})
return data
def b_w_from_abs_change(
counts_before: np.ndarray = np.array([200, 200, 200, 200, 200]),
abs_change: np.ndarray = np.array([50, 0, 0, 0, 0]),
n_total: int = 1000
) -> Tuple[np.ndarray, np.ndarray]:
"""
Calculates intercepts and slopes from a starting count and an absolute change for the first cell type
Parameters
----------
counts_before
cell counts for control samples
abs_change
change of first cell type in terms of cell counts
n_total
number of cells per sample. This stays constant over all samples!!!
Returns
-------
Returns an intercept and an effect array
intercepts
intercept parameters
slopes
slope parameters
"""
K = counts_before.shape[0]
# calculate intercepts for control samples
b = np.log(counts_before / n_total)
# count vector after applying the effect.
counts_after = counts_before + abs_change
da = np.where(abs_change!=0)[0]
sum_after_da = np.sum(counts_after[da])
non_da = [x for x in np.arange(K) if x not in da]
n_non_da = len(non_da)
count_non_da = (n_total - sum_after_da)/n_non_da
counts_after[non_da] = count_non_da
# Get parameter vector with effect
b_after = np.log(counts_after / n_total)
# w is the difference of b before and after
w = b_after - b
# Transform w such that only first entry is nonzero
w = w - w[K - 1]
return b, w
def counts_from_first(
b_0: int = 200,
n_total: int = 1000,
K: int = 5
) -> np.ndarray:
"""
Calculates a count vector from a given first entry, length and sum. The entries 2...K will get the same value.
Parameters
----------
b_0
size of first entry
n_total
total sum of all entries
K
length of output vector (number of cell types)
Returns
-------
An intercept array
b
count vector (not necessarily integer), size K
"""
b = np.repeat((n_total-b_0)/(K-1), K)
b[0] = b_0
return b
def sparse_effect_matrix(
D: int,
K: int,
n_d: int,
n_k: int
) -> np.ndarray:
"""
Generates a sparse effect matrix
Parameters
----------
D
Number of covariates
K
Number of cell types
n_d
Number of covariates that effect each cell type
n_k
Number of cell types that are affected by each covariate
Returns
-------
An effect matrix
w_true
Effect matrix
"""
# Choose indices of affected cell types and covariates randomly
d_eff = np.random.choice(range(D), size=n_d, replace=False)
k_eff = np.random.choice(range(K), size=n_k, replace=False)
# Possible entries of w_true
w_choice = [0.3, 0.5, 1]
w_true = np.zeros((D, K))
# Fill in w_true
for i in d_eff:
for j in k_eff:
c = np.random.choice(3, 1)
w_true[i, j] = w_choice[c]
return w_true
|
/scCODA-0.1.9.tar.gz/scCODA-0.1.9/sccoda/util/data_generation.py
| 0.898003 | 0.752808 |
data_generation.py
|
pypi
|
import numpy as np
import patsy as pt
from anndata import AnnData
from sccoda.model import scCODA_model as dm
from typing import Union, Optional
class CompositionalAnalysis:
"""
Initializer class for scCODA models. This class is called when performing compositional analysis with scCODA.
Usage: model = CompositionalAnalysis(data, formula="covariate1 + covariate2", reference_cell_type="CellTypeA")
Calling an scCODA model requires these parameters:
data
anndata object with cell counts as data.X and covariates saved in data.obs
formula
patsy-style formula for building the covariate matrix.
Categorical covariates are handled automatically, with the covariate value of the first sample being used as the reference category.
To set a different level as the base category for a categorical covariate, use "C(<CovariateName>, Treatment('<ReferenceLevelName>'))"
reference_cell_type
Column index that sets the reference cell type. Can either reference the name of a column or a column number (starting at 0).
If "automatic", the cell type with the lowest dispersion in relative abundance that is present in at least 90% of samlpes will be chosen.
"""
def __new__(
cls,
data: AnnData,
formula: str,
reference_cell_type: Union[str, int] = "automatic",
automatic_reference_absence_threshold: float = 0.05,
) -> dm.scCODAModel:
"""
Builds count and covariate matrix, returns a CompositionalModel object
Usage: model = CompositionalAnalysis(data, formula="covariate1 + covariate2", reference_cell_type="CellTypeA")
Parameters
----------
data
anndata object with cell counts as data.X and covariates saved in data.obs
formula
R-style formula for building the covariate matrix.
Categorical covariates are handled automatically, with the covariate value of the first sample being used as the reference category.
To set a different level as the base category for a categorical covariate, use "C(<CovariateName>, Treatment('<ReferenceLevelName>'))"
reference_cell_type
Column index that sets the reference cell type. Can either reference the name of a column or the n-th column (indexed at 0).
If "automatic", the cell type with the lowest dispersion in relative abundance that is present in at least 90% of samlpes will be chosen.
automatic_reference_absence_threshold
If using reference_cell_type = "automatic", determine what the maximum fraction of zero entries for a cell type is to be considered as a possible reference cell type
Returns
-------
A compositional model
model
A scCODA.models.scCODA_model.CompositionalModel object
"""
cell_types = data.var.index.to_list()
# Get count data
data_matrix = data.X.astype("float64")
# Build covariate matrix from R-like formula
covariate_matrix = pt.dmatrix(formula, data.obs)
covariate_names = covariate_matrix.design_info.column_names[1:]
covariate_matrix = covariate_matrix[:, 1:]
# Invoke instance of the correct model depending on reference cell type
# Automatic reference selection (dispersion-based)
if reference_cell_type == "automatic":
percent_zero = np.sum(data_matrix == 0, axis=0)/data_matrix.shape[0]
nonrare_ct = np.where(percent_zero < automatic_reference_absence_threshold)[0]
if len(nonrare_ct) == 0:
raise ValueError("No cell types that have large enough presence! Please increase automatic_reference_absence_threshold")
rel_abun = data_matrix / np.sum(data_matrix, axis=1, keepdims=True)
# select reference
cell_type_disp = np.var(rel_abun, axis=0)/np.mean(rel_abun, axis=0)
min_var = np.min(cell_type_disp[nonrare_ct])
ref_index = np.where(cell_type_disp == min_var)[0][0]
ref_cell_type = cell_types[ref_index]
print(f"Automatic reference selection! Reference cell type set to {ref_cell_type}")
return dm.scCODAModel(
covariate_matrix=np.array(covariate_matrix),
data_matrix=data_matrix,
cell_types=cell_types,
covariate_names=covariate_names,
reference_cell_type=ref_index,
formula=formula,
)
# Column name as reference cell type
elif reference_cell_type in cell_types:
num_index = cell_types.index(reference_cell_type)
return dm.scCODAModel(
covariate_matrix=np.array(covariate_matrix),
data_matrix=data_matrix,
cell_types=cell_types,
covariate_names=covariate_names,
reference_cell_type=num_index,
formula=formula,
)
# Numeric reference cell type
elif isinstance(reference_cell_type, int) & (reference_cell_type < len(cell_types)) & (reference_cell_type >= 0):
return dm.scCODAModel(
covariate_matrix=np.array(covariate_matrix),
data_matrix=data_matrix,
cell_types=cell_types,
covariate_names=covariate_names,
reference_cell_type=reference_cell_type,
formula=formula,
)
# None of the above: Throw error
else:
raise NameError("Reference index is not a valid cell type name or numerical index!")
|
/scCODA-0.1.9.tar.gz/scCODA-0.1.9/sccoda/util/comp_ana.py
| 0.93811 | 0.724432 |
comp_ana.py
|
pypi
|
import pandas as pd
import anndata as ad
import os
import numpy as np
from anndata import AnnData
from typing import Optional, Tuple, Collection, Union, List
def read_anndata_one_sample(
adata: AnnData,
cell_type_identifier: str,
covariate_key: Optional[str] = None
) -> Tuple[np.ndarray, dict]:
"""
Converts a single scRNA-seq data set from scanpy (anndata format) to a row of a cell count matrix.
It is assumed that a column of adata.obs (e.g. Louvain clustering results) contains the cell type assignment.
Additionally, covariates (control/disease group, ...) can be specified as a subdict in adata.uns
Usage:
``cell_counts, covs = from_scanpy(adata, cell_type_identifier="Louvain", covariate_key="covariates")``
Parameters
----------
adata
single-cell data object from scanpy
cell_type_identifier
column name in adata.obs that specifies the cell types
covariate_key
key for adata.uns, where the covariate values are stored
Returns
-------
A numpy array for the cell counts and a dict for the covariates
cell_counts
cell count vector
covs
covariate dictionary
"""
# Calculate cell counts for the sample
cell_counts = adata.obs[cell_type_identifier].value_counts()
# extracting covariates from uns
if covariate_key is not None:
covs = adata.uns[covariate_key]
return cell_counts, covs
else:
return cell_counts
def from_scanpy_list(
samples: List[AnnData],
cell_type_identifier: str,
covariate_key: Optional[str] = None,
covariate_df: Optional[pd.DataFrame] = None
) -> AnnData:
"""
Creates a compositional analysis data set from a list of scanpy data sets.
To use this function, all data sets need to have one identically named column in adata.obs that contains the cell type assignment.
Covariates can either be specified via a key in adata.uns, or as a separate DataFrame
Usage:
``data = from_scanpy_list([adata1, adata2, adata3], cell_type_identifier="Louvain", covariate_df="covariates")``
Parameters
----------
samples
list of scanpy data sets
cell_type_identifier
column name in adata.obs that specifies the cell types
covariate_key
key for adata.uns, where covariate values are stored
covariate_df
DataFrame with covariates
Returns
-------
A compositional analysis data set
data
A compositional analysis data set
"""
count_data = pd.DataFrame()
covariate_data = pd.DataFrame()
# iterate over anndata objects for each sample
if covariate_key is not None:
for s in samples:
cell_counts, covs = read_anndata_one_sample(s, cell_type_identifier, covariate_key)
cell_counts = pd.DataFrame(cell_counts).T
count_data = pd.concat([count_data, cell_counts])
covariate_data = pd.concat([covariate_data, pd.Series(covs).to_frame().T], ignore_index=True)
elif covariate_df is not None:
for s in samples:
cell_counts = read_anndata_one_sample(s, cell_type_identifier)
cell_counts = pd.DataFrame(cell_counts).T
count_data = pd.concat([count_data, cell_counts])
covariate_data = covariate_df
else:
print("No covariate information specified!")
return
# Replace NaNs
count_data = count_data.fillna(0)
covariate_data.index = covariate_data.index.astype(str)
var_dat = count_data.sum(axis=0).rename("n_cells").to_frame()
var_dat.index = var_dat.index.astype(str)
return ad.AnnData(X=count_data.values,
var=var_dat,
obs=covariate_data)
def from_scanpy_dir(
path: str,
cell_type_identifier: str,
covariate_key: Optional[str] = None,
covariate_df: Optional[pd.DataFrame] = None
) -> AnnData:
"""
Creates a compositional analysis data set from all scanpy data sets in a directory.
To use this function, all data sets need to have one identically named column in adata.obs that contains the cell type assignment.
Covariates can either be specified via a key in adata.uns, or as a separate DataFrame
Usage:
``data = from_scanpy_dir("./path/to/directory", cell_type_identifier="Louvain", covariate_key="covariates")``
Parameters
----------
path
path to directory
cell_type_identifier
column name in adata.obs that specifies the cell types
covariate_key
key for adata.uns, where covariate values are stored
covariate_df
DataFrame with covariates
Returns
-------
A compositional analysis data set
data
A compositional analysis data set
"""
count_data = pd.DataFrame()
covariate_data = pd.DataFrame()
filenames = os.listdir(path)
if covariate_key is not None:
for f in filenames:
adata = ad.read_h5ad(f)
cell_counts, covs = read_anndata_one_sample(adata, cell_type_identifier, covariate_key)
cell_counts = pd.DataFrame(cell_counts).T
count_data = pd.concat([count_data, cell_counts])
covariate_data = pd.concat([covariate_data, pd.Series(covs).to_frame().T], ignore_index=True)
elif covariate_df is not None:
for f in filenames:
adata = ad.read_h5ad(f)
cell_counts = read_anndata_one_sample(adata, cell_type_identifier)
cell_counts = pd.DataFrame(cell_counts).T
count_data = pd.concat([count_data, cell_counts])
covariate_data = covariate_df
else:
print("No covariate information specified!")
return
# Replace NaNs
count_data = count_data.fillna(0)
covariate_data.index = covariate_data.index.astype(str)
var_dat = count_data.sum(axis=0).rename("n_cells").to_frame()
var_dat.index = var_dat.index.astype(str)
return ad.AnnData(X=count_data.values,
var=var_dat,
obs=covariate_data)
def from_scanpy(
adata: AnnData,
cell_type_identifier: str,
sample_identifier: str,
covariate_key: Optional[str] = None,
covariate_df: Optional[pd.DataFrame] = None
) -> AnnData:
"""
Creates a compositional analysis dataset from a single anndata object, as it is produced by e.g. scanpy.
The anndata object needs to have a column in adata.obs that contains the cell type assignment,
and one column that specifies the grouping into samples.
Covariates can either be specified via a key in adata.uns, or as a separate DataFrame.
NOTE: The order of samples in the returned dataset is determined by the first occurence of cells from each sample in `adata`
Parameters
----------
adata
list of scanpy data sets
cell_type_identifier
column name in adata.obs that specifies the cell types
sample_identifier
column name in adata.obs that specifies the sample
covariate_key
key for adata.uns, where covariate values are stored
covariate_df
DataFrame with covariates
Returns
-------
A compositional analysis data set
data
A compositional analysis data set
"""
groups = adata.obs.value_counts([sample_identifier, cell_type_identifier])
count_data = groups.unstack(level=cell_type_identifier)
count_data = count_data.fillna(0)
if covariate_key is not None:
covariate_df = pd.DataFrame(adata.uns[covariate_key])
elif covariate_df is None:
print("No covariate information specified!")
covariate_df = pd.DataFrame(index=count_data.index)
if set(covariate_df.index) != set(count_data.index):
raise ValueError("anndata sample names and covariate_df index do not have the same elements!")
covs_ord = covariate_df.reindex(count_data.index)
covs_ord.index = covs_ord.index.astype(str)
var_dat = count_data.sum(axis=0).rename("n_cells").to_frame()
var_dat.index = var_dat.index.astype(str)
return ad.AnnData(X=count_data.values,
var=var_dat,
obs=covs_ord)
def from_pandas(
df: pd.DataFrame,
covariate_columns: List[str]
) -> AnnData:
"""
Converts a Pandas DataFrame into a compositional analysis data set.
The DataFrame must contain one row per sample, columns can be cell types or covariates
Note that all columns that are not specified as covariates are assumed to be cell types.
Usage:
``data = from_pandas(df, covariate_columns=["cov1", "cov2"])``
Parameters
----------
df
A pandas DataFrame with each row representing a sample; the columns can be cell counts or covariates
covariate_columns
List of column names that are interpreted as covariates; all other columns will be seen as cell types
Returns
-------
A compositional analysis data set
data
A compositional analysis data set
"""
covariate_data = df.loc[:, covariate_columns]
covariate_data.index = covariate_data.index.astype(str)
count_data = df.loc[:, ~df.columns.isin(covariate_data)]
celltypes = pd.DataFrame(index=count_data.columns)
return ad.AnnData(X=count_data.values,
var=celltypes,
obs=covariate_data)
|
/scCODA-0.1.9.tar.gz/scCODA-0.1.9/sccoda/util/cell_composition_data.py
| 0.924048 | 0.683314 |
cell_composition_data.py
|
pypi
|
import numpy as np
import time
import warnings
import tensorflow as tf
import tensorflow_probability as tfp
from sccoda.util import result_classes as res
from typing import Optional, Tuple, Collection, Union, List
tfd = tfp.distributions
tfb = tfp.bijectors
class CompositionalModel:
"""
Dynamical framework for formulation and inference of Bayesian models for compositional data analysis.
This framework is used to implement scCODA's model as a subclass of this class.
Tensorflow probability then allows to run a multitude of inference algorithms on these models
without the need to specify them every time.
A `CompositionalModel` consists of the following parameters:
- `covariate_matrix`: Numpy array that specifies the independent variables (X). Generated equivalently to the covariate matrix of a linear regression.
- `data_matrix`: Dependent variable (Y). Includes the raw cell type counts for every sample.
- `cell_types`, covariate_names: Names of cell types and covariates
- `formula`: String that represents which covariates to include and how to transform them. Used analogously to the formula in R's lm function
A specific compositional model is then implemented as a child class, with the following additional parameters
specified in the constructor:
- `target_log_prob_fn`: Log-probability function of the model. For more specific information, please refer to (tensorflow probability's API)[https://www.tensorflow.org/probability/api_docs/python/tfp]
- `param_names`: Names of prior and intermediate parameters that are included in the model output. The order has to be the same as in the states_burnin output of `self.get_y_hat`
- `init_params`: Initial values for the inference method
Methods implemented by this class:
- `sampling`: General MCMC sampling that uses a transition kernel
- `get_chains_after_burnin`: Application of burn-in to MCMC sampling results
- MCMC sampling methods (`sample_hmc`, `sample_hmc_da`, `sample_nuts`)
Methods implemented by a child class:
- `get_y_hat`: Calculation of intermediate parameters for all MCMC chain states and posterior mode of the cell count matrix
"""
def __init__(
self,
covariate_matrix: np.ndarray,
data_matrix: np.ndarray,
cell_types: List[str],
covariate_names: List[str],
formula: str,
*args,
**kwargs
):
"""
Generalized Constructor of Bayesian compositional model class.
Parameters
----------
covariate_matrix
covariate matrix, size NxD
data_matrix
cell count matrix, size NxK
cell_types
Cell type names
covariate_names
Covariate names
formula
Formula (R-style)
"""
dtype = tf.float64
self.x = tf.convert_to_tensor(covariate_matrix, dtype)
# Add pseudocount if zeroes are present.
if np.count_nonzero(data_matrix) != np.size(data_matrix):
print("Zero counts encountered in data! Added a pseudocount of 0.5.")
data_matrix[data_matrix == 0] = 0.5
self.y = tf.convert_to_tensor(data_matrix, dtype)
sample_counts = np.sum(data_matrix, axis=1)
self.n_total = tf.cast(sample_counts, dtype)
self.cell_types = cell_types
self.covariate_names = covariate_names
self.formula = formula
# Get dimensions of data
self.N, self.D = self.x.shape
self.K = self.y.shape[1]
# Check input data
if self.N != self.y.shape[0]:
raise ValueError("Wrong input dimensions X[{},:] != y[{},:]".format(self.x.shape[0], self.y.shape[0]))
if self.N != len(self.n_total):
raise ValueError("Wrong input dimensions X[{},:] != n_total[{}]".format(self.x.shape[0], len(self.n_total)))
def sampling(
self,
num_results: int,
num_burnin: int,
kernel,
init_state: dict,
trace_fn,
) -> Tuple[List[any], List[any], float]:
"""
MCMC sampling process (tensorflow 2)
Parameters
----------
num_results
MCMC chain length (default 20000)
num_burnin
Number of burnin iterations (default 5000)
kernel
tensorflow MCMC kernel object
init_state
Starting parameters
trace_fn
tracing function
Returns
-------
MCMC chain states and results
states
States of MCMC chain
kernel_results
sampling meta-information
duration
Duration of MCMC sampling process
"""
# HMC sampling function
@tf.function(autograph=False)
def sample_mcmc(num_results_, num_burnin_, kernel_, current_state_, trace_fn):
return tfp.mcmc.sample_chain(
num_results=num_results_,
num_burnin_steps=num_burnin_,
kernel=kernel_,
current_state=current_state_,
trace_fn=trace_fn
)
# The actual sampling process
start = time.time()
states, kernel_results = sample_mcmc(num_results, num_burnin, kernel, init_state, trace_fn)
duration = time.time() - start
print("MCMC sampling finished. ({:.3f} sec)".format(duration))
return states, kernel_results, duration
def get_chains_after_burnin(
self,
samples: List[any],
kernel_results: List[any],
num_burnin: int,
is_nuts: bool = False
) -> Tuple[List[any], dict, float]:
"""
Application of burn-in after MCMC sampling.
Cuts the first `num_burnin` samples from all inferred variables and diagnostic statistics.
Parameters
----------
samples
all kernel states
kernel_results
Kernel meta-information. The tracked statistics depend on the sampling method.
num_burnin
number of burn-in iterations
is_nuts
Specifies whether NUTS sampling was used
Returns
-------
MCMC chain without burn-in, sampling statistics, acceptance rate
states_burnin
Kernel states without burn-in samples
stats
sampling statistics
p_accept
acceptance rate of MCMC process
"""
# Samples after burn-in
states_burnin = []
stats = {}
# Apply burn-in to MCMC results
for s in samples:
states_burnin.append(s[num_burnin:].numpy())
# Apply burn-in to sampling statistics
for k, v in kernel_results.items():
stats[k] = v[num_burnin:].numpy()
# Calculation of acceptance rate (different for NUTS sampling)
if is_nuts:
p_accept = np.mean(np.exp(kernel_results["log_accept_ratio"].numpy()))
else:
acceptances = kernel_results["is_accepted"].numpy()
# Calculate acceptance rate
p_accept = sum(acceptances) / acceptances.shape[0]
print('Acceptance rate: %0.1f%%' % (100 * p_accept))
return states_burnin, stats, p_accept
def sample_hmc(
self,
num_results: int = int(20e3),
num_burnin: int = int(5e3),
num_adapt_steps: Optional[int] = None,
num_leapfrog_steps: Optional[int] = 10,
step_size: float = 0.01,
verbose: bool = True
) -> res.CAResult:
"""
Hamiltonian Monte Carlo (HMC) sampling in tensorflow 2.
Tracked diagnostic statistics:
- `target_log_prob`: Value of the model's log-probability
- `diverging`: Marks samples as diverging (NOTE: Handle with care, the spike-and-slab prior of scCODA usually leads to many samples being flagged as diverging)
- `is_accepted`: Whether the proposed sample was accepted in the algorithm's acceptance step
- `step_size`: The step size used by the algorithm in each step
Parameters
----------
num_results
MCMC chain length (default 20000)
num_burnin
Number of burnin iterations (default 5000)
num_adapt_steps
Length of step size adaptation procedure
num_leapfrog_steps
HMC leapfrog steps (default 10)
step_size
Initial step size (default 0.01)
verbose
If true, a progress bar is printed during MCMC sampling
Returns
-------
results object
result
Compositional analysis result
"""
# HMC transition kernel
hmc_kernel = tfp.mcmc.HamiltonianMonteCarlo(
target_log_prob_fn=self.target_log_prob_fn,
step_size=step_size,
num_leapfrog_steps=num_leapfrog_steps)
hmc_kernel = tfp.mcmc.TransformedTransitionKernel(
inner_kernel=hmc_kernel, bijector=self.constraining_bijectors)
# Set default value for adaptation steps if none given
if num_adapt_steps is None:
num_adapt_steps = int(0.8 * num_burnin)
# Add step size adaptation (Andrieu, Thomas - 2008)
hmc_kernel = tfp.mcmc.SimpleStepSizeAdaptation(
inner_kernel=hmc_kernel, num_adaptation_steps=num_adapt_steps, target_accept_prob=0.75)
if verbose:
pbar = tfp.experimental.mcmc.ProgressBarReducer(num_results)
hmc_kernel = tfp.experimental.mcmc.WithReductions(hmc_kernel, pbar)
# diagnostics tracing function
def trace_fn(_, pkr):
return {
'target_log_prob': pkr.inner_results.inner_results.inner_results.accepted_results.target_log_prob,
'diverging': (pkr.inner_results.inner_results.inner_results.log_accept_ratio < -1000.),
'is_accepted': pkr.inner_results.inner_results.inner_results.is_accepted,
'step_size': pkr.inner_results.inner_results.inner_results.accepted_results.step_size,
}
else:
# diagnostics tracing function
def trace_fn(_, pkr):
return {
'target_log_prob': pkr.inner_results.inner_results.accepted_results.target_log_prob,
'diverging': (pkr.inner_results.inner_results.log_accept_ratio < -1000.),
'is_accepted': pkr.inner_results.inner_results.is_accepted,
'step_size': pkr.inner_results.inner_results.accepted_results.step_size,
}
# The actual HMC sampling process
states, kernel_results, duration = self.sampling(num_results, num_burnin,
hmc_kernel, self.init_params, trace_fn)
if verbose:
pbar.bar.close()
# apply burn-in
states_burnin, sample_stats, acc_rate = self.get_chains_after_burnin(states, kernel_results, num_burnin,
is_nuts=False)
# Calculate posterior predictive
y_hat = self.get_y_hat(states_burnin, num_results, num_burnin)
sampling_stats = {"chain_length": num_results, "num_burnin": num_burnin,
"acc_rate": acc_rate, "duration": duration, "y_hat": y_hat}
result = self.make_result(states_burnin, sample_stats, sampling_stats)
return result
def sample_hmc_da(
self,
num_results: int = int(20e3),
num_burnin: int = int(5e3),
num_adapt_steps: Optional[int] = None,
num_leapfrog_steps: Optional[int] = 10,
step_size: float = 0.01,
verbose: bool = True
) -> res.CAResult:
"""
HMC sampling with dual-averaging step size adaptation (Nesterov, 2009)
Tracked diagnostic statistics:
- `target_log_prob`: Value of the model's log-probability
- `diverging`: Marks samples as diverging (NOTE: Handle with care, the spike-and-slab prior of scCODA usually leads to many samples being flagged as diverging)
- `log_acc_ratio`: log-acceptance ratio
- `is_accepted`: Whether the proposed sample was accepted in the algorithm's acceptance step
- `step_size`: The step size used by the algorithm in each step
Parameters
----------
num_results
MCMC chain length (default 20000)
num_burnin
Number of burnin iterations (default 5000)
num_adapt_steps
Length of step size adaptation procedure
num_leapfrog_steps
HMC leapfrog steps (default 10)
step_size
Initial step size (default 0.01)
verbose
If true, a progress bar is printed during MCMC sampling
Returns
-------
result object
result
Compositional analysis result
"""
# HMC transition kernel
hmc_kernel = tfp.mcmc.HamiltonianMonteCarlo(
target_log_prob_fn=self.target_log_prob_fn,
step_size=step_size,
num_leapfrog_steps=num_leapfrog_steps)
hmc_kernel = tfp.mcmc.TransformedTransitionKernel(
inner_kernel=hmc_kernel, bijector=self.constraining_bijectors)
# Set default value for adaptation steps if none given
if num_adapt_steps is None:
num_adapt_steps = int(0.8 * num_burnin)
# Add step size adaptation
hmc_kernel = tfp.mcmc.DualAveragingStepSizeAdaptation(
inner_kernel=hmc_kernel, num_adaptation_steps=num_adapt_steps, target_accept_prob=0.75, decay_rate=0.75)
if verbose:
pbar = tfp.experimental.mcmc.ProgressBarReducer(num_results)
hmc_kernel = tfp.experimental.mcmc.WithReductions(hmc_kernel, pbar)
# tracing function
def trace_fn(_, pkr):
return {
'target_log_prob': pkr.inner_results.inner_results.inner_results.accepted_results.target_log_prob,
'diverging': (pkr.inner_results.inner_results.inner_results.log_accept_ratio < -1000.),
"log_acc_ratio": pkr.inner_results.inner_results.inner_results.log_accept_ratio,
'is_accepted': pkr.inner_results.inner_results.inner_results.is_accepted,
'step_size': tf.exp(pkr.inner_results.log_averaging_step[0]),
}
else:
# tracing function
def trace_fn(_, pkr):
return {
'target_log_prob': pkr.inner_results.inner_results.accepted_results.target_log_prob,
'diverging': (pkr.inner_results.inner_results.log_accept_ratio < -1000.),
"log_acc_ratio": pkr.inner_results.inner_results.log_accept_ratio,
'is_accepted': pkr.inner_results.inner_results.is_accepted,
'step_size': tf.exp(pkr.log_averaging_step[0]),
}
# HMC sampling
states, kernel_results, duration = self.sampling(num_results, num_burnin, hmc_kernel, self.init_params,
trace_fn)
states_burnin, sample_stats, acc_rate = self.get_chains_after_burnin(states, kernel_results, num_burnin,
is_nuts=False)
if verbose:
pbar.bar.close()
y_hat = self.get_y_hat(states_burnin, num_results, num_burnin)
sampling_stats = {"chain_length": num_results, "num_burnin": num_burnin,
"acc_rate": acc_rate, "duration": duration, "y_hat": y_hat}
result = self.make_result(states_burnin, sample_stats, sampling_stats)
return result
def sample_nuts(
self,
num_results: int = int(10e3),
num_burnin: int = int(5e3),
num_adapt_steps: Optional[int] = None,
max_tree_depth: int = 10,
step_size: float = 0.01,
verbose: float = True
) -> res.CAResult:
"""
HMC with No-U-turn (NUTS) sampling.
This method is untested and might yield different results than expected.
Tracked diagnostic statistics:
- `target_log_prob`: Value of the model's log-probability
- `leapfrogs_taken`: Number of leapfrog steps taken by the integrator
- `diverging`: Marks samples as diverging (NOTE: Handle with care, the spike-and-slab prior of scCODA usually leads to many samples being flagged as diverging)
- `energy`: HMC "Energy" value for each step
- `log_accept_ratio`: log-acceptance ratio
- `step_size`: The step size used by the algorithm in each step
- `reached_max_depth`: Whether the NUTS algorithm reached the maximum sampling depth in each step
- `is_accepted`: Whether the proposed sample was accepted in the algorithm's acceptance step
Parameters
----------
num_results
MCMC chain length (default 10000)
num_burnin
Number of burnin iterations (default 5000)
num_adapt_steps
Length of step size adaptation procedure
max_tree_depth
Maximum tree depth (default 10)
step_size
Initial step size (default 0.01)
verbose
If true, a progress bar is printed during MCMC sampling
Returns
-------
result object
result
Compositional analysis result
"""
# NUTS transition kernel
nuts_kernel = tfp.mcmc.NoUTurnSampler(
target_log_prob_fn=self.target_log_prob_fn,
step_size=tf.cast(step_size, tf.float64),
max_tree_depth=max_tree_depth)
nuts_kernel = tfp.mcmc.TransformedTransitionKernel(
inner_kernel=nuts_kernel,
bijector=self.constraining_bijectors
)
# Set default value for adaptation steps
if num_adapt_steps is None:
num_adapt_steps = int(0.8 * num_burnin)
# Step size adaptation (Nesterov, 2009)
nuts_kernel = tfp.mcmc.DualAveragingStepSizeAdaptation(
inner_kernel=nuts_kernel,
num_adaptation_steps=num_adapt_steps,
target_accept_prob=tf.cast(0.75, tf.float64),
decay_rate=0.75,
step_size_setter_fn=lambda pkr, new_step_size: pkr._replace(
inner_results=pkr.inner_results._replace(step_size=new_step_size)
),
step_size_getter_fn=lambda pkr: pkr.inner_results.step_size,
log_accept_prob_getter_fn=lambda pkr: pkr.inner_results.log_accept_ratio,
)
if verbose:
pbar = tfp.experimental.mcmc.ProgressBarReducer(num_results)
nuts_kernel = tfp.experimental.mcmc.WithReductions(nuts_kernel, pbar)
# trace function
def trace_fn(_, pkr):
return {
"target_log_prob": pkr.inner_results.inner_results.inner_results.target_log_prob,
"leapfrogs_taken": pkr.inner_results.inner_results.inner_results.leapfrogs_taken,
"diverging": pkr.inner_results.inner_results.inner_results.has_divergence,
"energy": pkr.inner_results.inner_results.inner_results.energy,
"log_accept_ratio": pkr.inner_results.inner_results.inner_results.log_accept_ratio,
"step_size": pkr.inner_results.inner_results.inner_results.step_size,
"reach_max_depth": pkr.inner_results.inner_results.inner_results.reach_max_depth,
"is_accepted": pkr.inner_results.inner_results.inner_results.is_accepted,
}
else:
# trace function
def trace_fn(_, pkr):
return {
"target_log_prob": pkr.inner_results.inner_results.target_log_prob,
"leapfrogs_taken": pkr.inner_results.inner_results.leapfrogs_taken,
"diverging": pkr.inner_results.inner_results.has_divergence,
"energy": pkr.inner_results.inner_results.energy,
"log_accept_ratio": pkr.inner_results.inner_results.log_accept_ratio,
"step_size": pkr.inner_results.inner_results.step_size,
"reach_max_depth": pkr.inner_results.inner_results.reach_max_depth,
"is_accepted": pkr.inner_results.inner_results.is_accepted,
}
# HMC sampling
states, kernel_results, duration = self.sampling(num_results, num_burnin, nuts_kernel, self.init_params, trace_fn)
states_burnin, sample_stats, acc_rate = self.get_chains_after_burnin(states, kernel_results, num_burnin,
is_nuts=True)
if verbose:
pbar.bar.close()
y_hat = self.get_y_hat(states_burnin, num_results, num_burnin)
sampling_stats = {"chain_length": num_results, "num_burnin": num_burnin,
"acc_rate": acc_rate, "duration": duration, "y_hat": y_hat}
result = self.make_result(states_burnin, sample_stats, sampling_stats)
return result
def make_result(
self,
states_burnin,
sample_stats: dict,
sampling_stats: dict
):
"""
Result object generating function. Transforms chain states to result object.
Parameters
----------
states_burnin
MCMC chain states after burn-in removal
sample_stats
Dict with information about the MCMC samples
sampling_stats
Dict with information about the sampling process
Returns
-------
result object
result
Compositional analysis result
"""
params = dict(zip(self.param_names, states_burnin))
# Result object generation process. Uses arviz's data structure.
# Get names of cell types that are not the reference
if self.reference_cell_type is not None:
cell_types_nb = self.cell_types[:self.reference_cell_type] + self.cell_types[self.reference_cell_type + 1:]
else:
cell_types_nb = self.cell_types
posterior = {var_name: [var] for var_name, var in params.items() if
"prediction" not in var_name}
if "prediction" in self.param_names:
posterior_predictive = {"prediction": [params["prediction"]]}
else:
posterior_predictive = {}
observed_data = {"y": self.y}
dims = {"alpha": ["cell_type"],
"sigma_d": ["covariate"],
"b_offset": ["covariate", "cell_type_nb"],
"ind_raw": ["covariate", "cell_type_nb"],
"ind": ["covariate", "cell_type_nb"],
"b_raw": ["covariate", "cell_type_nb"],
"beta": ["covariate", "cell_type"],
"concentration": ["sample", "cell_type"],
"prediction": ["sample", "cell_type"]
}
coords = {"cell_type": self.cell_types,
"cell_type_nb": cell_types_nb,
"covariate": self.covariate_names,
"sample": range(self.y.shape[0])
}
model_specs = {"reference": self.reference_cell_type, "formula": self.formula}
return res.CAResultConverter(posterior=posterior,
posterior_predictive=posterior_predictive,
observed_data=observed_data,
dims=dims,
sample_stats=sample_stats,
coords=coords).to_result_data(sampling_stats=sampling_stats,
model_specs=model_specs)
class scCODAModel(CompositionalModel):
"""
Statistical model for single-cell differential composition analysis with specification of a reference cell type.
This is the standard scCODA model and recommenced for all uses.
The hierarchical formulation of the model for one sample is:
.. math::
y|x &\\sim DirMult(\\phi, \\bar{y}) \\\\
\\log(\\phi) &= \\alpha + x \\beta \\\\
\\alpha_k &\\sim N(0, 5) \\quad &\\forall k \\in [K] \\\\
\\beta_{m, \\hat{k}} &= 0 &\\forall m \\in [M]\\\\
\\beta_{m, k} &= \\tau_{m, k} \\tilde{\\beta}_{m, k} \\quad &\\forall m \\in [M], k \\in \\{[K] \\smallsetminus \\hat{k}\\} \\\\
\\tau_{m, k} &= \\frac{\\exp(t_{m, k})}{1+ \\exp(t_{m, k})} \\quad &\\forall m \\in [M], k \\in \\{[K] \\smallsetminus \\hat{k}\\} \\\\
\\frac{t_{m, k}}{50} &\\sim N(0, 1) \\quad &\\forall m \\in [M], k \\in \\{[K] \\smallsetminus \\hat{k}\\} \\\\
\\tilde{\\beta}_{m, k} &= \\sigma_m^2 \\cdot \\gamma_{m, k} \\quad &\\forall m \\in [M], k \\in \\{[K] \\smallsetminus \\hat{k}\\} \\\\
\\sigma_m^2 &\\sim HC(0, 1) \\quad &\\forall m \\in [M] \\\\
\\gamma_{m, k} &\\sim N(0,1) \\quad &\\forall m \\in [M], k \\in \\{[K] \\smallsetminus \\hat{k}\\} \\\\
with y being the cell counts and x the covariates.
For further information, see `scCODA: A Bayesian model for compositional single-cell data analysis`
(Büttner, Ostner et al., 2020)
"""
def __init__(
self,
reference_cell_type: int,
*args,
**kwargs):
"""
Constructor of model class. Defines model structure, log-probability function, parameter names,
and MCMC starting values.
Parameters
----------
reference_cell_type
Index of reference cell type (column in count data matrix)
args
arguments passed to top-level class
kwargs
arguments passed to top-level class
"""
super(self.__class__, self).__init__(*args, **kwargs)
self.reference_cell_type = reference_cell_type
dtype = tf.float64
# All parameters that are returned for analysis
self.param_names = ["sigma_d", "b_offset", "ind_raw", "alpha",
"ind", "b_raw", "beta", "concentration", "prediction"]
alpha_size = [self.K]
beta_size = [self.D, self.K]
sigma_size = [self.D, 1]
beta_nobl_size = [self.D, self.K-1]
Root = tfd.JointDistributionCoroutine.Root
def model():
sigma_d = yield Root(tfd.Independent(
tfd.HalfCauchy(tf.zeros(sigma_size, dtype=dtype),
tf.ones(sigma_size, dtype=dtype),
name="sigma_d"),
reinterpreted_batch_ndims=2))
b_offset = yield Root(tfd.Independent(
tfd.Normal(
loc=tf.zeros(beta_nobl_size, dtype=dtype),
scale=tf.ones(beta_nobl_size, dtype=dtype),
name="b_offset"),
reinterpreted_batch_ndims=2))
# Spike-and-slab
ind_raw = yield Root(tfd.Independent(
tfd.Normal(
loc=tf.zeros(shape=beta_nobl_size, dtype=dtype),
scale=tf.ones(shape=beta_nobl_size, dtype=dtype),
name="ind_raw"),
reinterpreted_batch_ndims=2))
ind_scaled = ind_raw * 50
ind = tf.exp(ind_scaled) / (1 + tf.exp(ind_scaled))
b_raw = sigma_d * b_offset
beta = ind * b_raw
# Include slope 0 for reference cell type
beta = tf.concat(axis=1, values=[beta[:, :reference_cell_type],
tf.zeros(shape=[self.D, 1], dtype=dtype),
beta[:, reference_cell_type:]])
alpha = yield Root(tfd.Independent(
tfd.Normal(
loc=tf.zeros(alpha_size, dtype=dtype),
scale=tf.ones(alpha_size, dtype=dtype) * 5,
name="alpha"),
reinterpreted_batch_ndims=1))
concentrations = tf.exp(alpha + tf.matmul(self.x, beta))
# Cell count prediction via DirMult
predictions = yield Root(tfd.Independent(
tfd.DirichletMultinomial(
total_count=tf.cast(self.n_total, dtype),
concentration=concentrations,
name="predictions"),
reinterpreted_batch_ndims=1))
self.model_struct = tfd.JointDistributionCoroutine(model)
# Joint posterior distribution
@tf.function(experimental_compile=True)
def target_log_prob_fn(*argsl):
return self.model_struct.log_prob(list(argsl) + [tf.cast(self.y, dtype)])
self.target_log_prob_fn = target_log_prob_fn
# MCMC starting values
self.init_params = [
tf.ones(sigma_size, name="init_sigma_d", dtype=dtype),
tf.random.normal(beta_nobl_size, 0, 1, name='init_b_offset', dtype=dtype),
tf.zeros(beta_nobl_size, name='init_ind_raw', dtype=dtype),
tf.random.normal(alpha_size, 0, 1, name='init_alpha', dtype=dtype)
]
self.constraining_bijectors = [tfb.Identity() for x in range(len(self.init_params))]
# Calculate predicted cell counts (for analysis purposes)
def get_y_hat(
self,
states_burnin: List[any],
num_results: int,
num_burnin: int
) -> np.ndarray:
"""
Calculate posterior mode of cell counts (for analysis purposes) and add intermediate parameters
that are no priors to MCMC results.
Parameters
----------
states_burnin
MCMC chain without burn-in samples
num_results
Chain length (with burn-in)
num_burnin
Number of burn-in samples
Returns
-------
posterior mode
y_mean
posterior mode of cell counts
"""
chain_size_y = [num_results - num_burnin, self.N, self.K]
chain_size_beta = [num_results - num_burnin, self.D, self.K]
alphas = states_burnin[3]
alphas_final = alphas.mean(axis=0)
ind_raw = states_burnin[2] * 50
sigma_d = states_burnin[0]
b_offset = states_burnin[1]
ind_ = np.exp(ind_raw) / (1 + np.exp(ind_raw))
b_raw_ = np.einsum("...jk, ...jl->...jk", b_offset, sigma_d)
beta_temp = np.einsum("..., ...", ind_, b_raw_)
beta_ = np.zeros(chain_size_beta)
for i in range(num_results - num_burnin):
beta_[i] = np.concatenate([beta_temp[i, :, :self.reference_cell_type],
np.zeros(shape=[self.D, 1], dtype=np.float64),
beta_temp[i, :, self.reference_cell_type:]], axis=1)
conc_ = np.exp(np.einsum("jk, ...kl->...jl", self.x, beta_)
+ alphas.reshape((num_results - num_burnin, 1, self.K)))
predictions_ = np.zeros(chain_size_y)
for i in range(num_results - num_burnin):
pred = tfd.DirichletMultinomial(self.n_total, conc_[i, :, :]).mean().numpy()
predictions_[i, :, :] = pred
betas_final = beta_.mean(axis=0)
states_burnin.append(ind_)
states_burnin.append(b_raw_)
states_burnin.append(beta_)
states_burnin.append(conc_)
states_burnin.append(predictions_)
concentration = np.exp(np.matmul(self.x, betas_final) + alphas_final).astype(np.float64)
y_mean = concentration / np.sum(concentration, axis=1, keepdims=True) * self.n_total.numpy()[:, np.newaxis]
return y_mean
|
/scCODA-0.1.9.tar.gz/scCODA-0.1.9/sccoda/model/scCODA_model.py
| 0.943777 | 0.72526 |
scCODA_model.py
|
pypi
|
# How to use scConnect to build and analyze a connectivity graph
scConnect integrate into a Scanpy analysis pipeline by utilizing the AnnData objects. This tutorial will not cover usage of scanpy, but tutorials for this can be found [here](https://scanpy.readthedocs.io/en/latest/tutorials.html).
We will cover four aspects:
* Gene calling
* Inference of interactions
* Construction of multi-directional graph
* Analysis of graph
However, before we begin, we will nend a dataset to work on. We will investigate the mouse brain dataset from [Saunder et al.](https://www.sciencedirect.com/science/article/pii/S0092867418309553). The original dataset contains hundreds of thousands of cells, but we will investigate meta cells (summation of all reads of cells from the same cell type) which drastically decrease the size of the dataset.
All meta cells has two levels of annotations. the First level relates to the tissue from which the cell originates. These are:
* Hippocampus (HC)
* Thalamus (TH)
* Frontal cortex (FC)
* Striatum (STR)
* Globus Pallidus and nucleus basalis (GP)
* Entopeducular nucleus and subthalamic nucleus (ENT)
* Substantia nigra and ventral tegmental area (SN)
* Cerebellum (CB)
* Posterior cortex (PC)
the second level is the cell type annotation, such as *Fast-spiking interneuron, Pvalb+*
# loading the dataset
Lets begin by importing all the packages we will need.
```
import pandas as pd
import scanpy as sc
import scConnect as cn
import matplotlib
import matplotlib.pyplot as plt
```
We read in the meta cells using `sc.read_csv()` and add the metadata to adata.obs.
```
adata = sc.read_csv("data/metacells.BrainCellAtlas_Saunders_version_2018.04.01.csv").T
meta = pd.read_excel("data/annotation.BrainCellAtlas_Saunders_version_2018.04.01.xlsx", index_col="tissue_subcluster")
adata.obs = meta
adata.obs.head(10)
```
Notice that we have cells of many different types. We will focus on neurons in our analysis, and hence we will only keep these meta cells.
```
adata = adata[adata.obs["class"] == "NEURON"]
adata
```
In many pipelines, we whould now normalize and logaritmize the read values to better visualize differences in gene expression. we will do the same here.
*Note that scConnect will later transform all values back to reads. If we were to perform some more advanced transformations, we can specifically discribe this to correcly transform the read values.*
```
sc.pp.normalize_total(adata, exclude_highly_expressed=True)
sc.pp.log1p(adata)
```
We now have everything that we need to proceed with scConnect:
* AnnData object
* Cell type annotations in adata.obs
scConnect already come packaged with a database for the mouse genome, but if you want to analyse any other species you can set up a database using `cn.database.setup_database()` and provide the species name: *mmusculus* for Mouse, *hsapiens* for human etc.
You can further select which receptor types that you want to include in the database.
* enzyme
* transporter
* gpcr
* catalytic_receptor
* other_protein
* vgic
* lgic
* other_ic
* nhr
Here we select receptors that are present at the synapses of neurons.
Note: In future verions, receptor type selection will be passed to `cn.connect.receptors()` instead, and all databases will contain the full set of receptors.
You can read more about receptor types [here](https://www.guidetopharmacology.org/targets.jsp).
Guide to Pharmacology (GTF) update their database regularly, and we include the latest database version available for each scConnect release. If you would like to update scConnect, and still use an older GTP database version, you can set this using `cn.database.version`.
**Note:** You will only have to run this once, as the files are changed in the package. If you run another pipeline with other database setting for the same species, you will have to rerun this database setup.
```
# set correct database ONLY RUN WHEN DATABASE HAS CHANGED
cn.database.version = "2019-5"
#cn.database.setup_database("mmusculus", receptor_types=["lgic", "vgic", "gpcr", "catalytic_receptor"])
```
# Gene calling
The gene/protein correlation is quite weak at a single cell level, however, at a cell type level (grouping cells by cell type) the correlation is much better. During gene celling, we achieve this by grouping all cells (in our case meta cells) by some cell annotation.
For our purposes we will group all cells from each brain regoin (*tissue*) and assess the mean gene expression. This will produce a new matrix with *tissues* as columns and genes as rows.
At this stage, we will also describe how the counts/reads have been transformer in order to transform them back to counts/reads. We do this by providing `"log1p"` to the transformation argument. This argument also accepts a function that would transform the values correcly.
```
adata_tissue = cn.genecall.meanExpression(adata, groupby="tissue", normalization=False, use_raw=False, transformation="log1p")
adata_tissue.uns["gene_call"].head(10)
```
Next step is to connect gene expression to ligands and reecptors. We do this using `cn.connect.ligands()` and `cn.connect.receptors()`. The results are stored under `adata.uns["receptors"]` and `adata.und["ligands"]` respectivly.
```
adata_tissue = cn.connect.ligands(adata_tissue)
adata_tissue = cn.connect.receptors(adata_tissue)
pd.DataFrame(adata_tissue.uns["ligands"]).head(10)
```
# Constructing the graph
A graph is built up of two parts; edges and nodes. An edge describe a relationship between two nodes, and the edge can be directional, meaning that the described edge only is true in one direction. Here, we describe interactions (edges) between two tissues (nodes), and we base this by infering interactions between two tissue if they have a matching ligand-receptor pair, that we know can interact with each other. This information is fetched from GTF and was included when we ran the database setup earlier.
## Detecting edges
We can detect eges between two AnnData object that has ligands and receptor annotation in them. In our case, we whould like to detect edges between the tissues of ust one AnnData object. We can do this by passing the same adata as emmitor and as target to `cn.connect.interactions()`. This produce a list of all interaction between all tissues.
## Collecting metadata about the tissues
using `cn.connect.nodes()` we can collect all metadata about the different tissues, as we want to include this in our graph later on
```
edges = cn.connect.interactions(adata_tissue, adata_tissue, self_reference=True)
nodes = cn.connect.nodes(adata_tissue)
```
We can construct the graph by passing in the edge list and the node list to `cn.graph.build_graph()`. The result is a `networkX.MultiDiGraph`.
```
G_tissue = cn.graph.build_graph(edges, nodes)
```
# Analysis of the graph
The data in the graph is complex, and several types of analysis might be suitable for different purposes. scConnect can run a Dash web application for interactive exploratory analysis of the graph, and it is recommended to initally use this method to get a feeling of the graph.
The web app is run by passing the graph object to `cn.app.graph()`. Click on the link to open the application.
**note:** If no link is shown, run the cell twise.
```
from importlib import reload
cn.app = reload(cn.app)
cn.app.graph(G_tissue, mode=None, debug=False)
```
## web app
If you are statically viewing this notebook, here is a short description of the web app's functionallity.
### Network graph
In the main network graph, you can select either a node or an edge. Here we have selected the SN population.

### Connectivity graph
Focusing on the SN population we will get a connectivity graph with all incomming and outgoing interactions the the SN population. Note that you can filter interactions based on scores so to only detect the strongest (score), or most specific (weighted score). Hovering over the interactions provide you with further details.

### Ligands and receptors
You can also investigate the ligand and receptors expressed by the population. Note that the plot is dynamic, and you can zoom in and pan around. Further more, you can search for specific receptors or ligands.

### Interactions
Selecting an edge in the main network graph provides a list of all interactions between the source and target node. This table can be sorted on score and weighted score and provide information about the ligand, receptor and receptor family in the interaction.

## Splitting the graph on interaction
By splitting the graph on interactions, we can assess the contribution of a specific ligand and receptor pair to the graph. This is especially usefull if you are interested in something perticular. We split the graph with `cn.graph.split_graph()` which returns a dictionary with interactions as keys and `networkX.DiGraph` as values.
```
Gs_tissue = cn.graph.split_graph(G_tissue)
```
We can visualize a `networkX.DiGraph` using the `cn.graph.plot_adjacency_matrix()`, and by utilizing the built in interaction module of jupyter notebooks, we can interactivly browse the different interacitons.
```
import ipywidgets as widgets
options = list(Gs_tissue.keys())
options.sort()
def f(interaction):
return cn.graph.plot_adjacency_matrix(Gs_tissue[interaction], weight="log_score", width=400, height=400, fontsize=15, fontscale=1.0)
widgets.interact(f, interaction=widgets.Dropdown(options=options, index=0))
```
## Interaction differences
Sometimes you would like to compare the interactions that two populations are involved in. This could be between two treatment groups to assess how the connectivity changed. For our purposes, we will compare the interactions made by pariental cortex (PC) and frontal cordex (FC).
Using the threshold of 2, we will only plot interactions that is 2 times stronger in any of the populations.
Red values are stronger in node a (PC) and blue values are stronger in node b (FC). Color bar is log10(ratio)
**Note:** *Receptor familiy is plotted for each row, so this function prints out the receptor families used in order, and a corresponding color bar. This is for publishing reasons, as you might want to build this figure with these components seperatly. This might change in furure releases to produce publishable images direcly.*
```
cn.graph.compare_interactions_plot(G_tissue, node_a="PC", node_b="FC", th=2, figsize_i=(10, 7), figsize_o=(10, 15))
```
## Manual access to data
Data is accessable directly from the MultiDiGraph and from the AnnData objects them self. Future releases will contain functions to simplify plotting of this information, such as the selected receptor and ligand plots bellow where the bar colors match the web app node colors.
```
import numpy as np
import numpy as np
import networkx as nx
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame(adata_tissue.uns["receptors"]).loc[["D1 receptor"]]
nodes = pd.Categorical(G_tissue.nodes())
# make a list of RGBA tuples, one for each node
colors = plt.cm.tab20c(nodes.codes/len(nodes.codes), bytes=False)
# zip node to color
color_map_nodes = dict(zip(nodes, colors))
f = sns.barplot(data=np.log10(df+1), palette=color_map_nodes)
f.set_xlabel("Tissue")
f.set_ylabel("Receptor score, log10(score)")
f.set_aspect(8, "box")
plt.xticks(rotation=90)
import numpy as np
import numpy as np
import networkx as nx
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame(adata_tissue.uns["receptors"]).loc[["D2 receptor"]]
nodes = pd.Categorical(G_tissue.nodes())
# make a list of RGBA tuples, one for each node
colors = plt.cm.tab20c(nodes.codes/len(nodes.codes), bytes=False)
# zip node to color
color_map_nodes = dict(zip(nodes, colors))
f = sns.barplot(data=np.log10(df+1), palette=color_map_nodes)
f.set_xlabel("Tissue")
f.set_ylabel("Receptor score, log10(score)")
f.set_aspect(20, "box")
plt.xticks(rotation=90)
df = pd.DataFrame(adata_tissue.uns["ligands"]).loc[["dopamine"]]
np.log10(df+1)
import numpy as np
import networkx as nx
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame(adata_tissue.uns["ligands"]).loc[["dopamine"]]
np.log10(df+1)
nodes = pd.Categorical(G_tissue.nodes())
# make a list of RGBA tuples, one for each node
colors = plt.cm.tab20c(nodes.codes/len(nodes.codes), bytes=False)
# zip node to color
color_map_nodes = dict(zip(nodes, colors))
f = sns.barplot(data=np.log10(df+1), palette=color_map_nodes)
f.set_xlabel("Tissue")
f.set_ylabel("ligand score, log10(score)")
f.set_aspect(5, "box")
plt.xticks(rotation=90)
```
# Further help
I hope this tutorial introduced you the the posibilities with scConnect. For further information please visit the projects [github](https://github.com/JonETJakobsson/scConnect) and [documentation](https://scconnect.readthedocs.io/en/latest/).
```
```
|
/scConnect-1.0.2.tar.gz/scConnect-1.0.2/tutorial/Connecting brain regions.ipynb
| 0.444565 | 0.986954 |
Connecting brain regions.ipynb
|
pypi
|
=========
Work flow
=========
+++++++++++++++++++++
Building the database
+++++++++++++++++++++
The current version of scConnect have version 2019-5 of the latest ligand, receptor and interaction data from `guide to pharmacology`__ allready compiled.
Should you find the need to change to an older database version, download and replace the csv files under data/GTP_tables/
and run :py:func:`scConnect.database.setup_database`. If you have allready built this database, set the version using :py:const:`scConnect.database.version`
__ https://www.guidetopharmacology.org/download.jsp
+++++++++++++++++++++++++++++++++++++++
Working with AnnData objects and Scanpy
+++++++++++++++++++++++++++++++++++++++
scConnect rely heavily on the workflow and data structures included in the scRNA-seq package `scanpy`__.
Please refer to their documentation for working with single cell data and how to detect cell populations.
__ https://scanpy.readthedocs.io/en/stable/
To run the functions in this package,
you will need an AnnData object with any kind of cell population groups under adata.obs.
+++++++++++++++
Make gene calls
+++++++++++++++
In order to link gene expression to precence or absence of ligands and receptors for cell populations,
we must decide how to measure gene expression on a cell population basis.
There are several algorithms to do this:
**Using threshold parameters**
.. autosummary::
scConnect.genecall.betabinomialTrinarization
scConnect.genecall.meanThreshold
scConnect.genecall.medianThreshold
**Non-parametric**
.. autosummary::
scConnect.genecall.percentExpression
scConnect.genecall.meanExpression
Calculating ligand scores for peptide ligands are staight forward, as this can be equal to the gene call.
Calculating molecular ligands involves more genes, as synthesis, vesicle transporters and reuptake transporters are all nesesary
to produce and transport the ligand. Further more, some genes cannot be expressed as these whould convert the ligand
to another ligand, these we call exclusion genes.
.. math:: Ligand promoting factor (p) = geom(max(transporters), geom(synthesis), max(reuptake))
.. math:: exclusion facor (e) = (p - Exclusion)/p
.. math:: molecular ligand score = p * e
?????????????????????????????????????????
Optimizing threshold settings for neurons
?????????????????????????????????????????
One common feature of neuronal tissue is that it contain cells that are either glutamatergic or gabaergic,
but they do rarle express both neurotransmitters. The neurons hence *segregate* into excitatory or inhibitory phenotypes.
This feature can be used to find the lowest threshold that replicates this biological feature,
and can be used as a guide when selecting a threshold.
The effect on this segregation can be assesed for all thresholds using :py:func:`scConnect.genecall.optimize_segregation` (only testing betabinomial trinarization).
Select the lowest threshold value producing the highest segregation score and run :py:func:`scConnect.genecall.betabinomialTrinarization` with this threshold.
Visualize the segregation using :py:func:`scConnect.genecall.plot_segregation`.
++++++++++++++++++++++++
Deciding what to connect
++++++++++++++++++++++++
After running the gene call algorithm of your choice, it is time to link the gene calls to ligands and receptors.
To do this, run the following functions on all datasets that you want to investigate connectivity between.
.. autosummary::
scConnect.connect.ligands
scConnect.connect.receptors
Interactions between cell populations are found using :py:func:`scConnect.connect.interactions`.
It expects two datasets, one **emitter** and one **target** dataset.
If you are interested in the interactions between cell populations in just one dataset,
supply this dataset as both emitter and target.
The end goal is to build a graph representing all the interactions that occur between our cell populations.
To build a graph, we need a list of all interactions, here named an edge list,
and also information about the cell types, here named node list.
:py:func:`scConnect.connect.interactions` returns a python list containing edge information,
and several edge lists can be added together using the `+` operator.
.. warning::
Cell population names has to be unique between different datasets and will
otherwise be considered the same population in the graph.
It is usefull to export information about ligand and receptor expression for cell populations
from all datasets before building a connectivity graph. This is done by supplying a list of all datasets to
:py:func:`scConnect.connect.nodes`. This will provide a list of all nodes with relevant metadata.
++++++++++++++++++
Building the graph
++++++++++++++++++
The graph is constructed using :py:func:`scConnect.graph.build_graph` with the edge list and node list as arguments.
When the graph is constructed some edge metrics are automatically calculated:
.. autosummary::
scConnect.graph.loyalty
scConnect.graph.promiscuity
scConnect.graph.weighted_score
The graph is a networkX multi directional graph, with each ligand receptor pair constituting an edge between two nodes.
For further information on how to work with the graph, please refer to `networkX documentation`__
__ https://networkx.github.io/documentation/stable/
+++++++++++++++++++
Analysing the graph
+++++++++++++++++++
to be continued..
|
/scConnect-1.0.2.tar.gz/scConnect-1.0.2/docs/source/Tutorials.rst
| 0.857127 | 0.65466 |
Tutorials.rst
|
pypi
|
# scETM: single-cell Embedded Topic Model
A generative topic model that facilitates integrative analysis of large-scale single-cell RNA sequencing data.
The full description of scETM and its application on published single cell RNA-seq datasets are available [here](https://www.biorxiv.org/content/10.1101/2021.01.13.426593v1).
This repository includes detailed instructions for installation and requirements, demos, and scripts used for the benchmarking of 7 other state-of-art methods.
## Contents ##
- [scETM: single-cell Embedded Topic Model](#scetm-single-cell-embedded-topic-model)
- [Contents](#contents)
- [1 Model Overview](#1-model-overview)
- [2 Installation](#2-installation)
- [3 Usage](#3-usage)
- [Data format](#data-format)
- [A taste of scETM](#a-taste-of-scetm)
- [p-scETM](#p-scetm)
- [Transfer learning](#transfer-learning)
- [Tensorboard Integration](#tensorboard-integration)
- [4 Benchmarking](#4-benchmarking)
## 1 Model Overview

**(a)** Probabilistic graphical model of scETM. We model the scRNA-profile read count matrix y<sub>d,g</sub> in cell d and gene g across S subjects or studies by a multinomial distribution with the rate parameterized by cell topic mixture θ, topic embedding α, gene embedding ρ, and batch effects λ. **(b)** Matrix factorization view of scETM. **(c)** Encoder architecture for inferring the cell topic mixture θ.
## 2 Installation
Python version: 3.7+
scETM is included in PyPI, so you can install it by
```bash
pip install scETM
```
To enable GPU computing (which significantly boosts the performance), please install [PyTorch](https://pytorch.org/) with GPU support **before** installing scETM.
## 3 Usage
**A step-by-step scETM tutorial can be found in [here](/notebooks/scETM%20introductory%20tutorial.ipynb).**
### Data format
scETM requires a cells-by-genes matrix `adata` as input, in the format of an AnnData object. Detailed description about AnnData can be found [here](https://anndata.readthedocs.io/en/latest/).
By default, scETM looks for batch information in the 'batch_indices' column of the `adata.obs` DataFrame, and cell type identity in the 'cell_types' column. If your data stores the batch and cell type information in different columns, pass them to the `batch_col` and `cell_type_col` arguments, respectively, when calling scETM functions.
### A taste of scETM
```python
from scETM import scETM, UnsupervisedTrainer, evaluate
import anndata
# Prepare the source dataset, Mouse Pancreas
mp = anndata.read_h5ad("MousePancreas.h5ad")
# Initialize model
model = scETM(mp.n_vars, mp.obs.batch_indices.nunique(), enable_batch_bias=True)
# The trainer object will set up the random seed, optimizer, training and evaluation loop, checkpointing and logging.
trainer = UnsupervisedTrainer(model, mp, train_instance_name="MP", ckpt_dir="../results")
# Train the model on adata for 12000 epochs, and evaluate every 1000 epochs. Use 4 threads to sample minibatches.
trainer.train(n_epochs=12000, eval_every=1000, n_samplers=4)
# Obtain scETM cell, gene and topic embeddings. Unnormalized cell embeddings will be stored at mp.obsm['delta'], normalized cell embeddings at mp.obsm['theta'], gene embeddings at mp.varm['rho'], topic embeddings at mp.uns['alpha'].
model.get_all_embeddings_and_nll(mp)
# Evaluate the model and save the embedding plot
evaluate(mp, embedding_key="delta", plot_fname="scETM_MP", plot_dir="figures/scETM_MP")
```
### p-scETM
p-scETM is a variant of scETM where part or all of the the gene embedding matrix ρ is fixed to a pathways-by-genes matrix, which can be downloaded from the [pathDIP4 pathway database](http://ophid.utoronto.ca/pathDIP/Download.jsp). We only keep pathways that contain more than 5 genes.
If it is desired to fix the gene embedding matrix ρ during training, let trainable_gene_emb_dim be zero. In this case, the gene set used to train the model would be the intersection of the genes in the scRNA-seq data and the genes in the gene-by-pathway matrix. Otherwise, if trainable_gene_emb_dim is set to a positive value, all the genes in the scRNA-seq data would be kept.
### Transfer learning
```python
from scETM import scETM, UnsupervisedTrainer, prepare_for_transfer
import anndata
# Prepare the source dataset, Mouse Pancreas
mp = anndata.read_h5ad("MousePancreas.h5ad")
# Initialize model
model = scETM(mp.n_vars, mp.obs.batch_indices.nunique(), enable_batch_bias=True)
# The trainer object will set up the random seed, optimizer, training and evaluation loop, checkpointing and logging.
trainer = UnsupervisedTrainer(model, mp, train_instance_name="MP", ckpt_dir="../results")
# Train the model on adata for 12000 epochs, and evaluate every 1000 epochs. Use 4 threads to sample minibatches.
trainer.train(n_epochs=12000, eval_every=1000, n_samplers=4)
# Load the target dataset, Human Pancreas
hp = anndata.read_h5ad('HumanPancreas.h5ad')
# Align the source dataset's gene names (which are mouse genes) to the target dataset (which are human genes)
mp_genes = mp.var_names.str.upper()
mp_genes.drop_duplicates(inplace=True)
# Generate a new model and a modified dataset from the previously trained model and the mp_genes
model, hp = prepare_for_transfer(model, hp, mp_genes,
keep_tgt_unique_genes=True, # Keep target-unique genes in the model and the target dataset
fix_shared_genes=True # Fix parameters related to shared genes in the model
)
# Instantiate another trainer to fine-tune the model
trainer = UnsupervisedTrainer(model, hp, train_instance_name="HP_all_fix", ckpt_dir="../results", init_lr=5e-4)
trainer.train(n_epochs=800, eval_every=200)
```
### Tensorboard Integration
If a Tensorboard SummaryWriter is passed to the `writer` argument of the `UnsupervisedTrainer.train` method, the package will store.
## 4 Benchmarking
The commands used for running [Harmony](https://github.com/immunogenomics/harmony), [Scanorama](https://github.com/brianhie/scanorama), [Seurat](https://satijalab.org/seurat/), [scVAE-GM](https://github.com/scvae/scvae), [scVI](https://github.com/YosefLab/scvi-tools), [LIGER](https://github.com/welch-lab/liger), [scVI-LD](https://www.biorxiv.org/content/10.1101/737601v1.full.pdf) are available in the [scripts](/scripts) folder.
|
/scETM-0.5.1a0.tar.gz/scETM-0.5.1a0/README.md
| 0.900426 | 0.960025 |
README.md
|
pypi
|
import numpy as np
import torch
from sklearn.manifold import TSNE
import torch.nn as nn
class tSNE(nn.Module):
def __init__(self, data, n_components=2, *, perplexity=30.0, early_exaggeration=12.0,
learning_rate=200.0, n_iter=1000, n_iter_without_progress=300, min_grad_norm=1e-07,
metric='euclidean', init='random', verbose=0, random_state=None,
method='barnes_hut', angle=0.5, n_jobs=None, square_distances='legacy'):
self.data = data.numpy()
self.perplexity = perplexity
self.n_components = n_components
self.early_exaggeration = early_exaggeration
self.n_iter = n_iter
self.learning_rate = learning_rate
self.n_iter_without_progress = n_iter_without_progress
self.min_grad_norm = min_grad_norm
self.metric = metric
self.init = init
self.verbose = verbose
self.random_state = random_state
self.method = method
self.angle = angle
self.n_jobs = n_jobs
self.square_distances = square_distances
def forward(self):
self.reducer = TSNE(perplexity=self.perplexity,
n_components=self.n_components,
early_exaggeration=self.early_exaggeration,
n_iter=self.n_iter,
learning_rate=self.learning_rate,
n_iter_without_progress=self.n_iter_without_progress,
min_grad_norm=self.min_grad_norm,
metric=self.metric,
init=self.init,
verbose=self.verbose,
random_state=self.random_state,
method=self.method,
angle=self.angle,
n_jobs=self.n_jobs,
square_distances=self.square_distances)
self.Y = self.reducer.fit_transform(self.data)
return self.Y
|
/Dim_reduction/TSNE.py
| 0.909594 | 0.240412 |
TSNE.py
|
pypi
|
import warnings
import itertools
import numpy as np
import pandas as pd
import statsmodels.api as sm
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import StandardScaler
from math import sqrt
import torch
import torch.nn as nn
import numpy as np
from tqdm import tqdm
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torch.optim import Adam
from torch.nn import init
from scFlash.utils.modules import scTask
class Basic():
def __init__(self):
pass
def initialize_weights(self,m): #add this to utils file
if (isinstance(m, nn.Linear) or isinstance(m, nn.Conv1d)):
init.uniform_(m.weight.data,a=0.0,b=1.0)
#init.xavier_uniform_(m.weight.data)
def Layer(self,i, o, activation=None, p=0., bias=True):
ll=nn.Linear(i, o, bias=bias)
self.initialize_weights(ll)
activation = activation.upper() if activation is not None else activation
model = [ll]
if activation == 'SELU':
model += [nn.SELU(inplace=True)]
elif activation == 'RELU':
model += [nn.ReLU(inplace=True)]
elif activation == 'LeakyReLU'.upper():
model += [nn.LeakyReLU(inplace=True)]
elif activation == 'Sigmoid'.upper():
model += [nn.Sigmoid()]
elif activation == 'Tanh'.upper():
model += [nn.Tanh()]
elif type(activation) is str:
raise ValueError('{} activation not implemented.'.format(activation))
if p > 0.:
model += [nn.Dropout(p)]
return nn.Sequential(*model)
class Encoder(nn.Module):
"""Encoder network for dimensionality reduction to latent space"""
def __init__(self, input_size, output_size=1, hidden_layer_depth=5,hidden_size=1024, activation='Sigmoid', dropout_rate=0.):
super(Encoder, self).__init__()
basic=Basic()
self.hidden_size = hidden_size
self.input_size = input_size
self.output_size = output_size
self.activation=activation
self.input_layer = basic.Layer(input_size, hidden_size,activation=activation,p=dropout_rate)
net = [basic.Layer(hidden_size, hidden_size, activation='RELU',p=dropout_rate) for _ in range(hidden_layer_depth-1)]
net.append(basic.Layer(hidden_size, hidden_size, activation='Sigmoid',p=dropout_rate))
self.hidden_network = nn.Sequential(*net)
self.output_layer = basic.Layer(hidden_size, output_size,activation='Sigmoid')
def forward(self, x):
out = self.input_layer(x)
out = self.hidden_network(out)
out = self.output_layer(out)
return out
class Lambda(nn.Module):
"""Application of Gaussian noise to the latent space"""
def __init__(self, i=1, o=1, scale=1E-3):
super(Lambda, self).__init__()
self.scale = scale
self.z_mean = nn.Linear(i, o)
self.z_log_var = nn.Linear(i, o)
def forward(self, x):
self.mu = self.z_mean(x)
self.log_v = self.z_log_var(x)
eps = self.scale * Variable(torch.randn(*self.log_v.size())).type_as(self.log_v)
return self.mu + torch.exp(self.log_v / 2.) * eps
class Decoder(nn.Module):
"""Decoder network for reconstruction from latent space"""
def __init__(self, output_size, input_size=1, hidden_layer_depth=5,
hidden_size=1024, activation='Sigmoid', dropout_rate=0.):
super(Decoder, self).__init__()
basic=Basic()
self.input_layer = basic.Layer(input_size, input_size, activation='RELU')
net = [basic.Layer(input_size, hidden_size,activation='RELU', p=dropout_rate)]
net += [basic.Layer(hidden_size, hidden_size, activation='RELU',p=dropout_rate) for _ in range(hidden_layer_depth-1)]
net += [basic.Layer(hidden_size, hidden_size, activation='Sigmoid',p=dropout_rate) ]
self.hidden_network = nn.Sequential(*net)
self.output_layer = basic.Layer(hidden_size, output_size,activation='Sigmoid')
def forward(self, x):
out = self.input_layer(x)
out = self.hidden_network(out)
out = self.output_layer(out)
return out
"""VAE DEFINITION"""
class VAE(nn.Module):
def __init__(self, input_dim, encoder_size=1, batch_size=100,
hidden_layer_depth=3, hidden_size=2048, scale=1E-3,
dropout_rate=0.,
activation='Sigmoid',
verbose=True,
**kwargs):
super(VAE, self).__init__()
basic = Basic()
input_size = input_dim
self.encoder = Encoder(input_size, output_size=encoder_size,
hidden_layer_depth=hidden_layer_depth,
hidden_size=hidden_size, activation=activation,dropout_rate=dropout_rate)
self.lmbd = Lambda(encoder_size, encoder_size, scale=scale)
self.decoder = Decoder(input_size, input_size=encoder_size,
hidden_layer_depth=hidden_layer_depth,
hidden_size=hidden_size, activation=activation,
dropout_rate=dropout_rate)
self.verbose = verbose
self.input_size = input_size
self.encoder_size = encoder_size
self.apply(basic.initialize_weights)
#self.optimizer = optim.Adam(self.parameters(), lr=lr)
self.is_fit = False
def vae_loss(self, x_decoded_mean, x):
x_decoded_mean = x_decoded_mean[0]
kl_loss=nn.functional.kl_div(x, x_decoded_mean, size_average=None, reduce=None, reduction='batchmean', log_target=False)
loss = nn.functional.binary_cross_entropy(nn.functional.softmax(x_decoded_mean,-1), nn.functional.softmax(x,-1), reduction='sum') # LOSS FUNCTION REQUIRES INPUT IN THE RANGE OF 0 TO 1
#loss = nn.functional.binary_cross_entropy(x_decoded_mean,x, reduction='sum')
return loss+kl_loss
def get_loss(self):
return {'vae_loss': self.vae_loss}
def forward(self, x):
u = self.encoder(x)
u_p = self.lmbd(u)
out = self.decoder(u_p)
return out , u
def _func(self, x):
return np.concatenate([i[0] for i in x])
|
/Dim_reduction/VAE.py
| 0.841044 | 0.368974 |
VAE.py
|
pypi
|
# scHiCTools
### Summary
A computational toolbox for analyzing single cell Hi-C (high-throughput sequencing for 3C) data which includes functions for:
1. Load single-cell HiC datasets
2. Smoothing the contact maps with linear convolution, random walk or network enhancing
3. Calculating embeddings for single cell HiC datasets efficiently with reproducibility measures include InnerProduct, HiCRep and Selfish
### Installation
**Required Python Packages**
- Python (version >= 3.6)
- numpy (version >= 1.15.4)
- scipy (version >= 1.0)
- matplotlib (version >=3.1.1)
- pandas (version >=0.19)
- simplejson
- six
- h5py
**`interactive_scatter` feature requirement**
- plotly (version >= >=4.8.0)
**Install from GitHub**
You can install the package with following command:
```console
$ git clone https://github.com/liu-bioinfo-lab/scHiCTools.git
$ cd scHiCTools
$ python setup.py install
```
**Install from PyPI**
```console
$ pip install scHiCTools
```
**Install optional interactive dependencie**
```console
$ pip install scHiCTools[interactive_scatter]
```
or
```console
$ pip install -e .[interactive_scatter]
```
### Usage
**Supported Formats**
- Pre-processed Matrices:
If the data is already processed into matrices for intra-chromosomal contacts,
the chromosome from the same cell must be stored in the same folder with
chromosome names as file names (e.g., scHiC/cell_1/chr1.txt).
You only need to provide the folder name for a cell (e.g., scHiC/cell_1).
- npy: numpy.array / numpy.matrix
- npz: scipy.sparse.coo_matrix
- matrix: matrix stored as pure text
- matrix_txt: matrix stored as .txt file
- HiCRep: the format required by HiCRep package
- Edge List <br />
For all formats below:<br />
str - strand (forward / reverse)<br />
chr - chromosome<br />
pos - position<br />
score - contact reads<br />
frag - fragments (will be ignored)<br />
mapq - map quality<br />
- Shortest
```
<chr1> <pos1> <chr2> <pos2>
```
- Shortest_Score
```
<chr1> <pos1> <chr2> <pos2> <score>
```
- Short
```
<str1> <chr1> <pos1> <frag1> <str2> <chr2> <pos2> <frag2>
```
- Short_Score
```
<str1> <chr1> <pos1> <frag1> <str2> <chr2> <pos2> <frag2> <score>
```
- Medium
```
<readname> <str1> <chr1> <pos1> <frag1> <str2> <chr2> <pos2> <frag2> <mapq1> <mapq2>
```
- Long
```
<str1> <chr1> <pos1> <frag1> <str2> <chr2> <pos2> <frag2> <mapq1> <cigar1> <sequence1> <mapq2> <cigar2> <sequence2> <readname1> <readname2>
```
- 4DN
```
## pairs format v1.0
#columns: readID chr1 position1 chr2 position2 strand1 strand2
```
- .hic format: we adapted "straw" from JuiceTools.
- .mcool format: we adapted "dump" from cool.
- Other formats: simply give the indices (start from 1) in the order of<br />
"chromosome1 - position1 - chromosome2 - position2 - score" or<br />
"chromosome1 - position1 - chromosome2 - position2" or<br />
"chromosome1 - position1 - chromosome2 - position2 - mapq1 - mapq2".<br />
For example, you can provide "2356" or [2, 3, 5, 6] if the file takes this format:
```
<name> <chromosome1> <position1> <frag1> <chromosome2> <position2> <frag2> <strand1> <strand2>
contact_1 chr1 3000000 1 chr1 3001000 1 + -
```
**Import Package**
```console
>>>import scHiCTools
```
**Load scHiC data**
The scHiC data is stored in a series of files, with each of the files corresponding to one cell.
You need to specify the list of scHiC file paths.
Only intra-chromosomal interactions are counted.
```console
>>>from scHiCTools import scHiCs
>>>files = ['./cell_1', './cell_2', './cell_3']
>>>loaded_data = scHiCs(
... files, reference_genome='mm9',
... resolution=500000, keep_n_strata=10,
... format='customized', adjust_resolution=True,
... customized_format=12345, header=0, chromosomes='except Y',
... operations=['OE_norm', 'convolution']
... )
```
- reference genome (dict or str): now supporting 'mm9', 'mm10', 'hg19', 'hg38'.
If your reference genome is not in ['mm9', 'mm10', 'hg19', 'hg38'], you need to provide the lengths of chromosomes
you are going to use with a Python dict. e.g. {'chr1': 150000000, 'chr2': 130000000, 'chr3': 200000000}
- resolution (int): the resolution to separate genome into bins.
If using .hic file format, the given resolution must match with the resolutions in .hic file.
- keep_n_strata (None or int): only store contacts within n strata near the diagonal. Default: 10.
If 'None', it will not store strata
- store_full_map (bool): whether store full contact maps in numpy matrices or
scipy sparse matrices,If False, it will save memory.
- sparse (bool): whether to use sparse matrices
- format (str): file format, supported formats: 'shortest', 'shortest_score', 'short',
'short_score' , 'medium', 'long', '4DN', '.hic', '.mcool', 'npy', 'npz', 'matrix',
'HiCRep', 'matrix_txt' and 'customized'. Default: 'customized'.
- customized_format (int or str or list): the column indices in the order of
"chromosome 1 - position 1 - chromosome 2 - position 2 - contact reads" or
"chromosome 1 - position 1 - chromosome 2 - position 2" or
"chromosome 1 - position 1 - chromosome 2 - position 2 - map quality 1 - map quality 2".
e.g. if the line is "chr1 5000000 chr2 3500000 2", the format should be '12345' or [1, 2, 3, 4, 5]; if there is no column
indicating number of reads, you can just provide 4 numbers like '1234', and contact read will be set as 1.
Default: '12345'.
- adjust_resolution: whether to adjust resolution for the input file.
Sometimes the input file is already in the proper resolution (e.g. position 3000000 has already been changed to 6 with 500kb resolution).
For this situation you can set adjust_resolution=False. Default: True.
- map_filter (float): keep all contacts with mapq higher than this threshold. Default: 0.0
- header (int): how many header lines does the file have. Default: 0.
- chromosomes (list or str): chromosomes to use, eg. ['chr1', 'chr2'], or
just 'except Y', 'except XY', 'all'.
Default: 'all', which means chr 1-19 + XY for mouse and chr 1-22 + XY for human.
- operations (list or None): the operations use for pre-processing or smoothing the maps given in a list.
The operations will happen in the given order.
Supported operations: 'logarithm', 'power', 'convolution', 'random_walk',
'network_enhancing', 'OE_norm', 'VC_norm', 'VC_SQRT_norm', 'KR_norm'。
Default: None.
- For preprocessing and smoothing operations, sometimes you need additional arguments
(introduced in next sub-section).
You can also skip pre-processing and smoothing in loading step (operations=None),
and do them in next lines.
**Plot number of contacts and select cells**
You can plot the number of contacts of your cells.
```console
>>>loaded_data.plot_contacts(hist=True, percent=True)
```
If hist is `True`, plot Histogram of the number of contacts. If percent is `True`, plot the scatter plot of cells with of short-range contacts (< 2 Mb) versus contacts at the mitotic band (2-12 Mb).
You can select cells based on number of contacts:
```console
>>>loaded_data.select_cells(min_n_contacts=10000,max_short_range_contact=0.99)
```
The above command select cells have number of contacts bigger than 10000 and percent of short range contacts small than .99.
**Pre-processing and Smoothing Operations**
Stand alone pre-processing and smoothing:
```console
>>>loaded_data.processing(['random_walk', 'network_enhancing'])
```
If you didn't store full map (i.e. store_full_map=False), processing is not
doable in a separate step.
- logarithm:
new_W_ij = log_(base) (W_ij + epsilon). Additional arguments:
- log_base: default: e
- epsilon: default: 1
- power: new_W_ij = (W_ij)^pow. Additional argument:
- pow: default: 0.5 (i.e., sqrt(W_ij))
- VC_norm: VC normalization - each value divided by the sum of
corresponding row then divided by the sum of corresponding column
- VC_SQRT_norm: VC_SQRT normalization - each value divided by the sqrt of the sum
of corresponding row then divided by the sqrt of the sum of corresponding column
- KR_norm: KR normalization - iterating until the sum of each row / column is one
Argument:
- maximum_error_rate (float): iteration ends when max error is smaller
than (maximum_error_rate). Default: 1e-4
- OE_norm: OE normalization - each value divided by the average of its
corresponding strata (diagonal line)
- convolution: smoothing with a N by N convolution kernel, with each value equal to 1/N^2.
Argument:
- kernel_shape: an integer. e.g. kernel_shape=3 means a 3*3 matrix with each value = 1/9. Default: 3.
- Random walk: multiply by a transition matrix (also calculated from contact map itself).
Argument:
- random_walk_ratio: a value between 0 and 1, e.g. if ratio=0.9, the result will be
0.9 * matrix_after_random_walk + 0.1 * original_matrix. Default: 1.0.
- Network enhancing: transition matrix only comes from k-nearest neighbors of each line.
Arguments:
- kNN: value 'k' in kNN. Default: 20.
- iterations: number of iterations for network enhancing. Default: 1
- alpha: similar with random_walk_ratio. Default: 0.9
**Learn Embeddings**
```console
>>>embs = loaded_data.learn_embedding(
... dim=2, similarity_method='inner_product', embedding_method='MDS',
... n_strata=None, aggregation='median', return_distance=False
... )
```
This function will return the embeddings in the format of a numpy array with shape ( # of cells, # of dimensions).
- dim (int): the dimension for the embedding
- similarity_method (str): reproducibility measure, 'InnerProduct', 'HiCRep' or
'Selfish'. Default: 'InnerProduct'
- embedding_method (str): 'MDS', 'tSNE' or 'UMAP'
- n_strata (int): only consider contacts within this genomic distance. Default: None.
If it is None, it will use the all strata kept (the argument keep_n_strata from
previous loading process). Thus n_strata and keep_n_strata (loading step) cannot be
None at the same time.
- aggregation (str): method to aggregate different chromosomes,
'mean' or 'median'. Default: 'median'.
- return_distance (bool): if True, return (embeddings, distance_matrix); if False, only return embeddings. Default: False.
- Some additional argument for Selfish:
- n_windows (int): split contact map into n windows, default: 10
- sigma (float): sigma in the Gaussian-like kernel: default: 1.6
**Clustering**
There are two functions to cluster cells.
```console
>>>label=loaded_data.clustering(
... n_clusters=4, clustering_method='kmeans', similarity_method='innerproduct',
... aggregation='median', n_strata=None
... )
```
`clustering` function returns a numpy array of cell labels clustered.
- n_clusters (int): Number of clusters.
- clustering_method (str):
Clustering method in 'kmeans', 'spectral_clustering' or 'HAC'(hierarchical agglomerative clustering).
- similarity_method (str):
Reproducibility measure.
Value in ‘InnerProduct’, ‘HiCRep’ or ‘Selfish’.
- aggregation (str):
Method to aggregate different chromosomes.
Value is either 'mean' or 'median'.
Default: 'median'.
- n_strata (int or None):
Only consider contacts within this genomic distance.
If it is None, it will use the all strata kept (the argument keep_n_strata) from previous loading process. Default: None.
- print_time (bool):
Whether to print the processing time. Default: False.
```console
>>>hicluster=loaded_data.scHiCluster(dim=2,cutoff=0.8,n_PCs=10,k=4)
```
`scHiCluster` function returns two componments.
First componment is a numpy array of embedding of cells using HiCluster.
Second componment is a numpy of cell labels clustered by HiCluster.
- dim (int): Number of dimension of embedding. Default: 2.
- cutoff (float): The cutoff proportion to convert the real contact matrix into binary matrix. Default: 0.8.
- n_PCs (int): Number of principal components. Default: 10.
- k (int): Number of clusters. Default: 4.
**Visualization**
```console
>>>scatter(data, dimension="2D", point_size=3, sty='default',
... label=None, title=None, alpha=None, aes_label=None
... )
>>>plt.show()
```
This function is to plot scatter plot of embedding points of single cell data.
Scatter plot of either two-dimensions or three-dimensions will be generated.
- data (numpy.array): A numpy array which has 2 or 3 columns, every row represent a point.
- dimension (str): Specifiy the dimension of the plot, either "2D" or "3D". Default: "2D".
- point_size (float): Set the size of the points in scatter plot. Default: 3.
- sty (str): Styles of Matplotlib. Default: 'default'.
- label (list or None): specifiy the label of each point. Default: None.
- title (str): Title of the plot. Default: None.
- alpha (float): The alpha blending value. Default: None.
- aes_label (list): Set the label of every axis. Default: None.
"scHiCTools" also support interactive scatter plot which require the module 'plotly'
```console
>>>interactive_scatter(loaded_data, data, out_file, dimension='2D', point_size=3,
... label=None, title=None, alpha=1, aes_label=None)
```
This function is to generate an interactive scatter plot of embedded single cell data.
The plot will be stored in a file.
- schic (scHiCs): A `scHiCs` object.
- data (numpy.array): A numpy array which has 2 or 3 columns, every row represent a point.
- out_file (str): Output file path.
- dimension (str): Specifiy the dimension of the plot, either "2D" or "3D". The default is "2D".
- point_size (float): Set the size of the points in scatter plot. The default is 3.
- label (list or None): Specifiy the label of each point. The default is None.
- title (str): Title of the plot. The default is None.
- alpha (float): The alpha blending value. The default is 1.
- aes_label (list): Set the label of every axis. The default is None.
### Citation
Xinjun Li, Fan Feng, Wai Yan Leung and Jie Liu. "scHiCTools: a computational toolbox for analyzing single cell Hi-C data."
bioRxiv (2019): 769513.
### References
A. R. Ardakany, F. Ay, and S. Lonardi. Selfish: Discovery of differential chromatininteractions via a self-similarity measure.bioRxiv, 2019.
N. C. Durand, J. T. Robinson, M. S. Shamim, I. Machol, J. P. Mesirov, E. S. Lander, and E. Lieberman Aiden. "Juicebox provides a visualization system for Hi-C contact maps with unlimited zoom." Cell Systems 3(1), 2016.
J. Liu, D. Lin, G. Yardimci, and W. S. Noble. Unsupervised embedding of single-cellHi-C data.Bioinformatics, 34:96–104, 2018.
T. Nagano, Y. Lubling, C. Várnai, C. Dudley, W. Leung, Y. Baran, N. M. Cohen,S. Wingett, P. Fraser, and A. Tanay. Cell-cycle dynamics of chromosomal organization at single-cell resolution.Nature, 547:61–67, 2017.
B. Wang, A. Pourshafeie, M. Zitnik, J. Zhu, C. D. Bustamante, S. Batzoglou, andJ. Leskovec. Network enhancement as a general method to denoise weighted biological networks.Nature Communications, 9(1):3108, 2018.
T. Yang, F. Zhang, G. G. Y. mcı, F. Song, R. C. Hardison, W. S. Noble, F. Yue, andQ. Li. HiCRep: assessing the reproducibility of Hi-C data using a stratum-adjusted correlation coefficient.Genome Research, 27(11):1939–1949, 2017.
G. G. Yardımcı, H. Ozadam, M. E. Sauria, O. Ursu, K. K. Yan, T. Yang,A. Chakraborty, A. Kaul, B. R. Lajoie, F. Song, et al. Measuring the reproducibilityand quality of hi-c data.Genome Biology, 20(1):57, 2019.
|
/scHiCTools-0.0.3.tar.gz/scHiCTools-0.0.3/README.md
| 0.899257 | 0.938969 |
README.md
|
pypi
|
# Author: Vlad Niculae
# Lars Buitinck
# Mathieu Blondel <[email protected]>
# Tom Dupre la Tour
# License: BSD 3 clause
from math import sqrt
import warnings
import numbers
import numpy as np
import scipy.sparse as sp
from datetime import datetime
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils import check_random_state, check_array
from sklearn.utils.extmath import randomized_svd, safe_sparse_dot, squared_norm
from sklearn.utils.validation import check_is_fitted
from sklearn.exceptions import ConvergenceWarning
from cdnmf_fast import _update_cdnmf_fast
EPSILON = np.finfo(np.float32).eps
INTEGER_TYPES = (numbers.Integral, np.integer)
def safe_min(X):
"""Returns the minimum value of a dense or a CSR/CSC matrix.
Adapated from https://stackoverflow.com/q/13426580
.. deprecated:: 0.22.0
Parameters
----------
X : array_like
The input array or sparse matrix
Returns
-------
Float
The min value of X
"""
if sp.issparse(X):
if len(X.data) == 0:
return 0
m = X.data.min()
return m if X.getnnz() == X.size else min(m, 0)
else:
return X.min()
def norm(x):
"""Dot product-based Euclidean norm implementation
See: http://fseoane.net/blog/2011/computing-the-vector-norm/
Parameters
----------
x : array-like
Vector for which to compute the norm
"""
return sqrt(squared_norm(x))
def trace_dot(X, Y):
"""Trace of np.dot(X, Y.T).
Parameters
----------
X : array-like
First matrix
Y : array-like
Second matrix
"""
return np.dot(_safe_ravel(X), _safe_ravel(Y))
def _check_non_negative(X, whom, accept_nan=False):
"""
Check if there is any negative value in an array.
Parameters
----------
X : array-like or sparse matrix
Input data.
whom : string
Who passed X to this function.
accept_nan : boolean
If True, NaN values are accepted in X.
"""
# avoid X.min() on sparse matrix since it also sorts the indices
if sp.issparse(X):
if X.format in ['lil', 'dok']:
X = X.tocsr()
if X.data.size == 0:
X = np.arange(1)
else:
X = X.data
if accept_nan:
X_min = np.nanmin(X)
else:
X_min = np.min(X)
if np.isnan(X_min):
raise ValueError("NaN values in data passed to %s" % whom)
if X_min < 0:
raise ValueError("Negative values in data passed to %s" % whom)
def _check_init(A, shape, whom):
A = check_array(A)
if np.shape(A) != shape:
raise ValueError('Array with wrong shape passed to %s. Expected %s, '
'but got %s ' % (whom, shape, np.shape(A)))
_check_non_negative(A, whom)
if np.max(A) == 0:
raise ValueError('Array passed to %s is full of zeros.' % whom)
def _safe_squared_norm(X):
"""Squared Euclidean or Frobenius norm of X, safe for numpy masked arrays.
"""
X = _safe_ravel(X)
if isinstance(X, np.ma.masked_array):
return float(np.ma.dot(X, X))
else:
return np.dot(X, X)
def _safe_ravel(X):
"""Guarantee that we preserve masked array in ravel.
"""
if isinstance(X, np.ma.masked_array):
return np.ma.ravel(X)
else:
return np.ravel(X)
def _safe_mean(X):
"""Compute the arithmetic mean of an array, safe for sparse and NaN values
"""
if sp.issparse(X):
return X.mean()
else:
return np.nanmean(X)
def _special_dot_X(W, H, X, out=None):
"""Computes np.dot(W, H) in a special way:
- If X is sparse, np.dot(W, H) is computed only where X is non zero,
and a sparse matrix is returned, with the same sparsity as X.
- If X is masked, np.dot(W, H) is computed entirely, and a masked array is
returned, with the same mask as X.
- If X is dense, np.dot(W, H) is computed entirely, and returned as a dense
array.
"""
if sp.issparse(X):
ii, jj = X.nonzero()
dot_vals = np.multiply(W[ii, :], H.T[jj, :]).sum(axis=1)
WH = sp.coo_matrix((dot_vals, (ii, jj)), shape=X.shape)
return WH.tocsr()
elif isinstance(X, np.ma.masked_array):
WH = np.ma.masked_array(np.dot(W, H, out=out), mask=X.mask)
WH._sharedmask = False
return WH
else:
return np.dot(W, H, out=out)
def _safe_dot(X, Ht):
"""Computes np.dot(X, Ht) such that the sparse and the masked cases are
handled correctly.
Note that the masked case do not return a masked array.
"""
if isinstance(X, np.ma.masked_array) or isinstance(Ht, np.ma.masked_array):
return np.asarray(np.ma.dot(X, Ht))
else:
return safe_sparse_dot(X, Ht)
def _compute_regularization(alpha, l1_ratio, regularization):
"""Compute L1 and L2 regularization coefficients for W and H"""
alpha_H = 0.
alpha_W = 0.
if regularization in ('both', 'components'):
alpha_H = float(alpha)
if regularization in ('both', 'transformation'):
alpha_W = float(alpha)
l1_reg_W = alpha_W * l1_ratio
l1_reg_H = alpha_H * l1_ratio
l2_reg_W = alpha_W * (1. - l1_ratio)
l2_reg_H = alpha_H * (1. - l1_ratio)
return l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H
def _loss(X, W, H):
"""Compute the Frobenius *squared* norm of X - dot(W, H).
Parameters
----------
X : float or array-like, shape (n_samples, n_features)
Numpy masked arrays or arrays containing NaN are accepted.
W : float or dense array-like, shape (n_samples, n_components)
H : float or dense array-like, shape (n_components, n_features)
Returns
-------
res : float
Frobenius norm of X and np.dot(X, H)
"""
# The method can be called with scalars
if not sp.issparse(X):
X = np.atleast_2d(X)
W = np.atleast_2d(W)
H = np.atleast_2d(H)
# Frobenius norm
# Avoid the creation of the dense np.dot(W, H) if X is sparse.
if sp.issparse(X):
norm_X = np.dot(X.data, X.data)
norm_WH = trace_dot(np.dot(np.dot(W.T, W), H), H)
cross_prod = trace_dot((X * H.T), W)
res = (norm_X + norm_WH - 2. * cross_prod) / 2.
else:
res = _safe_squared_norm(X - np.dot(W, H)) / 2.
assert not np.isnan(res)
assert res >= 0
return np.sqrt(res * 2)
def _initialize_nmf(X, n_components, init=None, eps=1e-6,
random_state=None):
"""Algorithms for NMF initialization.
Computes an initial guess for the non-negative
rank k matrix approximation for X: X = WH
Parameters
----------
X : array-like, shape (n_samples, n_features)
The data matrix to be decomposed.
n_components : integer
The number of components desired in the approximation.
init : None | 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar'
Method used to initialize the procedure.
Default: None.
Valid options:
- None: 'nndsvd' if n_components <= min(n_samples, n_features),
otherwise 'random'.
- 'random': non-negative random matrices, scaled with:
sqrt(X.mean() / n_components)
- 'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD)
initialization (better for sparseness)
- 'nndsvda': NNDSVD with zeros filled with the average of X
(better when sparsity is not desired)
- 'nndsvdar': NNDSVD with zeros filled with small random values
(generally faster, less accurate alternative to NNDSVDa
for when sparsity is not desired)
- 'custom': use custom matrices W and H
eps : float
Truncate all values less then this in output to zero.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`. Used when ``random`` == 'nndsvdar' or 'random'.
Returns
-------
W : array-like, shape (n_samples, n_components)
Initial guesses for solving X ~= WH
H : array-like, shape (n_components, n_features)
Initial guesses for solving X ~= WH
References
----------
C. Boutsidis, E. Gallopoulos: SVD based initialization: A head start for
nonnegative matrix factorization - Pattern Recognition, 2008
http://tinyurl.com/nndsvd
"""
_check_non_negative(X, "NMF initialization", accept_nan=True)
n_samples, n_features = X.shape
if (init is not None and init != 'random'
and n_components > min(n_samples, n_features)):
raise ValueError("init = '{}' can only be used when "
"n_components <= min(n_samples, n_features)"
.format(init))
if init is None:
if n_components <= min(n_samples, n_features):
init = 'nndsvd'
else:
init = 'random'
# Random initialization
if init == 'random':
X_mean = _safe_mean(X)
avg = np.sqrt(X_mean / n_components)
rng = check_random_state(random_state)
H = avg * rng.randn(n_components, n_features)
W = avg * rng.randn(n_samples, n_components)
# we do not write np.abs(H, out=H) to stay compatible with
# numpy 1.5 and earlier where the 'out' keyword is not
# supported as a kwarg on ufuncs
np.abs(H, H)
np.abs(W, W)
return W, H
if not sp.issparse(X) and np.any(np.isnan(X)):
raise ValueError("NMF initializations with NNDSVD are not available "
"with missing values (np.nan).")
# NNDSVD initialization
U, S, V = randomized_svd(X, n_components, random_state=random_state)
W, H = np.zeros(U.shape), np.zeros(V.shape)
# The leading singular triplet is non-negative
# so it can be used as is for initialization.
W[:, 0] = np.sqrt(S[0]) * np.abs(U[:, 0])
H[0, :] = np.sqrt(S[0]) * np.abs(V[0, :])
for j in range(1, n_components):
x, y = U[:, j], V[j, :]
# extract positive and negative parts of column vectors
x_p, y_p = np.maximum(x, 0), np.maximum(y, 0)
x_n, y_n = np.abs(np.minimum(x, 0)), np.abs(np.minimum(y, 0))
# and their norms
x_p_nrm, y_p_nrm = norm(x_p), norm(y_p)
x_n_nrm, y_n_nrm = norm(x_n), norm(y_n)
m_p, m_n = x_p_nrm * y_p_nrm, x_n_nrm * y_n_nrm
# choose update
if m_p > m_n:
u = x_p / x_p_nrm
v = y_p / y_p_nrm
sigma = m_p
else:
u = x_n / x_n_nrm
v = y_n / y_n_nrm
sigma = m_n
lbd = np.sqrt(S[j] * sigma)
W[:, j] = lbd * u
H[j, :] = lbd * v
W[W < eps] = 0
H[H < eps] = 0
if init == "nndsvd":
pass
elif init == "nndsvda":
avg = X.mean()
W[W == 0] = avg
H[H == 0] = avg
elif init == "nndsvdar":
rng = check_random_state(random_state)
avg = X.mean()
W[W == 0] = abs(avg * rng.randn(len(W[W == 0])) / 100)
H[H == 0] = abs(avg * rng.randn(len(H[H == 0])) / 100)
else:
raise ValueError(
'Invalid init parameter: got %r instead of one of %r' %
(init, (None, 'random', 'nndsvd', 'nndsvda', 'nndsvdar')))
return W, H
def _update_coordinate_descent(X, W, Ht, l1_reg, l2_reg, shuffle,
random_state):
"""Helper function for _fit_coordinate_descent
Update W to minimize the objective function, iterating once over all
coordinates. By symmetry, to update H, one can call
_update_coordinate_descent(X.T, Ht, W, ...)
"""
n_components = Ht.shape[1]
HHt = np.dot(Ht.T, Ht)
XHt = safe_sparse_dot(X, Ht)
# L2 regularization corresponds to increase of the diagonal of HHt
if l2_reg != 0.:
# adds l2_reg only on the diagonal
HHt.flat[::n_components + 1] += l2_reg
# L1 regularization corresponds to decrease of each element of XHt
if l1_reg != 0.:
XHt -= l1_reg
if shuffle:
permutation = random_state.permutation(n_components)
else:
permutation = np.arange(n_components)
# The following seems to be required on 64-bit Windows w/ Python 3.5.
permutation = np.asarray(permutation, dtype=np.intp)
return _update_cdnmf_fast(W, HHt, XHt, permutation)
def _fit_coordinate_descent(X, W, H, tol=1e-4, max_iter=200, l1_reg_W=0,
l1_reg_H=0, l2_reg_W=0, l2_reg_H=0,
verbose=0, shuffle=False, random_state=None):
"""Compute Non-negative Matrix Factorization (NMF) with Coordinate Descent
The objective function is minimized with an alternating minimization of W
and H. Each minimization is done with a cyclic (up to a permutation of the
features) Coordinate Descent.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Constant matrix.
W : array-like, shape (n_samples, n_components)
Initial guess for the solution.
H : array-like, shape (n_components, n_features)
Initial guess for the solution.
tol : float, default: 1e-4
Tolerance of the stopping condition.
max_iter : integer, default: 200
Maximum number of iterations before timing out.
l1_reg_W : double, default: 0.
L1 regularization parameter for W.
l1_reg_H : double, default: 0.
L1 regularization parameter for H.
l2_reg_W : double, default: 0.
L2 regularization parameter for W.
l2_reg_H : double, default: 0.
L2 regularization parameter for H.
update_H : boolean, default: True
Set to True, both W and H will be estimated from initial guesses.
Set to False, only W will be estimated.
verbose : integer, default: 0
The verbosity level.
shuffle : boolean, default: False
If true, randomize the order of coordinates in the CD solver.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
Returns
-------
W : array-like, shape (n_samples, n_components)
Solution to the non-negative least squares problem.
H : array-like, shape (n_components, n_features)
Solution to the non-negative least squares problem.
n_iter : int
The number of iterations done by the algorithm.
References
----------
Cichocki, Andrzej, and Phan, Anh-Huy. "Fast local algorithms for
large scale nonnegative matrix and tensor factorizations."
IEICE transactions on fundamentals of electronics, communications and
computer sciences 92.3: 708-721, 2009.
"""
# so W and Ht are both in C order in memory
Ht = check_array(H.T, order='C')
X = check_array(X, accept_sparse='csr')
rng = check_random_state(random_state)
for n_iter in range(max_iter):
violation = 0.
# Update W
violation += _update_coordinate_descent(X, W, Ht, l1_reg_W,
l2_reg_W, shuffle, rng)
# Update H
violation += _update_coordinate_descent(X.T, Ht, W, l1_reg_H,
l2_reg_H, shuffle, rng)
if n_iter == 0:
violation_init = violation
if violation_init == 0:
break
_violation = violation / violation_init
if verbose == 1:
print(f"{datetime.now().strftime('%m/%d/%Y %H:%M:%S')}, iteration: {n_iter: }, "
f"violation: {_violation: .8f}")
elif verbose == 2:
err = _loss(X, W, Ht.T)
print(f"{datetime.now().strftime('%m/%d/%Y %H:%M:%S')}, iteration: {n_iter: }, "
f"violation: {_violation: .8f}, error: {err: .8f}")
if violation / violation_init <= tol:
if verbose:
print(f"{datetime.now().strftime('%m/%d/%Y %H:%M:%S')}, "
f"Converged at iteration {n_iter + 1}")
break
return W, Ht.T, n_iter
def non_negative_factorization(X, W=None, H=None, n_components=None,
init=None, tol=1e-4,
max_iter=200, alpha=0., l1_ratio=0.,
regularization=None, random_state=None,
verbose=0, shuffle=False):
r"""Compute Non-negative Matrix Factorization (NMF)
Find two non-negative matrices (W, H) whose product approximates the non-
negative matrix X. This factorization can be used for example for
dimensionality reduction, source separation or topic extraction.
The objective function is::
0.5 * ||X - WH||_Fro^2
+ 0.5 * alpha * ||W||_Fro^2
+ 0.5 * alpha * ||H||_Fro^2
Where::
||A||_Fro^2 = \sum_{i,j} A_{ij}^2 (Frobenius norm)
||vec(A)||_1 = \sum_{i,j} abs(A_{ij}) (Elementwise L1 norm)
The objective function is minimized with an alternating minimization of W
and H.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Constant matrix.
W : array-like, shape (n_samples, n_components)
If init='custom', it is used as initial guess for the solution.
H : array-like, shape (n_components, n_features)
If init='custom', it is used as initial guess for the solution.
If update_H=False, it is used as a constant, to solve for W only.
n_components : integer
Number of components, if n_components is not set all features
are kept.
init : None | 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar' | 'custom'
Method used to initialize the procedure.
Default: 'random'.
The default value will change from 'random' to None in version 0.23
to make it consistent with decomposition.NMF.
Valid options:
- None: 'nndsvd' if n_components < n_features, otherwise 'random'.
- 'random': non-negative random matrices, scaled with:
sqrt(X.mean() / n_components)
- 'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD)
initialization (better for sparseness)
- 'nndsvda': NNDSVD with zeros filled with the average of X
(better when sparsity is not desired)
- 'nndsvdar': NNDSVD with zeros filled with small random values
(generally faster, less accurate alternative to NNDSVDa
for when sparsity is not desired)
- 'custom': use custom matrices W and H
tol : float, default: 1e-4
Tolerance of the stopping condition.
max_iter : integer, default: 200
Maximum number of iterations before timing out.
alpha : double, default: 0.
Constant that multiplies the regularization terms.
l1_ratio : double, default: 0.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
For l1_ratio = 0 the penalty is an elementwise L2 penalty
(aka Frobenius Norm).
For l1_ratio = 1 it is an elementwise L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
regularization : 'both' | 'components' | 'transformation' | None
Select whether the regularization affects the components (H), the
transformation (W), both or none of them.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
verbose : integer, default: 0
The verbosity level.
shuffle : boolean, default: False
If true, randomize the order of coordinates in the CD solver.
Returns
-------
W : array-like, shape (n_samples, n_components)
Solution to the non-negative least squares problem.
H : array-like, shape (n_components, n_features)
Solution to the non-negative least squares problem.
n_iter : int
Actual number of iterations.
References
----------
Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for
large scale nonnegative matrix and tensor factorizations."
IEICE transactions on fundamentals of electronics, communications and
computer sciences 92.3: 708-721, 2009.
"""
X = check_array(X, accept_sparse=('csr', 'csc'), dtype=float,
force_all_finite=False)
_check_non_negative(X, "NMF (input X)", accept_nan=True)
if sp.issparse(X) and np.any(np.isnan(X.data)):
raise ValueError("X contains NaN values, and NMF with missing "
"values is not implemented for sparse matrices.")
n_samples, n_features = X.shape
if n_components is None:
n_components = n_features
if not isinstance(n_components, INTEGER_TYPES) or n_components <= 0:
raise ValueError("Number of components must be a positive integer;"
" got (n_components=%r)" % n_components)
if not isinstance(max_iter, INTEGER_TYPES) or max_iter < 0:
raise ValueError("Maximum number of iterations must be a positive "
"integer; got (max_iter=%r)" % max_iter)
if not isinstance(tol, numbers.Number) or tol < 0:
raise ValueError("Tolerance for stopping criteria must be "
"positive; got (tol=%r)" % tol)
# check W and H, or initialize them
if init == 'custom':
_check_init(H, (n_components, n_features), "NMF (input H)")
_check_init(W, (n_samples, n_components), "NMF (input W)")
else:
W, H = _initialize_nmf(X, n_components, init=init,
random_state=random_state)
l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H = _compute_regularization(
alpha, l1_ratio, regularization)
W, H, n_iter = _fit_coordinate_descent(X, W, H, tol, max_iter,
l1_reg_W, l1_reg_H,
l2_reg_W, l2_reg_H,
verbose=verbose,
shuffle=shuffle,
random_state=random_state)
if n_iter == max_iter and tol > 0:
warnings.warn("Maximum number of iteration %d reached. Increase it to"
" improve convergence." % max_iter, ConvergenceWarning)
return W, H, n_iter
class NMF(BaseEstimator, TransformerMixin):
r"""Non-Negative Matrix Factorization (NMF)
Find two non-negative matrices (W, H) whose product approximates the non-
negative matrix X. This factorization can be used for example for
dimensionality reduction, source separation or topic extraction.
The objective function is::
0.5 * ||X - WH||_Fro^2
+ alpha * l1_ratio * ||vec(W)||_1
+ alpha * l1_ratio * ||vec(H)||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
+ 0.5 * alpha * (1 - l1_ratio) * ||H||_Fro^2
Where::
||A||_Fro^2 = \sum_{i,j} A_{ij}^2 (Frobenius norm)
||vec(A)||_1 = \sum_{i,j} abs(A_{ij}) (Elementwise L1 norm)
For multiplicative-update ('mu') solver, the Frobenius norm
(0.5 * ||X - WH||_Fro^2) can be changed into another beta-divergence loss,
by changing the beta_loss parameter.
The objective function is minimized with an alternating minimization of W
and H.
Read more in the :ref:`User Guide <NMF>`.
Parameters
----------
n_components : int or None
Number of components, if n_components is not set all features
are kept.
init : None | 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar' | 'custom'
Method used to initialize the procedure.
Default: None.
Valid options:
- None: 'nndsvd' if n_components <= min(n_samples, n_features),
otherwise random.
- 'random': non-negative random matrices, scaled with:
sqrt(X.mean() / n_components)
- 'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD)
initialization (better for sparseness)
- 'nndsvda': NNDSVD with zeros filled with the average of X
(better when sparsity is not desired)
- 'nndsvdar': NNDSVD with zeros filled with small random values
(generally faster, less accurate alternative to NNDSVDa
for when sparsity is not desired)
- 'custom': use custom matrices W and H
tol : float, default: 1e-4
Tolerance of the stopping condition.
max_iter : integer, default: 200
Maximum number of iterations before timing out.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
alpha : double, default: 0.
Constant that multiplies the regularization terms. Set it to zero to
have no regularization.
.. versionadded:: 0.17
*alpha* used in the Coordinate Descent solver.
l1_ratio : double, default: 0.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
For l1_ratio = 0 the penalty is an elementwise L2 penalty
(aka Frobenius Norm).
For l1_ratio = 1 it is an elementwise L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
.. versionadded:: 0.17
Regularization parameter *l1_ratio* used in the Coordinate Descent
solver.
verbose : bool, default=False
Whether to be verbose.
shuffle : boolean, default: False
If true, randomize the order of coordinates in the CD solver.
.. versionadded:: 0.17
*shuffle* parameter used in the Coordinate Descent solver.
Attributes
----------
components_ : array, [n_components, n_features]
Factorization matrix, sometimes called 'dictionary'.
reconstruction_err_ : number
Frobenius norm of the matrix difference, or beta-divergence, between
the training data ``X`` and the reconstructed data ``WH`` from
the fitted model.
n_iter_ : int
Actual number of iterations.
Examples
--------
>>> import numpy as np
>>> X = np.array([[1, 1], [2, 1], [3, 1.2], [4, 1], [5, 0.8], [6, 1]])
>>> from sklearn.decomposition import NMF
>>> model = NMF(n_components=2, init='random', random_state=0)
>>> W = model.fit_transform(X)
>>> H = model.components_
References
----------
Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for
large scale nonnegative matrix and tensor factorizations."
IEICE transactions on fundamentals of electronics, communications and
computer sciences 92.3: 708-721, 2009.
Fevotte, C., & Idier, J. (2011). Algorithms for nonnegative matrix
factorization with the beta-divergence. Neural Computation, 23(9).
"""
def __init__(self, n_components=None, init=None, tol=1e-4, max_iter=200,
random_state=None, alpha=0., l1_ratio=0., verbose=0,
shuffle=False):
self.n_components = n_components
self.init = init
self.tol = tol
self.max_iter = max_iter
self.random_state = random_state
self.alpha = alpha
self.l1_ratio = l1_ratio
self.verbose = verbose
self.shuffle = shuffle
def fit_transform(self, X, y=None, W=None, H=None):
"""Learn a NMF model for the data X and returns the transformed data.
This is more efficient than calling fit followed by transform.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Data matrix to be decomposed
y : Ignored
W : array-like, shape (n_samples, n_components)
If init='custom', it is used as initial guess for the solution.
H : array-like, shape (n_components, n_features)
If init='custom', it is used as initial guess for the solution.
Returns
-------
W : array, shape (n_samples, n_components)
Transformed data.
"""
X = check_array(X, accept_sparse=('csr', 'csc'), dtype=float,
force_all_finite=False)
W, H, n_iter_ = non_negative_factorization(
X=X, W=W, H=H, n_components=self.n_components, init=self.init,
tol=self.tol, max_iter=self.max_iter, alpha=self.alpha,
l1_ratio=self.l1_ratio, regularization='both',
random_state=self.random_state, verbose=self.verbose,
shuffle=self.shuffle)
self.reconstruction_err_ = _loss(X, W, H)
self.n_components_ = H.shape[0]
self.components_ = H
self.n_iter_ = n_iter_
return W
def fit(self, X, y=None, **params):
"""Learn a NMF model for the data X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Data matrix to be decomposed
y : Ignored
Returns
-------
self
"""
self.fit_transform(X, **params)
return self
def transform(self, X):
"""Transform the data X according to the fitted NMF model
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Data matrix to be transformed by the model
Returns
-------
W : array, shape (n_samples, n_components)
Transformed data
"""
check_is_fitted(self, 'n_components_')
W, _, n_iter_ = non_negative_factorization(
X=X, W=None, H=self.components_, n_components=self.n_components_,
init=self.init, tol=self.tol, max_iter=self.max_iter,
alpha=self.alpha, l1_ratio=self.l1_ratio, regularization='both',
random_state=self.random_state, verbose=self.verbose,
shuffle=self.shuffle)
return W
def inverse_transform(self, W):
"""Transform data back to its original space.
Parameters
----------
W : {array-like, sparse matrix}, shape (n_samples, n_components)
Transformed data matrix
Returns
-------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Data matrix of original shape
.. versionadded:: 0.18
"""
check_is_fitted(self, 'n_components_')
return np.dot(W, self.components_)
|
/scOpen-1.0.1.tar.gz/scOpen-1.0.1/scopen/MF.py
| 0.901176 | 0.601828 |
MF.py
|
pypi
|
# scRFE
```
# Imports
import numpy as np
import pandas as pd
import scanpy as sc
import random
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from sklearn.feature_selection import RFECV
import seaborn as sns
import matplotlib.pyplot as plt
import scanpy.external as sce
import logging as logg
def columnToString (dataMatrix):
cat_columns = dataMatrix.obs.select_dtypes(['category']).columns
dataMatrix.obs[cat_columns] = dataMatrix.obs[cat_columns].astype(str)
return dataMatrix
def filterNormalize (dataMatrix, classOfInterest):
np.random.seed(644685)
# sc.pp.filter_cells(dataMatrix, min_genes=0)
# sc.pp.filter_genes(dataMatrix, min_cells=0)
dataMatrix = dataMatrix[dataMatrix.obs[classOfInterest]!='nan']
dataMatrix = dataMatrix[~dataMatrix.obs[classOfInterest].isna()]
print ('na data removed')
return dataMatrix
def labelSplit (dataMatrix, classOfInterest, labelOfInterest):
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
dataMatrix.obs['classification_group'] = 'B'
dataMatrix.obs.loc[dataMatrix.obs[dataMatrix.obs[classOfInterest]==labelOfInterest]
.index,'classification_group'] = 'A' #make labels based on A/B of
# classofInterest
return dataMatrix
def downsampleToSmallestCategory(dataMatrix, random_state, min_cells,
keep_small_categories,
classOfInterest = 'classification_group',
) -> sc.AnnData:
"""
returns an annData object in which all categories in 'classOfInterest' have
the same size
classOfInterest
column with the categories to downsample
min_cells
Minimum number of cells to downsample.
Categories having less than `min_cells` are discarded unless
keep_small_categories is True
keep_small_categories
Be default categories with less than min_cells are discarded.
Set to true to keep them
"""
counts = dataMatrix.obs[classOfInterest].value_counts(sort=False)
if len(counts[counts < min_cells]) > 0 and keep_small_categories is False:
logg.warning(
"The following categories have less than {} cells and will be "
"ignored: {}".format(min_cells, dict(counts[counts < min_cells]))
)
min_size = min(counts[counts >= min_cells])
sample_selection = None
for sample, num_cells in counts.items():
if num_cells <= min_cells:
if keep_small_categories:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample].index)
else:
continue
else:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample]
.sample(min_size, random_state=random_state)
.index
)
if sample_selection is None:
sample_selection = sel
else:
sample_selection |= sel
logg.info(
"The cells in category {!r} had been down-sampled to have each {} cells. "
"The original counts where {}".format(classOfInterest, min_size, dict(counts))
)
return dataMatrix[sample_selection].copy()
def makeOneForest (dataMatrix, classOfInterest, labelOfInterest, nEstimators,
randomState, min_cells, keep_small_categories,
nJobs, oobScore, Step, Cv):
"""
Builds and runs a random forest for one label in a class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
feature_selected : list
list of top features from random forest
selector.estimator_.feature_importances_ : list
list of top ginis corresponding to to features
"""
splitDataMatrix = labelSplit (dataMatrix, classOfInterest, labelOfInterest)
downsampledMatrix = downsampleToSmallestCategory (dataMatrix = splitDataMatrix,
random_state = randomState, min_cells = min_cells,
keep_small_categories = keep_small_categories,
classOfInterest = 'classification_group', )
feat_labels = downsampledMatrix.var_names
X = downsampledMatrix.X
y = downsampledMatrix.obs['classification_group'] #'A' or 'B' labels from labelSplit
clf = RandomForestClassifier(n_estimators = nEstimators, random_state = randomState,
n_jobs = nJobs, oob_score = oobScore)
selector = RFECV(clf, step = Step, cv = Cv)
clf.fit(X, y)
selector.fit(X, y)
feature_selected = feat_labels[selector.support_]
dataMatrix.obs['classification_group'] = 'B'
return feature_selected, selector.estimator_.feature_importances_
def resultWrite (classOfInterest, results_df, labelOfInterest,
feature_selected, feature_importance):
column_headings = []
column_headings.append(labelOfInterest)
column_headings.append(labelOfInterest + '_gini')
resaux = pd.DataFrame(columns = column_headings)
resaux[labelOfInterest] = feature_selected
resaux[labelOfInterest + '_gini'] = feature_importance
resaux = resaux.sort_values(by = [labelOfInterest + '_gini'], ascending = False)
resaux.reset_index(drop = True, inplace = True)
results_df = pd.concat([results_df, resaux], axis=1)
return results_df
def scRFE (adata, classOfInterest, nEstimators = 5000, randomState = 0, min_cells = 15,
keep_small_categories = True, nJobs = -1, oobScore = True, Step = 0.2, Cv = 5):
"""
Builds and runs a random forest with one vs all classification for each label
for one class of interest
Parameters
----------
adata : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
min_cells : int
Minimum number of cells in a given class to downsample.
keep_small_categories : bool
Whether to keep classes with small number of observations, or to remove.
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
results_df : pd.DataFrame
Dataframe with results for each label in the class, formatted as
"label" for one column, then "label + gini" for the corresponding column
"""
dataMatrix = adata.copy()
dataMatrix = columnToString (dataMatrix)
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
results_df = pd.DataFrame()
for labelOfInterest in np.unique(dataMatrix.obs[classOfInterest]):
dataMatrix_labelOfInterest = dataMatrix.copy()
feature_selected, feature_importance = makeOneForest(
dataMatrix = dataMatrix_labelOfInterest, classOfInterest = classOfInterest,
labelOfInterest = labelOfInterest,
nEstimators = nEstimators, randomState = randomState, min_cells = min_cells,
keep_small_categories = keep_small_categories, nJobs = nJobs,
oobScore = oobScore, Step = Step, Cv = Cv)
results_df = resultWrite (classOfInterest, results_df,
labelOfInterest = labelOfInterest,
feature_selected = feature_selected,
feature_importance = feature_importance)
return results_df
adata = read_h5ad('/Users/madelinepark/Downloads/Liver_droplet.h5ad')
scRFE (adata, classOfInterest = 'age', nEstimators = 10, Cv = 3)
```
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/practiceScripts/scRFEv1.4.2.ipynb
| 0.787114 | 0.846451 |
scRFEv1.4.2.ipynb
|
pypi
|
# Visualization: Venn Diagram
```
import numpy as np
import pandas as pd
import scanpy as sc
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from matplotlib import pyplot as plt
import matplotlib_venn
from matplotlib import pyplot as plt
from matplotlib_venn import venn2, venn3, venn3_circles
```
# Venn Diagram
```
# Read in SORTED results for each feature (ex: age)
# Highest gini scores and their corresponding genes at top, fill the column in descending order
sorted_24 = pd.read_csv('/Users/madelinepark/src2/maca-data-analysis/rf-rfe-results/cv_24m_facs_sorted.csv')
sorted_3 = pd.read_csv('/Users/madelinepark/src2/maca-data-analysis/rf-rfe-results/cv_3m_facs_sorted.csv')
# compare 3m vs 24m results
compare_3_24 = venn2([set(sorted_24['24m']), set(sorted_3['3m'])], set_labels=('3m','24m'))
```
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/practiceScripts/venn-diagram.ipynb
| 0.508544 | 0.665143 |
venn-diagram.ipynb
|
pypi
|
# scRFE
```
# madeline editting 06/22
# Imports
import numpy as np
import pandas as pd
import scanpy as sc
import random
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from sklearn.feature_selection import RFECV
import seaborn as sns
import matplotlib.pyplot as plt
import scanpy.external as sce
import logging as logg
def columnToString (dataMatrix):
cat_columns = dataMatrix.obs.select_dtypes(['category']).columns
dataMatrix.obs[cat_columns] = dataMatrix.obs[cat_columns].astype(str)
return dataMatrix
def filterNormalize (dataMatrix, classOfInterest):
np.random.seed(644685)
sc.pp.filter_cells(dataMatrix, min_genes=0)
sc.pp.filter_genes(dataMatrix, min_cells=0)
dataMatrix = dataMatrix[dataMatrix.obs[classOfInterest]!='nan']
dataMatrix = dataMatrix[~dataMatrix.obs[classOfInterest].isna()]
return dataMatrix
def labelSplit (dataMatrix, classOfInterest, labelOfInterest):
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
dataMatrix.obs['classification_group'] = 'B'
dataMatrix.obs.loc[dataMatrix.obs[dataMatrix.obs[classOfInterest]==labelOfInterest]
.index,'classification_group'] = 'A'
return dataMatrix
def downsampleToSmallestCategory(dataMatrix, random_state, min_cells, keep_small_categories,
classOfInterest = 'classification_group'
) -> sc.AnnData:
"""
returns an annData object in which all categories in 'classOfInterest' have
the same size
classOfInterest
column with the categories to downsample
min_cells
Minimum number of cells to downsample.
Categories having less than `min_cells` are discarded unless
keep_small_categories is True
keep_small_categories
Be default categories with less than min_cells are discarded.
Set to true to keep them
"""
print(min_cells)
counts = dataMatrix.obs[classOfInterest].value_counts(sort=False)
if len(counts[counts < min_cells]) > 0 and keep_small_categories is False:
logg.warning(
"The following categories have less than {} cells and will be "
"ignored: {}".format(min_cells, dict(counts[counts < min_cells]))
)
min_size = min(counts[counts >= min_cells])
sample_selection = None
for sample, num_cells in counts.items():
if num_cells <= min_cells:
if keep_small_categories:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample].index)
else:
continue
else:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample]
.sample(min_size, random_state=random_state)
.index
)
if sample_selection is None:
sample_selection = sel
else:
sample_selection |= sel
logg.info(
"The cells in category {!r} had been down-sampled to have each {} cells. "
"The original counts where {}".format(classOfInterest, min_size, dict(counts))
)
return dataMatrix[sample_selection].copy()
def makeOneForest (dataMatrix, classOfInterest, labelOfInterest, nEstimators = 5000,
randomState = 0, nJobs = -1, oobScore = True, Step = 0.2, Cv = 5):
"""
Builds and runs a random forest for one label in a class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
feature_selected : list
list of top features from random forest
selector.estimator_.feature_importances_ : list
list of top ginis corresponding to to features
"""
splitDataMatrix = labelSplit (dataMatrix, classOfInterest, labelOfInterest)
downsampledMatrix = downsampleToSmallestCategory (dataMatrix = splitDataMatrix,
classOfInterest = 'classification_group',
random_state = None, min_cells = 15, keep_small_categories = False)
feat_labels = downsampledMatrix.var_names
X = downsampledMatrix.X
y = downsampledMatrix.obs['classification_group']
clf = RandomForestClassifier(n_estimators = nEstimators, random_state = randomState,
n_jobs = nJobs, oob_score = oobScore)
selector = RFECV(clf, step = Step, cv = Cv)
clf.fit(X, y)
selector.fit(X, y)
feature_selected = feat_labels[selector.support_]
dataMatrix.obs['classification_group'] = 'B'
return feature_selected, selector.estimator_.feature_importances_
def resultWrite (classOfInterest, results_df, labelOfInterest,
feature_selected, feature_importance):
column_headings = []
column_headings.append(labelOfInterest)
column_headings.append(labelOfInterest + '_gini')
resaux = pd.DataFrame(columns = column_headings)
resaux[labelOfInterest] = feature_selected
resaux[labelOfInterest + '_gini'] = feature_importance
resaux = resaux.sort_values(by = [labelOfInterest + '_gini'], ascending = False)
resaux.reset_index(drop = True, inplace = True)
results_df = pd.concat([results_df, resaux], axis=1)
return results_df
def scRFE (adata, classOfInterest, nEstimators = 5000, randomState = 0,
nJobs = -1, oobScore = True, Step = 0.2, Cv = 5):
"""
Builds and runs a random forest with one vs all classification for each label
for one class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
results_df : pd.DataFrame
Dataframe with results for each label in the class, formatted as
"label" for one column, then "label + gini" for the corresponding column
"""
dataMatrix = adata.copy()
dataMatrix = columnToString (dataMatrix)
# print("Original dataset ", dataMatrix.shape)
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
# print("Filtered dataset ",dataMatrix.shape)
# print(pd.DataFrame(dataMatrix.obs.groupby([classOfInterest])[classOfInterest].count()))
results_df = pd.DataFrame()
for labelOfInterest in np.unique(dataMatrix.obs[classOfInterest]):
# print(labelOfInterest)
dataMatrix_labelOfInterest = dataMatrix.copy()
feature_selected, feature_importance = makeOneForest(dataMatrix_labelOfInterest,
classOfInterest,
labelOfInterest = labelOfInterest)
results_df = resultWrite (classOfInterest, results_df,
labelOfInterest = labelOfInterest,
feature_selected = feature_selected,
feature_importance = feature_importance)
return results_df
# liverTFAge = scRFE (adata = adataLiver, classOfInterest = 'age',
# nEstimators = 10, randomState = 0,
# nJobs = -1, oobScore = True, Step = 0.2, Cv = 3)
```
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/practiceScripts/scRFEjun24.ipynb
| 0.728652 | 0.868994 |
scRFEjun24.ipynb
|
pypi
|
# # scRFE
# In[154]:
# madeline editting 06/22
# In[186]:
# Imports
import numpy as np
import pandas as pd
import scanpy as sc
import random
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from sklearn.feature_selection import RFECV
import seaborn as sns
import matplotlib.pyplot as plt
import scanpy.external as sce
import logging as logg
# In[187]:
# adataLiver = read_h5ad('/Users/madelinepark/Downloads/Liver_droplet.h5ad')
# In[188]:
# mouse_tfs = pd.read_csv("/Users/madelinepark/Downloads/GO_term_summary_20171110_222852.csv")
# mouse_tfs.head()
# In[191]:
def columnToString (dataMatrix):
cat_columns = dataMatrix.obs.select_dtypes(['category']).columns
dataMatrix.obs[cat_columns] = dataMatrix.obs[cat_columns].astype(str)
return dataMatrix
# In[192]:
def filterNormalize (dataMatrix, classOfInterest):
np.random.seed(644685)
sc.pp.filter_cells(dataMatrix, min_genes=0)
sc.pp.filter_genes(dataMatrix, min_cells=0)
dataMatrix = dataMatrix[dataMatrix.obs[classOfInterest]!='nan']
dataMatrix = dataMatrix[~dataMatrix.obs[classOfInterest].isna()]
return dataMatrix
# In[193]:
def labelSplit (dataMatrix, classOfInterest, labelOfInterest):
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
dataMatrix.obs['classification_group'] = 'B'
dataMatrix.obs.loc[dataMatrix.obs[dataMatrix.obs[classOfInterest]==labelOfInterest]
.index,'classification_group'] = 'A'
return dataMatrix
# In[194]:
def downsampleToSmallestCategory(dataMatrix,
classOfInterest = 'classification_group',
random_state = None,
min_cells = 15,
keep_small_categories = True
) -> sc.AnnData:
"""
returns an annData object in which all categories in 'classOfInterest' have
the same size
classOfInterest
column with the categories to downsample
min_cells
Minimum number of cells to downsample.
Categories having less than `min_cells` are discarded unless
keep_small_categories is True
keep_small_categories
Be default categories with less than min_cells are discarded.
Set to true to keep them
"""
counts = dataMatrix.obs[classOfInterest].value_counts(sort=False)
if len(counts[counts < min_cells]) > 0 and keep_small_categories is False:
logg.warning(
"The following categories have less than {} cells and will be "
"ignored: {}".format(min_cells, dict(counts[counts < min_cells]))
)
min_size = min(counts[counts >= min_cells])
sample_selection = None
for sample, num_cells in counts.items():
if num_cells <= min_cells:
if keep_small_categories:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample].index)
else:
continue
else:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample]
.sample(min_size, random_state=random_state)
.index
)
if sample_selection is None:
sample_selection = sel
else:
sample_selection |= sel
logg.info(
"The cells in category {!r} had been down-sampled to have each {} cells. "
"The original counts where {}".format(classOfInterest, min_size, dict(counts))
)
return dataMatrix[sample_selection].copy()
# In[199]:
def makeOneForest (dataMatrix, classOfInterest, labelOfInterest, nEstimators = 5000,
randomState = 0, nJobs = -1, oobScore = True, Step = 0.2, Cv = 5):
"""
Builds and runs a random forest for one label in a class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
feature_selected : list
list of top features from random forest
selector.estimator_.feature_importances_ : list
list of top ginis corresponding to to features
"""
splitDataMatrix = labelSplit (dataMatrix, classOfInterest, labelOfInterest)
downsampledMatrix = downsampleToSmallestCategory (dataMatrix = splitDataMatrix,
classOfInterest = 'classification_group',
random_state = None, min_cells = 15, keep_small_categories = False)
feat_labels = downsampledMatrix.var_names
X = downsampledMatrix.X
y = downsampledMatrix.obs['classification_group']
clf = RandomForestClassifier(n_estimators = nEstimators, random_state = randomState,
n_jobs = nJobs, oob_score = oobScore)
selector = RFECV(clf, step = Step, cv = Cv)
clf.fit(X, y)
selector.fit(X, y)
feature_selected = feat_labels[selector.support_]
dataMatrix.obs['classification_group'] = 'B'
return feature_selected, selector.estimator_.feature_importances_
# In[200]:
def resultWrite (classOfInterest, results_df, labelOfInterest,
feature_selected, feature_importance):
column_headings = []
column_headings.append(labelOfInterest)
column_headings.append(labelOfInterest + '_gini')
resaux = pd.DataFrame(columns = column_headings)
resaux[labelOfInterest] = feature_selected
resaux[labelOfInterest + '_gini'] = feature_importance
resaux = resaux.sort_values(by = [labelOfInterest + '_gini'], ascending = False)
resaux.reset_index(drop = True, inplace = True)
results_df = pd.concat([results_df, resaux], axis=1)
return results_df
# In[201]:
def scRFE(adata, classOfInterest, nEstimators = 5000, randomState = 0,
nJobs = -1, oobScore = True, Step = 0.2, Cv = 5):
"""
Builds and runs a random forest with one vs all classification for each label
for one class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
results_df : pd.DataFrame
Dataframe with results for each label in the class, formatted as
"label" for one column, then "label + gini" for the corresponding column
"""
dataMatrix = adata.copy()
dataMatrix = columnToString (dataMatrix)
print("Original dataset ", dataMatrix.shape)
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
print("Filtered dataset ",dataMatrix.shape)
print(pd.DataFrame(dataMatrix.obs.groupby([classOfInterest])[classOfInterest].count()))
results_df = pd.DataFrame()
for labelOfInterest in np.unique(dataMatrix.obs[classOfInterest]):
print(labelOfInterest)
dataMatrix_labelOfInterest = dataMatrix.copy()
feature_selected, feature_importance = makeOneForest(dataMatrix_labelOfInterest,
classOfInterest,
labelOfInterest = labelOfInterest)
results_df = resultWrite (classOfInterest, results_df,
labelOfInterest = labelOfInterest,
feature_selected = feature_selected,
feature_importance = feature_importance)
return results_df
# In[ ]:
# liverTFAge = scRFE (adata = adataLiver, classOfInterest = 'age',
# nEstimators = 10, randomState = 0,
# nJobs = -1, oobScore = True, Step = 0.2, Cv = 3)
# In[ ]:
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/practiceScripts/scRFEjun24.py
| 0.67694 | 0.606469 |
scRFEjun24.py
|
pypi
|
# # scRFE
# In[3]:
# Imports
import numpy as np
import pandas as pd
import scanpy as sc
import random
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from sklearn.feature_selection import RFECV
import seaborn as sns
import matplotlib.pyplot as plt
import scanpy.external as sce
import logging as logg
# In[84]:
def columnToString (dataMatrix):
cat_columns = dataMatrix.obs.select_dtypes(['category']).columns
dataMatrix.obs[cat_columns] = dataMatrix.obs[cat_columns].astype(str)
return dataMatrix
# In[101]:
def filterNormalize (dataMatrix, classOfInterest):
np.random.seed(644685)
# sc.pp.filter_cells(dataMatrix, min_genes=0)
# sc.pp.filter_genes(dataMatrix, min_cells=0)
dataMatrix = dataMatrix[dataMatrix.obs[classOfInterest]!='nan']
dataMatrix = dataMatrix[~dataMatrix.obs[classOfInterest].isna()]
print ('na data removed')
return dataMatrix
# In[86]:
def labelSplit (dataMatrix, classOfInterest, labelOfInterest):
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
dataMatrix.obs['classification_group'] = 'B'
dataMatrix.obs.loc[dataMatrix.obs[dataMatrix.obs[classOfInterest]==labelOfInterest]
.index,'classification_group'] = 'A' #make labels based on A/B of
# classofInterest
return dataMatrix
# In[92]:
def downsampleToSmallestCategory(dataMatrix, random_state, min_cells,
keep_small_categories,
classOfInterest = 'classification_group',
) -> sc.AnnData:
"""
returns an annData object in which all categories in 'classOfInterest' have
the same size
classOfInterest
column with the categories to downsample
min_cells
Minimum number of cells to downsample.
Categories having less than `min_cells` are discarded unless
keep_small_categories is True
keep_small_categories
Be default categories with less than min_cells are discarded.
Set to true to keep them
"""
counts = dataMatrix.obs[classOfInterest].value_counts(sort=False)
if len(counts[counts < min_cells]) > 0 and keep_small_categories is False:
logg.warning(
"The following categories have less than {} cells and will be "
"ignored: {}".format(min_cells, dict(counts[counts < min_cells]))
)
min_size = min(counts[counts >= min_cells])
sample_selection = None
for sample, num_cells in counts.items():
if num_cells <= min_cells:
if keep_small_categories:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample].index)
else:
continue
else:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample]
.sample(min_size, random_state=random_state)
.index
)
if sample_selection is None:
sample_selection = sel
else:
sample_selection |= sel
logg.info(
"The cells in category {!r} had been down-sampled to have each {} cells. "
"The original counts where {}".format(classOfInterest, min_size, dict(counts))
)
return dataMatrix[sample_selection].copy()
# In[93]:
def makeOneForest (dataMatrix, classOfInterest, labelOfInterest, nEstimators,
randomState, min_cells, keep_small_categories,
nJobs, oobScore, Step, Cv):
"""
Builds and runs a random forest for one label in a class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
feature_selected : list
list of top features from random forest
selector.estimator_.feature_importances_ : list
list of top ginis corresponding to to features
"""
splitDataMatrix = labelSplit (dataMatrix, classOfInterest, labelOfInterest)
downsampledMatrix = downsampleToSmallestCategory (dataMatrix = splitDataMatrix,
random_state = randomState, min_cells = min_cells,
keep_small_categories = keep_small_categories,
classOfInterest = 'classification_group', )
feat_labels = downsampledMatrix.var_names
X = downsampledMatrix.X
y = downsampledMatrix.obs['classification_group'] #'A' or 'B' labels from labelSplit
clf = RandomForestClassifier(n_estimators = nEstimators, random_state = randomState,
n_jobs = nJobs, oob_score = oobScore)
selector = RFECV(clf, step = Step, cv = Cv)
clf.fit(X, y)
selector.fit(X, y)
feature_selected = feat_labels[selector.support_]
dataMatrix.obs['classification_group'] = 'B'
return feature_selected, selector.estimator_.feature_importances_
# In[94]:
def resultWrite (classOfInterest, results_df, labelOfInterest,
feature_selected, feature_importance):
column_headings = []
column_headings.append(labelOfInterest)
column_headings.append(labelOfInterest + '_gini')
resaux = pd.DataFrame(columns = column_headings)
resaux[labelOfInterest] = feature_selected
resaux[labelOfInterest + '_gini'] = feature_importance
resaux = resaux.sort_values(by = [labelOfInterest + '_gini'], ascending = False)
resaux.reset_index(drop = True, inplace = True)
results_df = pd.concat([results_df, resaux], axis=1)
return results_df
# In[99]:
def scRFE (adata, classOfInterest, nEstimators = 5000, randomState = 0, min_cells = 15,
keep_small_categories = True, nJobs = -1, oobScore = True, Step = 0.2, Cv = 5):
"""
Builds and runs a random forest with one vs all classification for each label
for one class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
min_cells : int
Minimum number of cells in a given class to downsample.
keep_small_categories : bool
Whether to keep classes with small number of observations, or to remove.
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
results_df : pd.DataFrame
Dataframe with results for each label in the class, formatted as
"label" for one column, then "label + gini" for the corresponding column
"""
dataMatrix = adata.copy()
dataMatrix = columnToString (dataMatrix)
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
results_df = pd.DataFrame()
for labelOfInterest in sorted(np.unique(dataMatrix.obs[classOfInterest])):
dataMatrix_labelOfInterest = dataMatrix.copy()
feature_selected, feature_importance = makeOneForest(
dataMatrix = dataMatrix_labelOfInterest, classOfInterest = classOfInterest,
labelOfInterest = labelOfInterest,
nEstimators = nEstimators, randomState = randomState, min_cells = min_cells,
keep_small_categories = keep_small_categories, nJobs = nJobs,
oobScore = oobScore, Step = Step, Cv = Cv)
results_df = resultWrite (classOfInterest, results_df,
labelOfInterest = labelOfInterest,
feature_selected = feature_selected,
feature_importance = feature_importance)
return results_df
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/practiceScripts/scRFEv1.4.2.py
| 0.7478 | 0.643721 |
scRFEv1.4.2.py
|
pypi
|
# scRFEjun19
```
# AnnDatasubset
# Angela sent to Madeline on June 22
# Imports
import numpy as np
import pandas as pd
import scanpy as sc
import random
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from sklearn.feature_selection import RFECV
import seaborn as sns
import matplotlib.pyplot as plt
import scanpy.external as sce
import logging as logg
mouse_tfs = pd.read_csv("/home/angela/maca/GO_term_summary_20171110_222852.csv")
mouse_tfs.head()
adata = read_h5ad(
"/home/angela/maca/tabula-muris-senis/0_data_ingest/01_figure_1/tabula-muris-senis-droplet-processed-official-annotations.h5ad")
adata
adata = adata[:,adata.var_names[adata.var_names.isin(mouse_tfs['Symbol'])]]
adata
# adataLiver = read_h5ad('/Users/madelinepark/Downloads/Liver_droplet.h5ad')
adataLiver = adata[adata.obs['tissue']=='Liver'].copy()
adataLiver
def remove_cats(adata):
cat_columns = adata.obs.select_dtypes(['category']).columns
adata.obs[cat_columns] = adata.obs[cat_columns].astype(str)
return adata
def filterNormalize (dataMatrix, classOfInterest):
np.random.seed(644685)
# sc.logging.print_versions()
# sc.settings.verbosity = 3
# sc.logging.print_versions()
# dataMatrix.obs['n_counts'] = dataMatrix.X.sum(axis=1).A1
sc.pp.filter_cells(dataMatrix, min_genes=0)
sc.pp.filter_genes(dataMatrix, min_cells=0)
# dataMatrix = dataMatrix[dataMatrix.obs['n_counts'] > 1500, :]
# sc.pp.normalize_per_cell(dataMatrix, counts_per_cell_after=1e5)
# sc.pp.log1p(dataMatrix)
# dataMatrix.raw = dataMatrix
dataMatrix = dataMatrix[dataMatrix.obs[classOfInterest]!='nan']
dataMatrix = dataMatrix[~dataMatrix.obs[classOfInterest].isna()]
return dataMatrix
def labelSplit (dataMatrix, classOfInterest, labelOfInterest):
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
dataMatrix.obs['classification_group'] = 'B'
dataMatrix.obs.loc[dataMatrix.obs[dataMatrix.obs[classOfInterest]==labelOfInterest]
.index,'classification_group'] = 'A'
return dataMatrix
def downsampleToSmallestCategory(dataMatrix,
classOfInterest = 'classification_group',
random_state = None,
min_cells = 15,
keep_small_categories = True
) -> sc.AnnData:
"""
returns an annData object in which all categories in 'classOfInterest' have
the same size
classOfInterest
column with the categories to downsample
min_cells
Minimum number of cells to downsample.
Categories having less than `min_cells` are discarded unless
keep_small_categories is True
keep_small_categories
Be default categories with less than min_cells are discarded.
Set to true to keep them
"""
counts = dataMatrix.obs[classOfInterest].value_counts(sort=False)
if len(counts[counts < min_cells]) > 0 and keep_small_categories is False:
logg.warning(
"The following categories have less than {} cells and will be "
"ignored: {}".format(min_cells, dict(counts[counts < min_cells]))
)
min_size = min(counts[counts >= min_cells])
sample_selection = None
for sample, num_cells in counts.items():
if num_cells <= min_cells:
if keep_small_categories:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample].index)
else:
continue
else:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample]
.sample(min_size, random_state=random_state)
.index
)
if sample_selection is None:
sample_selection = sel
else:
sample_selection |= sel
logg.info(
"The cells in category {!r} had been down-sampled to have each {} cells. "
"The original counts where {}".format(classOfInterest, min_size, dict(counts))
)
return dataMatrix[sample_selection].copy()
def makeOneForest (dataMatrix, classOfInterest, labelOfInterest, nEstimators = 5000,
randomState = 0, nJobs = -1, oobScore = True, Step = 0.2, Cv = 5):
"""
Builds and runs a random forest for one label in a class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
feature_selected : list
list of top features from random forest
selector.estimator_.feature_importances_ : list
list of top ginis corresponding to to features
"""
splitDataMatrix = labelSplit (dataMatrix, classOfInterest, labelOfInterest)
downsampledMatrix = downsampleToSmallestCategory (dataMatrix = splitDataMatrix,
classOfInterest = 'classification_group',
random_state = None, min_cells = 15, keep_small_categories = False)
print('downsampled Matrix')
# print("labelOfInterest")
print(pd.DataFrame(downsampledMatrix.obs.groupby(['classification_group',classOfInterest])[classOfInterest].count()))
# display (downsampledMatrix.obs['classification_group'])
# print(set(downsampledMatrix.obs['classification_group']))
feat_labels = downsampledMatrix.var_names
X = downsampledMatrix.X
y = downsampledMatrix.obs['classification_group']
clf = RandomForestClassifier(n_estimators = nEstimators, random_state = randomState,
n_jobs = nJobs, oob_score = oobScore)
selector = RFECV(clf, step = Step, cv = Cv)
clf.fit(X, y)
selector.fit(X, y)
feature_selected = feat_labels[selector.support_]
# display(downsampledMatrix.obs)
dataMatrix.obs['classification_group'] = 'B'
# print('corresponding')
# display(downsampledMatrix.obs)
return feature_selected, selector.estimator_.feature_importances_
def resultWrite (classOfInterest, results_df, labelOfInterest,
feature_selected, feature_importance):
column_headings = []
column_headings.append(labelOfInterest)
column_headings.append(labelOfInterest + '_gini')
resaux = pd.DataFrame(columns = column_headings)
resaux[labelOfInterest] = feature_selected
resaux[labelOfInterest + '_gini'] = feature_importance
resaux = resaux.sort_values(by = [labelOfInterest + '_gini'], ascending = False)
resaux.reset_index(drop = True, inplace = True)
results_df = pd.concat([results_df, resaux], axis=1)
return results_df
def scRFE(adata, classOfInterest, nEstimators = 5000, randomState = 0,
nJobs = -1, oobScore = True, Step = 0.2, Cv = 5):
"""
Builds and runs a random forest with one vs all classification for each label
for one class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
results_df : pd.DataFrame
Dataframe with results for each label in the class, formatted as
"label" for one column, then "label + gini" for the corresponding column
"""
dataMatrix = adata.copy()
dataMatrix = remove_cats(dataMatrix)
print("Original dataset ",dataMatrix.shape)
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
print("Filtered dataset ",dataMatrix.shape)
print(pd.DataFrame(dataMatrix.obs.groupby([classOfInterest])[classOfInterest].count()))
results_df = pd.DataFrame()
for labelOfInterest in np.unique(dataMatrix.obs[classOfInterest]):
print(labelOfInterest)
dataMatrix_labelOfInterest = dataMatrix.copy()
feature_selected, feature_importance = makeOneForest(dataMatrix_labelOfInterest,
classOfInterest,
labelOfInterest = labelOfInterest)
results_df = resultWrite (classOfInterest, results_df,
labelOfInterest = labelOfInterest,
feature_selected = feature_selected,
feature_importance = feature_importance)
# finaldf = makeOneForest (dataMatrix, classOfInterest, labelOfInterest = labelOfInterest)[2]
return results_df
senis_facs_tfs_age = scRFE (adata, classOfInterest = 'age',
nEstimators = 10, randomState = 0,
nJobs = -1, oobScore = True, Step = 0.2, Cv = 3)
adata
senis_facs_tfs_age
age = '24m'
sum(senis_droplet_tfs_age[age].isin(senis_facs_tfs_age[age]))/sum(~senis_droplet_tfs_age[age].isna())*100
sum(senis_facs_tfs_age['3m'].isin(senis_droplet_tfs_age['3m']))/sum(~senis_facs_tfs_age['3m'].isna())*100
sum(~senis_facs_tfs_age['3m'].isna()),sum(~senis_droplet_tfs_age['3m'].isna())
sum(senis_facs_tfs_age['3m'].isin(senis_droplet_tfs_age['3m']))
senis_droplet_tfs_age.to_csv("senis_droplet_tfs_age.csv")
senis_facs_tfs_age.to_csv("senis_facs_tfs_age.csv")
liverAgeSmallnorm = scRFE (dataMatrix = adataLiver, classOfInterest = 'age',
nEstimators = 10, randomState = 0,
nJobs = -1, oobScore = True, Step = 0.2, Cv = 3)
liverAgeSmall.to_csv("scRFE_Liver_droplet_age.csv")
liverAgeSmallnonorm
liverAgeSmallnorm.to_csv("scRFE_Liver_facs_age.csv")
```
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/practiceScripts/scRFE_jun19_FROMANGELA.ipynb
| 0.580233 | 0.803482 |
scRFE_jun19_FROMANGELA.ipynb
|
pypi
|
# Sorting Results
```
# Imports
import numpy as np
import pandas as pd
import scanpy as sc
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from sklearn.feature_selection import RFECV
cd scrfe test results
kidney_facs_1000_age = pd.read_csv('KidneyFacsAge1000TissReset.csv')
# kidney_facs_1000_age
def sortVals(df):
cols = df.columns.to_list()
print(cols[1])
return df.sort_values(by = cols[2], ascending=False)
sortVals(kidney_facs_1000_age)
kidney_facs_1000_cell = pd.read_csv('KidneyFacsCell1000TissReset.csv')
sortVals(kidney_facs_1000_cell).head()
heart_droplet_1000_age = pd.read_csv('HeartDropletAge1000TissReset.csv')
sortVals(heart_droplet_1000_age).head()
```
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/practiceScripts/SortingResults.ipynb
| 0.417509 | 0.525673 |
SortingResults.ipynb
|
pypi
|
# # scRFE
# In[3]:
# Imports
import numpy as np
import pandas as pd
import scanpy as sc
import random
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from sklearn.feature_selection import RFECV
import seaborn as sns
import matplotlib.pyplot as plt
import scanpy.external as sce
import logging as logg
# In[84]:
def columnToString (dataMatrix):
cat_columns = dataMatrix.obs.select_dtypes(['category']).columns
dataMatrix.obs[cat_columns] = dataMatrix.obs[cat_columns].astype(str)
return dataMatrix
# In[101]:
def filterNormalize (dataMatrix, classOfInterest):
np.random.seed(644685)
# sc.pp.filter_cells(dataMatrix, min_genes=0)
# sc.pp.filter_genes(dataMatrix, min_cells=0)
dataMatrix = dataMatrix[dataMatrix.obs[classOfInterest]!='nan']
dataMatrix = dataMatrix[~dataMatrix.obs[classOfInterest].isna()]
print ('na data removed')
return dataMatrix
# In[86]:
def labelSplit (dataMatrix, classOfInterest, labelOfInterest):
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
dataMatrix.obs['classification_group'] = 'B'
dataMatrix.obs.loc[dataMatrix.obs[dataMatrix.obs[classOfInterest]==labelOfInterest]
.index,'classification_group'] = 'A' #make labels based on A/B of
# classofInterest
return dataMatrix
# In[92]:
def downsampleToSmallestCategory(dataMatrix, random_state, min_cells,
keep_small_categories,
classOfInterest = 'classification_group',
) -> sc.AnnData:
"""
returns an annData object in which all categories in 'classOfInterest' have
the same size
classOfInterest
column with the categories to downsample
min_cells
Minimum number of cells to downsample.
Categories having less than `min_cells` are discarded unless
keep_small_categories is True
keep_small_categories
Be default categories with less than min_cells are discarded.
Set to true to keep them
"""
counts = dataMatrix.obs[classOfInterest].value_counts(sort=False)
if len(counts[counts < min_cells]) > 0 and keep_small_categories is False:
logg.warning(
"The following categories have less than {} cells and will be "
"ignored: {}".format(min_cells, dict(counts[counts < min_cells]))
)
min_size = min(counts[counts >= min_cells])
sample_selection = None
for sample, num_cells in counts.items():
if num_cells <= min_cells:
if keep_small_categories:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample].index)
else:
continue
else:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample]
.sample(min_size, random_state=random_state)
.index
)
if sample_selection is None:
sample_selection = sel
else:
sample_selection |= sel
logg.info(
"The cells in category {!r} had been down-sampled to have each {} cells. "
"The original counts where {}".format(classOfInterest, min_size, dict(counts))
)
return dataMatrix[sample_selection].copy()
# In[93]:
def makeOneForest (dataMatrix, classOfInterest, labelOfInterest, nEstimators,
randomState, min_cells, keep_small_categories,
nJobs, oobScore, Step, Cv):
"""
Builds and runs a random forest for one label in a class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
feature_selected : list
list of top features from random forest
selector.estimator_.feature_importances_ : list
list of top ginis corresponding to to features
"""
splitDataMatrix = labelSplit (dataMatrix, classOfInterest, labelOfInterest)
downsampledMatrix = downsampleToSmallestCategory (dataMatrix = splitDataMatrix,
random_state = randomState, min_cells = min_cells,
keep_small_categories = keep_small_categories,
classOfInterest = 'classification_group', )
feat_labels = downsampledMatrix.var_names
X = downsampledMatrix.X
y = downsampledMatrix.obs['classification_group'] #'A' or 'B' labels from labelSplit
clf = RandomForestClassifier(n_estimators = nEstimators, random_state = randomState,
n_jobs = nJobs, oob_score = oobScore)
selector = RFECV(clf, step = Step, cv = Cv)
clf.fit(X, y)
selector.fit(X, y)
feature_selected = feat_labels[selector.support_]
dataMatrix.obs['classification_group'] = 'B'
return feature_selected, selector.estimator_.feature_importances_
# In[94]:
def resultWrite (classOfInterest, results_df, labelOfInterest,
feature_selected, feature_importance):
column_headings = []
column_headings.append(labelOfInterest)
column_headings.append(labelOfInterest + '_gini')
resaux = pd.DataFrame(columns = column_headings)
resaux[labelOfInterest] = feature_selected
resaux[labelOfInterest + '_gini'] = feature_importance
resaux = resaux.sort_values(by = [labelOfInterest + '_gini'], ascending = False)
resaux.reset_index(drop = True, inplace = True)
results_df = pd.concat([results_df, resaux], axis=1)
return results_df
# In[99]:
def scRFE (adata, classOfInterest, nEstimators = 5000, randomState = 0, min_cells = 15,
keep_small_categories = True, nJobs = -1, oobScore = True, Step = 0.2, Cv = 5):
"""
Builds and runs a random forest with one vs all classification for each label
for one class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
min_cells : int
Minimum number of cells in a given class to downsample.
keep_small_categories : bool
Whether to keep classes with small number of observations, or to remove.
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
results_df : pd.DataFrame
Dataframe with results for each label in the class, formatted as
"label" for one column, then "label + gini" for the corresponding column
"""
dataMatrix = adata.copy()
dataMatrix = columnToString (dataMatrix)
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
results_df = pd.DataFrame()
for labelOfInterest in sorted(np.unique(dataMatrix.obs[classOfInterest])):
dataMatrix_labelOfInterest = dataMatrix.copy()
feature_selected, feature_importance = makeOneForest(
dataMatrix = dataMatrix_labelOfInterest, classOfInterest = classOfInterest,
labelOfInterest = labelOfInterest,
nEstimators = nEstimators, randomState = randomState, min_cells = min_cells,
keep_small_categories = keep_small_categories, nJobs = nJobs,
oobScore = oobScore, Step = Step, Cv = Cv)
results_df = resultWrite (classOfInterest, results_df,
labelOfInterest = labelOfInterest,
feature_selected = feature_selected,
feature_importance = feature_importance)
return results_df
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/practiceScripts/scRFEV142.py
| 0.811415 | 0.555496 |
scRFEV142.py
|
pypi
|
# # scRFE Tutorial
#
# Here we present an example of how to use scRFE. We analyze the Limb Muscle Facs data from the Tabula-Muris-Senis dataset that is available on Figshare. We split the data by age.
# More features were selected than ideal in this model, because we used a very small number of estimators and a low CV score, for time's sake. This results are not accurate though, and we recommend running the code with 1000 estimators and CV>=5 with an EC2 instance.
# ### Imports
# In[2]:
# Imports
import numpy as np
import pandas as pd
import scanpy as sc
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from sklearn.feature_selection import RFECV
# ### Read in anndata file
# In[3]:
adata = read_h5ad('/Users/madelinepark/Downloads/Limb_Muscle_facs.h5ad')
tiss = adata
# In[4]:
list(set(tiss.obs['age']))
# ### Run scRFE
# we decreased n_estimators and cv so that the code will run faster, but you should increase both before using
# In[5]:
tiss.obs['age_type_of_interest'] = 'rest'
results_age_cv = pd.DataFrame()
for c in list(set(tiss.obs['age'])):
print(c)
clf = RandomForestClassifier(n_estimators=10, random_state=0, n_jobs=-1, oob_score=True)
selector = RFECV(clf, step=0.2, cv=3, n_jobs=4) # step = % rounded down at each iteration
age_of_interest = c
tiss.obs.loc[tiss.obs[tiss.obs['age'] == age_of_interest].index,'age_type_of_interest'] = age_of_interest
feat_labels = tiss.var_names
X = tiss.X
y = tiss.obs['age_type_of_interest']
print('training...')
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.05, random_state=0)
clf.fit(X_train, y_train)
selector.fit(X_train, y_train)
print(type(feat_labels)) #adding this to test
feature_selected = feat_labels[selector.support_]
print('result writing')
column_headings = []
column_headings.append(c)
column_headings.append(c + '_gini')
resaux = pd.DataFrame(columns=column_headings)
resaux[c] = feature_selected
resaux[c + '_gini'] = (selector.estimator_.feature_importances_)
print(feature_selected)
print (selector.estimator_.feature_importances_)
results_age_cv = pd.concat([results_age_cv,resaux],axis=1)
tiss.obs['age_type_of_interest'] = 'rest'
results_age_cv
# In[ ]:
# In[ ]:
# In[ ]:
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/practiceScripts/scRFE-tutorial.py
| 0.509764 | 0.759805 |
scRFE-tutorial.py
|
pypi
|
# scRFE
```
# Imports
import numpy as np
import pandas as pd
import scanpy as sc
import random
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from sklearn.feature_selection import RFECV
import seaborn as sns
import matplotlib.pyplot as plt
import scanpy.external as sce
import logging as logg
def columnToString (dataMatrix):
cat_columns = dataMatrix.obs.select_dtypes(['category']).columns
dataMatrix.obs[cat_columns] = dataMatrix.obs[cat_columns].astype(str)
return dataMatrix
def filterNormalize (dataMatrix, classOfInterest):
np.random.seed(644685)
# sc.pp.filter_cells(dataMatrix, min_genes=0)
# sc.pp.filter_genes(dataMatrix, min_cells=0)
dataMatrix = dataMatrix[dataMatrix.obs[classOfInterest]!='nan']
dataMatrix = dataMatrix[~dataMatrix.obs[classOfInterest].isna()]
print ('na data removed')
return dataMatrix
def labelSplit (dataMatrix, classOfInterest, labelOfInterest):
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
dataMatrix.obs['classification_group'] = 'B'
dataMatrix.obs.loc[dataMatrix.obs[dataMatrix.obs[classOfInterest]==labelOfInterest]
.index,'classification_group'] = 'A' #make labels based on A/B of
# classofInterest
return dataMatrix
def downsampleToSmallestCategory(dataMatrix, random_state, min_cells,
keep_small_categories,
classOfInterest = 'classification_group',
) -> sc.AnnData:
"""
returns an annData object in which all categories in 'classOfInterest' have
the same size
classOfInterest
column with the categories to downsample
min_cells
Minimum number of cells to downsample.
Categories having less than `min_cells` are discarded unless
keep_small_categories is True
keep_small_categories
Be default categories with less than min_cells are discarded.
Set to true to keep them
"""
counts = dataMatrix.obs[classOfInterest].value_counts(sort=False)
if len(counts[counts < min_cells]) > 0 and keep_small_categories is False:
logg.warning(
"The following categories have less than {} cells and will be "
"ignored: {}".format(min_cells, dict(counts[counts < min_cells]))
)
min_size = min(counts[counts >= min_cells])
sample_selection = None
for sample, num_cells in counts.items():
if num_cells <= min_cells:
if keep_small_categories:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample].index)
else:
continue
else:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample]
.sample(min_size, random_state=random_state)
.index
)
if sample_selection is None:
sample_selection = sel
else:
sample_selection |= sel
logg.info(
"The cells in category {!r} had been down-sampled to have each {} cells. "
"The original counts where {}".format(classOfInterest, min_size, dict(counts))
)
return dataMatrix[sample_selection].copy()
def makeOneForest (dataMatrix, classOfInterest, labelOfInterest, nEstimators,
randomState, min_cells, keep_small_categories,
nJobs, oobScore, Step, Cv):
"""
Builds and runs a random forest for one label in a class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
feature_selected : list
list of top features from random forest
selector.estimator_.feature_importances_ : list
list of top ginis corresponding to to features
"""
splitDataMatrix = labelSplit (dataMatrix, classOfInterest, labelOfInterest)
downsampledMatrix = downsampleToSmallestCategory (dataMatrix = splitDataMatrix,
random_state = randomState, min_cells = min_cells,
keep_small_categories = keep_small_categories,
classOfInterest = 'classification_group', )
feat_labels = downsampledMatrix.var_names
X = downsampledMatrix.X
y = downsampledMatrix.obs['classification_group'] #'A' or 'B' labels from labelSplit
clf = RandomForestClassifier(n_estimators = nEstimators, random_state = randomState,
n_jobs = nJobs, oob_score = oobScore)
selector = RFECV(clf, step = Step, cv = Cv)
clf.fit(X, y)
selector.fit(X, y)
feature_selected = feat_labels[selector.support_]
dataMatrix.obs['classification_group'] = 'B'
return feature_selected, selector.estimator_.feature_importances_
def resultWrite (classOfInterest, results_df, labelOfInterest,
feature_selected, feature_importance):
column_headings = []
column_headings.append(labelOfInterest)
column_headings.append(labelOfInterest + '_gini')
resaux = pd.DataFrame(columns = column_headings)
resaux[labelOfInterest] = feature_selected
resaux[labelOfInterest + '_gini'] = feature_importance
resaux = resaux.sort_values(by = [labelOfInterest + '_gini'], ascending = False)
resaux.reset_index(drop = True, inplace = True)
results_df = pd.concat([results_df, resaux], axis=1)
return results_df
def scRFE (adata, classOfInterest, nEstimators = 5000, randomState = 0, min_cells = 15,
keep_small_categories = True, nJobs = -1, oobScore = True, Step = 0.2, Cv = 5):
"""
Builds and runs a random forest with one vs all classification for each label
for one class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
min_cells : int
Minimum number of cells in a given class to downsample.
keep_small_categories : bool
Whether to keep classes with small number of observations, or to remove.
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
results_df : pd.DataFrame
Dataframe with results for each label in the class, formatted as
"label" for one column, then "label + gini" for the corresponding column
"""
dataMatrix = adata.copy()
dataMatrix = columnToString (dataMatrix)
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
results_df = pd.DataFrame()
for labelOfInterest in sorted(np.unique(dataMatrix.obs[classOfInterest])):
dataMatrix_labelOfInterest = dataMatrix.copy()
feature_selected, feature_importance = makeOneForest(
dataMatrix = dataMatrix_labelOfInterest, classOfInterest = classOfInterest,
labelOfInterest = labelOfInterest,
nEstimators = nEstimators, randomState = randomState, min_cells = min_cells,
keep_small_categories = keep_small_categories, nJobs = nJobs,
oobScore = oobScore, Step = Step, Cv = Cv)
results_df = resultWrite (classOfInterest, results_df,
labelOfInterest = labelOfInterest,
feature_selected = feature_selected,
feature_importance = feature_importance)
return results_df
```
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/practiceScripts/scRFEdefaultParams.ipynb
| 0.760562 | 0.885483 |
scRFEdefaultParams.ipynb
|
pypi
|
# Visualization: Venn Diagram
```
import numpy as np
import pandas as pd
import scanpy as sc
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from matplotlib import pyplot as plt
import matplotlib_venn
from matplotlib import pyplot as plt
from matplotlib_venn import venn2, venn3, venn3_circles
```
# Venn Diagram
```
# Read in SORTED results for each feature (ex: age)
# Highest gini scores and their corresponding genes at top, fill the column in descending order
sorted_24 = pd.read_csv('/Users/madelinepark/src2/maca-data-analysis/rf-rfe-results/cv_24m_facs_sorted.csv')
sorted_3 = pd.read_csv('/Users/madelinepark/src2/maca-data-analysis/rf-rfe-results/cv_3m_facs_sorted.csv')
# compare 3m vs 24m results
compare_3_24 = venn2([set(sorted_24['24m']), set(sorted_3['3m'])], set_labels=('3m','24m'))
```
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/practiceScripts/.ipynb_checkpoints/venn-diagram-checkpoint.ipynb
| 0.508544 | 0.665143 |
venn-diagram-checkpoint.ipynb
|
pypi
|
```
# testing scRFE
from scRFE import scRFE
from scRFE import scRFEimplot
from scRFE.scRFE import makeOneForest
import numpy as np
import pandas as pd
from anndata import read_h5ad
adata = read_h5ad('/Users/madelinepark/Downloads/Liver_droplet.h5ad')
madeForest = makeOneForest(dataMatrix=adata, classOfInterest='age', labelOfInterest='3m', nEstimators=10,
randomState=0, min_cells=15, keep_small_categories=True,
nJobs=-1, oobScore=True, Step=0.2, Cv=3, verbosity=True)
type(madeForest[4])
from scRFE.scRFE import scRFEimplot
scRFEimplot(X_new=madeForest[3], y = madeForest[4])
```
# scRFE
```
# Imports
import numpy as np
import pandas as pd
import scanpy as sc
import random
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from sklearn.feature_selection import RFECV
import seaborn as sns
import matplotlib.pyplot as plt
import scanpy.external as sce
import logging as logg
adata = read_h5ad('/Users/madelinepark/Downloads/Liver_droplet.h5ad')
def columnToString (dataMatrix):
cat_columns = dataMatrix.obs.select_dtypes(['category']).columns
dataMatrix.obs[cat_columns] = dataMatrix.obs[cat_columns].astype(str)
return dataMatrix
def filterNormalize (dataMatrix, classOfInterest, verbosity):
np.random.seed(644685)
# sc.pp.filter_cells(dataMatrix, min_genes=0)
# sc.pp.filter_genes(dataMatrix, min_cells=0)
dataMatrix = dataMatrix[dataMatrix.obs[classOfInterest]!='nan']
dataMatrix = dataMatrix[~dataMatrix.obs[classOfInterest].isna()]
if verbosity == True:
print ('na data removed')
return dataMatrix
filterNormalize(dataMatrix = adata, classOfInterest = 'age', verbosity = True)
def labelSplit (dataMatrix, classOfInterest, labelOfInterest, verbosity):
dataMatrix = filterNormalize (dataMatrix, classOfInterest, verbosity)
dataMatrix.obs['classification_group'] = 'B'
dataMatrix.obs.loc[dataMatrix.obs[dataMatrix.obs[classOfInterest]==labelOfInterest]
.index,'classification_group'] = 'A' #make labels based on A/B of
# classofInterest
return dataMatrix
def downsampleToSmallestCategory(dataMatrix, random_state, min_cells,
keep_small_categories, verbosity,
classOfInterest = 'classification_group'
) -> sc.AnnData:
"""
returns an annData object in which all categories in 'classOfInterest' have
the same size
classOfInterest
column with the categories to downsample
min_cells
Minimum number of cells to downsample.
Categories having less than `min_cells` are discarded unless
keep_small_categories is True
keep_small_categories
Be default categories with less than min_cells are discarded.
Set to true to keep them
"""
counts = dataMatrix.obs[classOfInterest].value_counts(sort=False)
if len(counts[counts < min_cells]) > 0 and keep_small_categories is False:
logg.warning(
"The following categories have less than {} cells and will be "
"ignored: {}".format(min_cells, dict(counts[counts < min_cells]))
)
min_size = min(counts[counts >= min_cells])
sample_selection = None
for sample, num_cells in counts.items():
if num_cells <= min_cells:
if keep_small_categories:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample].index)
else:
continue
else:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample]
.sample(min_size, random_state=random_state)
.index
)
if sample_selection is None:
sample_selection = sel
else:
sample_selection |= sel
logg.info(
"The cells in category {!r} had been down-sampled to have each {} cells. "
"The original counts where {}".format(classOfInterest, min_size, dict(counts))
)
return dataMatrix[sample_selection].copy()
def makeOneForest (dataMatrix, classOfInterest, labelOfInterest, nEstimators,
randomState, min_cells, keep_small_categories,
nJobs, oobScore, Step, Cv, verbosity):
"""
Builds and runs a random forest for one label in a class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
feature_selected : list
list of top features from random forest
selector.estimator_.feature_importances_ : list
list of top ginis corresponding to to features
"""
splitDataMatrix = labelSplit (dataMatrix, classOfInterest, labelOfInterest, verbosity)
downsampledMatrix = downsampleToSmallestCategory (dataMatrix = splitDataMatrix,
random_state = randomState, min_cells = min_cells,
keep_small_categories = keep_small_categories, verbosity = verbosity,
classOfInterest = 'classification_group', )
feat_labels = downsampledMatrix.var_names
X = downsampledMatrix.X
y = downsampledMatrix.obs['classification_group'] #'A' or 'B' labels from labelSplit
clf = RandomForestClassifier(n_estimators = nEstimators, random_state = randomState,
n_jobs = nJobs, oob_score = oobScore)
selector = RFECV(clf, step = Step, cv = Cv)
clf.fit(X, y)
selector.fit(X, y)
feature_selected = feat_labels[selector.support_]
dataMatrix.obs['classification_group'] = 'B'
return feature_selected, selector.estimator_.feature_importances_
def resultWrite (classOfInterest, results_df, labelOfInterest,
feature_selected, feature_importance):
column_headings = []
column_headings.append(labelOfInterest)
column_headings.append(labelOfInterest + '_gini')
resaux = pd.DataFrame(columns = column_headings)
resaux[labelOfInterest] = feature_selected
resaux[labelOfInterest + '_gini'] = feature_importance
resaux = resaux.sort_values(by = [labelOfInterest + '_gini'], ascending = False)
resaux.reset_index(drop = True, inplace = True)
results_df = pd.concat([results_df, resaux], axis=1)
return results_df
def scRFE (adata, classOfInterest, nEstimators = 5000, randomState = 0, min_cells = 15,
keep_small_categories = True, nJobs = -1, oobScore = True, Step = 0.2, Cv = 5,
verbosity = True):
"""
Builds and runs a random forest with one vs all classification for each label
for one class of interest
Parameters
----------
adata : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
min_cells : int
Minimum number of cells in a given class to downsample.
keep_small_categories : bool
Whether to keep classes with small number of observations, or to remove.
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
results_df : pd.DataFrame
Dataframe with results for each label in the class, formatted as
"label" for one column, then "label + gini" for the corresponding column
"""
dataMatrix = adata.copy()
dataMatrix = columnToString (dataMatrix)
dataMatrix = filterNormalize (dataMatrix, classOfInterest, verbosity)
results_df = pd.DataFrame()
for labelOfInterest in np.unique(dataMatrix.obs[classOfInterest]):
dataMatrix_labelOfInterest = dataMatrix.copy()
feature_selected, feature_importance = makeOneForest(
dataMatrix = dataMatrix_labelOfInterest, classOfInterest = classOfInterest,
labelOfInterest = labelOfInterest,
nEstimators = nEstimators, randomState = randomState, min_cells = min_cells,
keep_small_categories = keep_small_categories, nJobs = nJobs,
oobScore = oobScore, Step = Step, Cv = Cv, verbosity=verbosity)
results_df = resultWrite (classOfInterest, results_df,
labelOfInterest = labelOfInterest,
feature_selected = feature_selected,
feature_importance = feature_importance)
return results_df
adata = read_h5ad('/Users/madelinepark/Downloads/Liver_droplet.h5ad')
scRFE (adata, classOfInterest = 'age', nEstimators = 10, Cv = 3)
import logging
logging.info('%s before you %s', 'Look', 'leap!')
def logprint (verbosity):
if verbosity == True:
print('hi')
logprint(verbosity=True)
```
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/practiceScripts/.ipynb_checkpoints/scRFE-Copy1-checkpoint.ipynb
| 0.624064 | 0.739822 |
scRFE-Copy1-checkpoint.ipynb
|
pypi
|
# Sorting Results
```
# Imports
import numpy as np
import pandas as pd
import scanpy as sc
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from sklearn.feature_selection import RFECV
cd scrfe test results
kidney_facs_1000_age = pd.read_csv('KidneyFacsAge1000TissReset.csv')
# kidney_facs_1000_age
def sortVals(df):
cols = df.columns.to_list()
print(cols[1])
return df.sort_values(by = cols[2], ascending=False)
sortVals(kidney_facs_1000_age)
kidney_facs_1000_cell = pd.read_csv('KidneyFacsCell1000TissReset.csv')
sortVals(kidney_facs_1000_cell).head()
heart_droplet_1000_age = pd.read_csv('HeartDropletAge1000TissReset.csv')
sortVals(heart_droplet_1000_age).head()
```
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/practiceScripts/.ipynb_checkpoints/SortingResults-checkpoint.ipynb
| 0.417509 | 0.525673 |
SortingResults-checkpoint.ipynb
|
pypi
|
# scRFE
```
# Imports
import numpy as np
import pandas as pd
import scanpy as sc
import random
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from sklearn.feature_selection import RFECV
import seaborn as sns
import matplotlib.pyplot as plt
import scanpy.external as sce
import logging as logg
def columnToString (dataMatrix):
cat_columns = dataMatrix.obs.select_dtypes(['category']).columns
dataMatrix.obs[cat_columns] = dataMatrix.obs[cat_columns].astype(str)
return dataMatrix
def filterNormalize (dataMatrix, classOfInterest):
np.random.seed(644685)
# sc.pp.filter_cells(dataMatrix, min_genes=0)
# sc.pp.filter_genes(dataMatrix, min_cells=0)
dataMatrix = dataMatrix[dataMatrix.obs[classOfInterest]!='nan']
dataMatrix = dataMatrix[~dataMatrix.obs[classOfInterest].isna()]
print ('na data removed')
return dataMatrix
def labelSplit (dataMatrix, classOfInterest, labelOfInterest):
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
dataMatrix.obs['classification_group'] = 'B'
dataMatrix.obs.loc[dataMatrix.obs[dataMatrix.obs[classOfInterest]==labelOfInterest]
.index,'classification_group'] = 'A' #make labels based on A/B of
# classofInterest
return dataMatrix
def downsampleToSmallestCategory(dataMatrix, random_state, min_cells,
keep_small_categories,
classOfInterest = 'classification_group',
) -> sc.AnnData:
"""
returns an annData object in which all categories in 'classOfInterest' have
the same size
classOfInterest
column with the categories to downsample
min_cells
Minimum number of cells to downsample.
Categories having less than `min_cells` are discarded unless
keep_small_categories is True
keep_small_categories
Be default categories with less than min_cells are discarded.
Set to true to keep them
"""
counts = dataMatrix.obs[classOfInterest].value_counts(sort=False)
if len(counts[counts < min_cells]) > 0 and keep_small_categories is False:
logg.warning(
"The following categories have less than {} cells and will be "
"ignored: {}".format(min_cells, dict(counts[counts < min_cells]))
)
min_size = min(counts[counts >= min_cells])
sample_selection = None
for sample, num_cells in counts.items():
if num_cells <= min_cells:
if keep_small_categories:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample].index)
else:
continue
else:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample]
.sample(min_size, random_state=random_state)
.index
)
if sample_selection is None:
sample_selection = sel
else:
sample_selection |= sel
logg.info(
"The cells in category {!r} had been down-sampled to have each {} cells. "
"The original counts where {}".format(classOfInterest, min_size, dict(counts))
)
return dataMatrix[sample_selection].copy()
def makeOneForest (dataMatrix, classOfInterest, labelOfInterest, nEstimators,
randomState, min_cells, keep_small_categories,
nJobs, oobScore, Step, Cv):
"""
Builds and runs a random forest for one label in a class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
feature_selected : list
list of top features from random forest
selector.estimator_.feature_importances_ : list
list of top ginis corresponding to to features
"""
splitDataMatrix = labelSplit (dataMatrix, classOfInterest, labelOfInterest)
downsampledMatrix = downsampleToSmallestCategory (dataMatrix = splitDataMatrix,
random_state = randomState, min_cells = min_cells,
keep_small_categories = keep_small_categories,
classOfInterest = 'classification_group', )
feat_labels = downsampledMatrix.var_names
X = downsampledMatrix.X
y = downsampledMatrix.obs['classification_group'] #'A' or 'B' labels from labelSplit
clf = RandomForestClassifier(n_estimators = nEstimators, random_state = randomState,
n_jobs = nJobs, oob_score = oobScore)
selector = RFECV(clf, step = Step, cv = Cv)
clf.fit(X, y)
selector.fit(X, y)
feature_selected = feat_labels[selector.support_]
dataMatrix.obs['classification_group'] = 'B'
return feature_selected, selector.estimator_.feature_importances_
def resultWrite (classOfInterest, results_df, labelOfInterest,
feature_selected, feature_importance):
column_headings = []
column_headings.append(labelOfInterest)
column_headings.append(labelOfInterest + '_gini')
resaux = pd.DataFrame(columns = column_headings)
resaux[labelOfInterest] = feature_selected
resaux[labelOfInterest + '_gini'] = feature_importance
resaux = resaux.sort_values(by = [labelOfInterest + '_gini'], ascending = False)
resaux.reset_index(drop = True, inplace = True)
results_df = pd.concat([results_df, resaux], axis=1)
return results_df
def scRFE (adata, classOfInterest, nEstimators = 5000, randomState = 0, min_cells = 15,
keep_small_categories = True, nJobs = -1, oobScore = True, Step = 0.2, Cv = 5):
"""
Builds and runs a random forest with one vs all classification for each label
for one class of interest
Parameters
----------
adata : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
min_cells : int
Minimum number of cells in a given class to downsample.
keep_small_categories : bool
Whether to keep classes with small number of observations, or to remove.
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
results_df : pd.DataFrame
Dataframe with results for each label in the class, formatted as
"label" for one column, then "label + gini" for the corresponding column
"""
dataMatrix = adata.copy()
dataMatrix = columnToString (dataMatrix)
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
results_df = pd.DataFrame()
for labelOfInterest in np.unique(dataMatrix.obs[classOfInterest]):
dataMatrix_labelOfInterest = dataMatrix.copy()
feature_selected, feature_importance = makeOneForest(
dataMatrix = dataMatrix_labelOfInterest, classOfInterest = classOfInterest,
labelOfInterest = labelOfInterest,
nEstimators = nEstimators, randomState = randomState, min_cells = min_cells,
keep_small_categories = keep_small_categories, nJobs = nJobs,
oobScore = oobScore, Step = Step, Cv = Cv)
results_df = resultWrite (classOfInterest, results_df,
labelOfInterest = labelOfInterest,
feature_selected = feature_selected,
feature_importance = feature_importance)
return results_df
adata = read_h5ad('/Users/madelinepark/Downloads/Liver_droplet.h5ad')
scRFE (adata, classOfInterest = 'age', nEstimators = 10, Cv = 3)
```
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/practiceScripts/.ipynb_checkpoints/scRFEv1.4.2-checkpoint.ipynb
| 0.787114 | 0.846451 |
scRFEv1.4.2-checkpoint.ipynb
|
pypi
|
## Matrix plots July 16
```
import numpy as np
import pandas as pd
import scanpy as sc
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from matplotlib import pyplot as plt
sc.settings.verbosity = 3 # verbosity: errors (0), warnings (1), info (2), hints (3)
sc.logging.print_versions()
#results_file = './write/pbmc3k.h5ad' # the file that will store the analysis results, change this
#does the results file have to be h5ad?
```
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/visualization/matrixPlotsJul16.ipynb
| 0.596668 | 0.5526 |
matrixPlotsJul16.ipynb
|
pypi
|
# scRFE
```
# Imports
import numpy as np
import pandas as pd
import scanpy as sc
import random
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from sklearn.feature_selection import RFECV
import seaborn as sns
import matplotlib.pyplot as plt
import scanpy.external as sce
import logging as logg
def columnToString (dataMatrix):
cat_columns = dataMatrix.obs.select_dtypes(['category']).columns
dataMatrix.obs[cat_columns] = dataMatrix.obs[cat_columns].astype(str)
return dataMatrix
def filterNormalize (dataMatrix, classOfInterest):
np.random.seed(644685)
# sc.pp.filter_cells(dataMatrix, min_genes=0)
# sc.pp.filter_genes(dataMatrix, min_cells=0)
dataMatrix = dataMatrix[dataMatrix.obs[classOfInterest]!='nan']
dataMatrix = dataMatrix[~dataMatrix.obs[classOfInterest].isna()]
print ('na data removed')
return dataMatrix
def labelSplit (dataMatrix, classOfInterest, labelOfInterest):
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
dataMatrix.obs['classification_group'] = 'B'
dataMatrix.obs.loc[dataMatrix.obs[dataMatrix.obs[classOfInterest]==labelOfInterest]
.index,'classification_group'] = 'A' #make labels based on A/B of
# classofInterest
return dataMatrix
def downsampleToSmallestCategory(dataMatrix, random_state, min_cells,
keep_small_categories,
classOfInterest = 'classification_group',
) -> sc.AnnData:
"""
returns an annData object in which all categories in 'classOfInterest' have
the same size
classOfInterest
column with the categories to downsample
min_cells
Minimum number of cells to downsample.
Categories having less than `min_cells` are discarded unless
keep_small_categories is True
keep_small_categories
Be default categories with less than min_cells are discarded.
Set to true to keep them
"""
counts = dataMatrix.obs[classOfInterest].value_counts(sort=False)
if len(counts[counts < min_cells]) > 0 and keep_small_categories is False:
logg.warning(
"The following categories have less than {} cells and will be "
"ignored: {}".format(min_cells, dict(counts[counts < min_cells]))
)
min_size = min(counts[counts >= min_cells])
sample_selection = None
for sample, num_cells in counts.items():
if num_cells <= min_cells:
if keep_small_categories:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample].index)
else:
continue
else:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample]
.sample(min_size, random_state=random_state)
.index
)
if sample_selection is None:
sample_selection = sel
else:
sample_selection |= sel
logg.info(
"The cells in category {!r} had been down-sampled to have each {} cells. "
"The original counts where {}".format(classOfInterest, min_size, dict(counts))
)
return dataMatrix[sample_selection].copy()
def makeOneForest (dataMatrix, classOfInterest, labelOfInterest, nEstimators,
randomState, min_cells, keep_small_categories,
nJobs, oobScore, Step, Cv):
"""
Builds and runs a random forest for one label in a class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
feature_selected : list
list of top features from random forest
selector.estimator_.feature_importances_ : list
list of top ginis corresponding to to features
"""
splitDataMatrix = labelSplit (dataMatrix, classOfInterest, labelOfInterest)
downsampledMatrix = downsampleToSmallestCategory (dataMatrix = splitDataMatrix,
random_state = randomState, min_cells = min_cells,
keep_small_categories = keep_small_categories,
classOfInterest = 'classification_group', )
feat_labels = downsampledMatrix.var_names
X = downsampledMatrix.X
y = downsampledMatrix.obs['classification_group'] #'A' or 'B' labels from labelSplit
clf = RandomForestClassifier(n_estimators = nEstimators, random_state = randomState,
n_jobs = nJobs, oob_score = oobScore)
selector = RFECV(clf, step = Step, cv = Cv)
clf.fit(X, y)
selector.fit(X, y)
feature_selected = feat_labels[selector.support_]
dataMatrix.obs['classification_group'] = 'B'
return feature_selected, selector.estimator_.feature_importances_
def resultWrite (classOfInterest, results_df, labelOfInterest,
feature_selected, feature_importance):
column_headings = []
column_headings.append(labelOfInterest)
column_headings.append(labelOfInterest + '_gini')
resaux = pd.DataFrame(columns = column_headings)
resaux[labelOfInterest] = feature_selected
resaux[labelOfInterest + '_gini'] = feature_importance
resaux = resaux.sort_values(by = [labelOfInterest + '_gini'], ascending = False)
resaux.reset_index(drop = True, inplace = True)
results_df = pd.concat([results_df, resaux], axis=1)
return results_df
def scRFE (adata, classOfInterest, nEstimators = 5000, randomState = 0, min_cells = 15,
keep_small_categories = True, nJobs = -1, oobScore = True, Step = 0.2, Cv = 5):
"""
Builds and runs a random forest with one vs all classification for each label
for one class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
min_cells : int
Minimum number of cells in a given class to downsample.
keep_small_categories : bool
Whether to keep classes with small number of observations, or to remove.
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
results_df : pd.DataFrame
Dataframe with results for each label in the class, formatted as
"label" for one column, then "label + gini" for the corresponding column
"""
dataMatrix = adata.copy()
dataMatrix = columnToString (dataMatrix)
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
results_df = pd.DataFrame()
for labelOfInterest in sorted(np.unique(dataMatrix.obs[classOfInterest])):
dataMatrix_labelOfInterest = dataMatrix.copy()
feature_selected, feature_importance = makeOneForest(
dataMatrix = dataMatrix_labelOfInterest, classOfInterest = classOfInterest,
labelOfInterest = labelOfInterest,
nEstimators = nEstimators, randomState = randomState, min_cells = min_cells,
keep_small_categories = keep_small_categories, nJobs = nJobs,
oobScore = oobScore, Step = Step, Cv = Cv)
results_df = resultWrite (classOfInterest, results_df,
labelOfInterest = labelOfInterest,
feature_selected = feature_selected,
feature_importance = feature_importance)
return results_df
```
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/.ipynb_checkpoints/scRFEdefaultParams-checkpoint.ipynb
| 0.760562 | 0.885483 |
scRFEdefaultParams-checkpoint.ipynb
|
pypi
|
# scRFE
```
# madeline editting 06/22
# Imports
import numpy as np
import pandas as pd
import scanpy as sc
import random
from anndata import read_h5ad
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from sklearn.feature_selection import RFECV
import seaborn as sns
import matplotlib.pyplot as plt
import scanpy.external as sce
import logging as logg
def columnToString (dataMatrix):
cat_columns = dataMatrix.obs.select_dtypes(['category']).columns
dataMatrix.obs[cat_columns] = dataMatrix.obs[cat_columns].astype(str)
return dataMatrix
def filterNormalize (dataMatrix, classOfInterest):
np.random.seed(644685)
sc.pp.filter_cells(dataMatrix, min_genes=0)
sc.pp.filter_genes(dataMatrix, min_cells=0)
dataMatrix = dataMatrix[dataMatrix.obs[classOfInterest]!='nan']
dataMatrix = dataMatrix[~dataMatrix.obs[classOfInterest].isna()]
return dataMatrix
def labelSplit (dataMatrix, classOfInterest, labelOfInterest):
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
dataMatrix.obs['classification_group'] = 'B'
dataMatrix.obs.loc[dataMatrix.obs[dataMatrix.obs[classOfInterest]==labelOfInterest]
.index,'classification_group'] = 'A'
return dataMatrix
def downsampleToSmallestCategory(dataMatrix, random_state, min_cells, keep_small_categories,
classOfInterest = 'classification_group'
) -> sc.AnnData:
"""
returns an annData object in which all categories in 'classOfInterest' have
the same size
classOfInterest
column with the categories to downsample
min_cells
Minimum number of cells to downsample.
Categories having less than `min_cells` are discarded unless
keep_small_categories is True
keep_small_categories
Be default categories with less than min_cells are discarded.
Set to true to keep them
"""
print(min_cells)
counts = dataMatrix.obs[classOfInterest].value_counts(sort=False)
if len(counts[counts < min_cells]) > 0 and keep_small_categories is False:
logg.warning(
"The following categories have less than {} cells and will be "
"ignored: {}".format(min_cells, dict(counts[counts < min_cells]))
)
min_size = min(counts[counts >= min_cells])
sample_selection = None
for sample, num_cells in counts.items():
if num_cells <= min_cells:
if keep_small_categories:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample].index)
else:
continue
else:
sel = dataMatrix.obs.index.isin(
dataMatrix.obs[dataMatrix.obs[classOfInterest] == sample]
.sample(min_size, random_state=random_state)
.index
)
if sample_selection is None:
sample_selection = sel
else:
sample_selection |= sel
logg.info(
"The cells in category {!r} had been down-sampled to have each {} cells. "
"The original counts where {}".format(classOfInterest, min_size, dict(counts))
)
return dataMatrix[sample_selection].copy()
def makeOneForest (dataMatrix, classOfInterest, labelOfInterest, nEstimators = 5000,
randomState = 0, nJobs = -1, oobScore = True, Step = 0.2, Cv = 5):
"""
Builds and runs a random forest for one label in a class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
feature_selected : list
list of top features from random forest
selector.estimator_.feature_importances_ : list
list of top ginis corresponding to to features
"""
splitDataMatrix = labelSplit (dataMatrix, classOfInterest, labelOfInterest)
downsampledMatrix = downsampleToSmallestCategory (dataMatrix = splitDataMatrix,
classOfInterest = 'classification_group',
random_state = None, min_cells = 15, keep_small_categories = False)
feat_labels = downsampledMatrix.var_names
X = downsampledMatrix.X
y = downsampledMatrix.obs['classification_group']
clf = RandomForestClassifier(n_estimators = nEstimators, random_state = randomState,
n_jobs = nJobs, oob_score = oobScore)
selector = RFECV(clf, step = Step, cv = Cv)
clf.fit(X, y)
selector.fit(X, y)
feature_selected = feat_labels[selector.support_]
dataMatrix.obs['classification_group'] = 'B'
return feature_selected, selector.estimator_.feature_importances_
def resultWrite (classOfInterest, results_df, labelOfInterest,
feature_selected, feature_importance):
column_headings = []
column_headings.append(labelOfInterest)
column_headings.append(labelOfInterest + '_gini')
resaux = pd.DataFrame(columns = column_headings)
resaux[labelOfInterest] = feature_selected
resaux[labelOfInterest + '_gini'] = feature_importance
resaux = resaux.sort_values(by = [labelOfInterest + '_gini'], ascending = False)
resaux.reset_index(drop = True, inplace = True)
results_df = pd.concat([results_df, resaux], axis=1)
return results_df
def scRFE (adata, classOfInterest, nEstimators = 5000, randomState = 0,
nJobs = -1, oobScore = True, Step = 0.2, Cv = 5):
"""
Builds and runs a random forest with one vs all classification for each label
for one class of interest
Parameters
----------
dataMatrix : anndata object
The data file of interest
classOfInterest : str
The class you will split the data by in the set of dataMatrix.obs
labelOfInterest : str
The specific label within the class that the random forezt will run a
"one vs all" classification on
nEstimators : int
The number of trees in the forest
randomState : int
Controls random number being used
nJobs : int
The number of jobs to run in parallel
oobScore : bool
Whether to use out-of-bag samples to estimate the generalization accuracy
Step : float
Corresponds to percentage of features to remove at each iteration
Cv : int
Determines the cross-validation splitting strategy
Returns
-------
results_df : pd.DataFrame
Dataframe with results for each label in the class, formatted as
"label" for one column, then "label + gini" for the corresponding column
"""
dataMatrix = adata.copy()
dataMatrix = columnToString (dataMatrix)
# print("Original dataset ", dataMatrix.shape)
dataMatrix = filterNormalize (dataMatrix, classOfInterest)
# print("Filtered dataset ",dataMatrix.shape)
# print(pd.DataFrame(dataMatrix.obs.groupby([classOfInterest])[classOfInterest].count()))
results_df = pd.DataFrame()
for labelOfInterest in np.unique(dataMatrix.obs[classOfInterest]):
# print(labelOfInterest)
dataMatrix_labelOfInterest = dataMatrix.copy()
feature_selected, feature_importance = makeOneForest(dataMatrix_labelOfInterest,
classOfInterest,
labelOfInterest = labelOfInterest)
results_df = resultWrite (classOfInterest, results_df,
labelOfInterest = labelOfInterest,
feature_selected = feature_selected,
feature_importance = feature_importance)
return results_df
# liverTFAge = scRFE (adata = adataLiver, classOfInterest = 'age',
# nEstimators = 10, randomState = 0,
# nJobs = -1, oobScore = True, Step = 0.2, Cv = 3)
```
|
/scRFE-1.5.6.tar.gz/scRFE-1.5.6/scripts/.ipynb_checkpoints/scRFEjun24-checkpoint.ipynb
| 0.728652 | 0.868994 |
scRFEjun24-checkpoint.ipynb
|
pypi
|
from time import time
import os
import torch
from torch_geometric.data import InMemoryDataset, Data
from collections import defaultdict
import episcanpy.api as epi
import scanpy as sc
import numpy as np
import pandas as pd
import anndata as ad
from anndata import AnnData
from typing import Optional, Mapping, List, Union
from scipy import sparse
import sklearn
import cosg
import pickle
import random
def tfidf(X: Union[np.ndarray, sparse.spmatrix]) -> Union[np.ndarray, sparse.spmatrix]:
r"""
TF-IDF normalization (following the Seurat v3 approach)
Parameters
----------
X
Input matrix
Returns
-------
X_tfidf
TF-IDF normalized matrix
"""
idf = X.shape[0] / X.sum(axis=0)
if sparse.issparse(X):
tf = X.multiply(1 / X.sum(axis=1))
return tf.multiply(idf)
else:
tf = X / X.sum(axis=1, keepdims=True)
return tf * idf
def lsi(
adata: AnnData, n_components: int = 20,
use_highly_variable: Optional[bool] = None, **kwargs
) -> None:
r"""
LSI analysis (following the Seurat v3 approach)
Parameters
----------
adata
Input dataset
n_components
Number of dimensions to use
use_highly_variable
Whether to use highly variable features only, stored in
``adata.var['highly_variable']``. By default uses them if they
have been determined beforehand.
**kwargs
Additional keyword arguments are passed to
:func:`sklearn.utils.extmath.randomized_svd`
"""
if "random_state" not in kwargs:
kwargs["random_state"] = 0 # Keep deterministic as the default behavior
if use_highly_variable is None:
use_highly_variable = "highly_variable" in adata.var
adata_use = adata[:, adata.var["highly_variable"]] if use_highly_variable else adata
X = tfidf(adata_use.X)
X_norm = sklearn.preprocessing.normalize(X, norm="l1")
X_norm = np.log1p(X_norm * 1e4)
X_lsi = sklearn.utils.extmath.randomized_svd(X_norm, n_components, **kwargs)[0]
X_lsi -= X_lsi.mean(axis=1, keepdims=True)
X_lsi /= X_lsi.std(axis=1, ddof=1, keepdims=True)
adata.obsm["X_lsi"] = X_lsi
def aggregate_obs(
adata: AnnData, by: str, X_agg: Optional[str] = "sum",
obs_agg: Optional[Mapping[str, str]] = None,
obsm_agg: Optional[Mapping[str, str]] = None,
layers_agg: Optional[Mapping[str, str]] = None
) -> AnnData:
r"""
Aggregate obs in a given dataset by certain categories
Parameters
----------
adata
Dataset to be aggregated
by
Specify a column in ``adata.obs`` used for aggregation,
must be discrete.
X_agg
Aggregation function for ``adata.X``, must be one of
``{"sum", "mean", ``None``}``. Setting to ``None`` discards
the ``adata.X`` matrix.
obs_agg
Aggregation methods for ``adata.obs``, indexed by obs columns,
must be one of ``{"sum", "mean", "majority"}``, where ``"sum"``
and ``"mean"`` are for continuous data, and ``"majority"`` is for
discrete data. Fields not specified will be discarded.
obsm_agg
Aggregation methods for ``adata.obsm``, indexed by obsm keys,
must be one of ``{"sum", "mean"}``. Fields not specified will be
discarded.
layers_agg
Aggregation methods for ``adata.layers``, indexed by layer keys,
must be one of ``{"sum", "mean"}``. Fields not specified will be
discarded.
Returns
-------
aggregated
Aggregated dataset
"""
obs_agg = obs_agg or {}
obsm_agg = obsm_agg or {}
layers_agg = layers_agg or {}
by = adata.obs[by]
agg_idx = pd.Index(by.cat.categories) \
if pd.api.types.is_categorical_dtype(by) \
else pd.Index(np.unique(by))
agg_sum = sparse.coo_matrix((
np.ones(adata.shape[0]), (
agg_idx.get_indexer(by),
np.arange(adata.shape[0])
)
)).tocsr()
agg_mean = agg_sum.multiply(1 / agg_sum.sum(axis=1))
agg_method = {
"sum": lambda x: agg_sum @ x,
"mean": lambda x: agg_mean @ x,
"majority": lambda x: pd.crosstab(by, x).idxmax(axis=1).loc[agg_idx].to_numpy()
}
X = agg_method[X_agg](adata.X) if X_agg and adata.X is not None else None
obs = pd.DataFrame({
k: agg_method[v](adata.obs[k])
for k, v in obs_agg.items()
}, index=agg_idx.astype(str))
obsm = {
k: agg_method[v](adata.obsm[k])
for k, v in obsm_agg.items()
}
layers = {
k: agg_method[v](adata.layers[k])
for k, v in layers_agg.items()
}
for c in obs:
if pd.api.types.is_categorical_dtype(adata.obs[c]):
obs[c] = pd.Categorical(obs[c], categories=adata.obs[c].cat.categories)
return AnnData(
X=X, obs=obs, var=adata.var,
obsm=obsm, varm=adata.varm, layers=layers,
dtype=None if X is None else X.dtype
)
class ATACDataset(object):
def __init__(self, data_root: str, raw_filename: str, file_chrom: str):
self.data_root = data_root
self.raw_filename = raw_filename
self.adata = self.load_matrix()
# self.adata.raw = self.adata.copy()
self.path_process = os.path.join(data_root, 'processed_files')
if not os.path.exists(self.path_process):
os.mkdir(self.path_process)
self.file_peaks_sort = os.path.join(self.path_process, 'peaks.sort.bed')
if os.path.exists(self.file_peaks_sort):
os.remove(self.file_peaks_sort)
self.file_chrom = file_chrom
self.generate_peaks_file()
self.all_promoter_genes = None
self.all_proximal_genes = None
self.adata_merge = None
self.other_peaks = None
self.df_graph = None
self.list_graph = None
self.array_peak = None
self.array_celltype = None
self.df_rna = None
self.dict_promoter = None
self.df_gene_peaks = None
self.df_proximal = None
self.df_distal = None
self.df_eqtl = None
self.df_tf = None
def load_matrix(self):
if self.raw_filename[-5:] == '.h5ad':
adata_atac = sc.read_h5ad(os.path.join(self.data_root, self.raw_filename))
elif self.raw_filename[-4:] == '.tsv':
adata_atac = ad.read_text(
os.path.join(self.data_root, self.raw_filename),
delimiter='\t', first_column_names=True, dtype='int')
epi.pp.sparse(adata_atac)
else:
raise ImportError("Input format error!")
return adata_atac
def generate_peaks_file(self):
df_chrom = pd.read_csv(self.file_chrom, sep='\t', header=None, index_col=0)
df_chrom = df_chrom.iloc[:24]
file_peaks_atac = os.path.join(self.path_process, 'peaks.bed')
fmt_peak = "{chrom_peak}\t{start_peak}\t{end_peak}\t{peak_id}\n"
with open(file_peaks_atac, 'w') as w_peak:
for one_peak in self.adata.var.index:
chrom_peak = one_peak.strip().split('-')[0]
# locs = one_peak.strip().split(':')[1]
if chrom_peak in df_chrom.index:
start_peak = one_peak.strip().split('-')[1]
end_peak = one_peak.strip().split('-')[2]
peak_id = one_peak
w_peak.write(fmt_peak.format(**locals()))
os.system(f"bedtools sort -i {file_peaks_atac} > {self.file_peaks_sort}")
def hg19tohg38(self, len_down: int = 200, len_up: int = 1000):
path_peak = os.path.join(self.data_root, 'peaks_process')
if not os.path.exists(path_peak):
os.mkdir(path_peak)
file_chain = '/root/tools/files_liftOver/hg19ToHg38.over.chain.gz'
liftover = '/root/tools/liftOver'
file_ummap = os.path.join(path_peak, 'unmap.bed')
file_peaks_hg38 = os.path.join(path_peak, 'peaks_hg38.bed')
os.system(f"{liftover} {self.file_peaks_sort} {file_chain} {file_peaks_hg38} {file_ummap}")
df_hg38 = pd.read_csv(file_peaks_hg38, sep='\t', header=None)
df_hg38['peak_hg38'] = df_hg38.apply(lambda x: f"{x[0]}-{x[1]}-{x[2]}", axis=1)
df_hg38['length'] = df_hg38.iloc[:, 2] - df_hg38.iloc[:, 1]
df_hg38 = df_hg38.loc[df_hg38['length'] < len_up, :]
df_hg38 = df_hg38.loc[df_hg38['length'] > len_down, :]
sel_peaks_hg19 = df_hg38.iloc[:, 3]
adata_atac_out = self.adata[:, sel_peaks_hg19]
adata_atac_out.var['peaks_hg19'] = adata_atac_out.var.index
adata_atac_out.var.index = df_hg38['peak_hg38']
self.adata = adata_atac_out
def quality_control(self, min_features: int = 1000, max_features: int = 50000,
min_percent: Optional[float] = None, min_cells: Optional[int] = None):
adata_atac = self.adata
epi.pp.filter_cells(adata_atac, min_features=min_features)
epi.pp.filter_cells(adata_atac, max_features=max_features)
if min_percent is not None:
by = adata_atac.obs['celltype']
agg_idx = pd.Index(by.cat.categories) \
if pd.api.types.is_categorical_dtype(by) \
else pd.Index(np.unique(by))
agg_sum = sparse.coo_matrix((
np.ones(adata_atac.shape[0]), (
agg_idx.get_indexer(by),
np.arange(adata_atac.shape[0])
)
)).tocsr()
sum_x = agg_sum @ (adata_atac.X != 0)
df_percent = pd.DataFrame(
sum_x.toarray(), index=agg_idx, columns=adata_atac.var.index
) / adata_atac.obs.value_counts('celltype').loc[agg_idx].to_numpy()[:, np.newaxis]
df_percent_max = np.max(df_percent, axis=0)
sel_peaks = df_percent.columns[df_percent_max > min_percent]
self.adata = self.adata[:, sel_peaks]
elif min_cells is not None:
epi.pp.filter_features(adata_atac, min_cells=min_cells)
def select_genes(self, num_peak=120000):
adata_atac = self.adata
sc.pp.normalize_total(adata_atac)
sc.pp.log1p(adata_atac)
sc.pp.highly_variable_genes(adata_atac, n_top_genes=num_peak, flavor='seurat')
self.adata = self.adata[:, adata_atac.var.highly_variable]
def deepen_atac(self, num_pc=100, n_iter=15, num_cell_merge=10):
random.seed(1234)
adata_atac_sample_cluster = self.adata.copy()
lsi(adata_atac_sample_cluster, n_components=num_pc, n_iter=n_iter)
sc.pp.neighbors(adata_atac_sample_cluster, use_rep="X_lsi", metric="cosine",
n_neighbors=num_cell_merge, n_pcs=num_pc)
list_atac_index = []
list_neigh_index = []
for cell_atac in list(adata_atac_sample_cluster.obs.index):
cell_atac = [cell_atac]
cell_atac_index = np.where(adata_atac_sample_cluster.obs.index == cell_atac[0])[0]
cell_neighbor_idx = \
np.nonzero(
adata_atac_sample_cluster.obsp['connectivities'].getcol(
np.where(
adata_atac_sample_cluster.obs.index == cell_atac[0])[0]).toarray())[0]
# cell_sample_atac = np.hstack([cell_atac_index, cell_neighbor_idx])
# cell_sample_atac = np.hstack([cell_atac_index,
# cell_neighbor_idx[0:(num_cell_merge-1)]])
num_sample = min(num_cell_merge, len(cell_neighbor_idx))
cell_sample_atac = np.hstack([cell_atac_index,
np.random.choice(cell_neighbor_idx, num_sample,
replace=False)])
list_atac_index.extend([cell_atac_index[0] for _ in range(num_sample + 1)])
list_neigh_index.append(cell_sample_atac)
agg_sum = sparse.coo_matrix((
np.ones(len(list_atac_index)), (np.hstack(list_neigh_index), np.array(list_atac_index))
)).tocsr()
array_atac = agg_sum @ self.adata.X
# self.adata = self.adata.copy()
self.adata.X = None
self.adata.X = array_atac
# epi.pp.sparse(self.adata)
def add_promoter(self, file_tss, flank_proximal=2000):
sc.pp.normalize_total(self.adata)
sc.pp.log1p(self.adata)
df_tss = pd.read_csv(file_tss, sep='\t', header=None)
df_tss.columns = ['chrom', 'tss', 'symbol', 'ensg_id', 'strand']
df_tss = df_tss.drop_duplicates(subset='symbol')
df_tss.index = df_tss['symbol']
df_tss['tss_start'] = df_tss['tss'] - 2000
df_tss['tss_end'] = df_tss['tss'] + 2000
df_tss['proximal_start'] = df_tss['tss'] - flank_proximal
df_tss['proximal_end'] = df_tss['tss'] + flank_proximal
file_promoter = os.path.join(self.path_process, 'promoter.txt')
file_proximal = os.path.join(self.path_process, 'proximal.txt')
df_promoter = \
df_tss.loc[:, ['chrom', 'tss_start', 'tss_end', 'symbol', 'ensg_id', 'strand']]
df_promoter.to_csv(file_promoter, sep='\t', header=False, index=False)
df_proximal = \
df_tss.loc[:, ['chrom', 'proximal_start', 'proximal_end',
'symbol', 'ensg_id', 'strand']]
df_proximal.to_csv(file_proximal, sep='\t', header=False, index=False)
self.generate_peaks_file()
# add promoter to adata
file_peaks_promoter = os.path.join(self.path_process, 'peaks_promoter.txt')
os.system(f"bedtools intersect -a {self.file_peaks_sort} -b {file_promoter} -wao "
f"> {file_peaks_promoter}")
dict_promoter = defaultdict(list)
with open(file_peaks_promoter, 'r') as w_pro:
for line in w_pro:
list_line = line.strip().split('\t')
if list_line[4] == '.':
continue
gene_symbol = list_line[7]
peak = list_line[3]
gene_tss = df_tss.loc[gene_symbol, 'tss']
coor_cre = (int(list_line[2]) + int(list_line[1]))/2
dist_gene_cre = abs(gene_tss - coor_cre)
dict_promoter[gene_symbol].append((peak, dist_gene_cre))
all_genes = dict_promoter.keys()
list_peaks_promoter = []
list_genes_promoter = []
for gene_symbol in all_genes:
sub_peaks = dict_promoter[gene_symbol]
sel_peak = ''
min_dist = 2000
for sub_peak in sub_peaks:
if sub_peak[1] < min_dist:
sel_peak = sub_peak[0]
min_dist = sub_peak[1]
if sel_peak != '':
list_peaks_promoter.append(sel_peak)
list_genes_promoter.append(gene_symbol)
self.all_promoter_genes = list_genes_promoter
adata_gene_promoter = self.adata[:, list_peaks_promoter]
adata_promoter = \
ad.AnnData(X=adata_gene_promoter.X,
var=pd.DataFrame(data={'cRE_type': np.full(len(list_genes_promoter),
'Promoter')},
index=list_genes_promoter),
obs=pd.DataFrame(index=adata_gene_promoter.obs.index))
adata_peak = self.adata.copy()
adata_peak.obs = pd.DataFrame(index=self.adata.obs.index)
adata_peak.var = pd.DataFrame(data={'node_type': np.full(adata_peak.var.shape[0], 'cRE')},
index=adata_peak.var.index)
adata_merge = ad.concat([adata_promoter, adata_peak], axis=1)
self.adata_merge = adata_merge
# proximal regulation
file_peaks_proximal = os.path.join(self.path_process, 'peaks_proximal.txt')
os.system(f"bedtools intersect -a {self.file_peaks_sort} -b {file_proximal} -wao "
f"> {file_peaks_proximal}")
dict_proximal = defaultdict(list)
with open(file_peaks_proximal, 'r') as w_pro:
for line in w_pro:
list_line = line.strip().split('\t')
if list_line[4] == '.':
continue
gene_symbol = list_line[7].strip().split('<-')[0]
peak = list_line[3]
dict_proximal[gene_symbol].append(peak)
self.dict_promoter = dict_proximal
all_genes = dict_proximal.keys()
list_peaks_proximal = []
list_genes_proximal = []
for gene_symbol in all_genes:
sub_peaks = dict_proximal[gene_symbol]
list_genes_proximal.extend([gene_symbol for _ in range(len(sub_peaks))])
list_peaks_proximal.extend(sub_peaks)
self.all_proximal_genes = set(list_genes_proximal)
self.df_gene_peaks = \
pd.DataFrame({'gene': list_genes_proximal, 'peak': list_peaks_proximal})
self.df_proximal = \
pd.DataFrame({'region1': list_genes_proximal, 'region2': list_peaks_proximal,
'type': ['proximal']*len(list_peaks_proximal)})
set_gene = set(self.df_rna.columns).intersection(self.all_promoter_genes)
self.df_proximal = \
self.df_proximal.loc[self.df_proximal["region1"].apply(lambda x: x in set_gene), :]
return
def build_graph(self, path_interaction, sel_interaction='PO'):
file_pp = os.path.join(path_interaction, 'PP.txt')
file_po = os.path.join(path_interaction, 'PO.txt')
if sel_interaction == 'PP' or sel_interaction == 'ALL':
df_pp_pre = pd.read_csv(file_pp, sep='\t', header=None)
df_pp_pre = \
df_pp_pre.loc[df_pp_pre.apply(
lambda x: x.iloc[0] in self.all_promoter_genes and x.iloc[1] in self.all_promoter_genes, axis=1), :]
df_pp_pre.columns = ['region1', 'gene']
df_gene_peaks = self.df_gene_peaks.copy()
df_gene_peaks.columns = ['gene', 'region2']
df_pp = pd.merge(left=df_pp_pre, right=df_gene_peaks, on='gene')
df_pp = df_pp.loc[:, ['region1', 'region2']]
if sel_interaction == 'PO' or sel_interaction == 'ALL':
file_po_peaks = os.path.join(self.path_process, 'peaks_PO.bed')
os.system(f"bedtools intersect -a {self.file_peaks_sort} -b {file_po} -wao "
f"> {file_po_peaks}")
list_dict = []
with open(file_po_peaks, 'r') as r_po:
for line in r_po:
list_line = line.strip().split('\t')
peak = list_line[3]
gene_symbol = list_line[8]
if gene_symbol in self.all_promoter_genes:
list_dict.append({"region1": gene_symbol, "region2": peak})
df_po = pd.DataFrame(list_dict)
if sel_interaction == 'PP':
df_interaction = df_pp
elif sel_interaction == 'PO':
df_interaction = df_po
elif sel_interaction == 'ALL':
df_interaction = pd.concat([df_pp, df_po])
else:
print("Error: please set correct parameter 'sel_interaction'! ")
return
self.df_distal = df_interaction.drop_duplicates()
self.df_distal['type'] = ['distal']*self.df_distal.shape[0]
set_gene = set(self.df_rna.columns)
self.df_distal = \
self.df_distal.loc[self.df_distal["region1"].apply(lambda x: x in set_gene), :]
self.df_graph = pd.concat([self.df_proximal, self.df_distal], axis=0)
return
def add_eqtl(self, file_eqtl):
file_eqtl_peaks = os.path.join(self.path_process, 'peaks_eQTL.bed')
os.system(f"bedtools intersect -a {self.file_peaks_sort} -b {file_eqtl} -wao "
f"> {file_eqtl_peaks}")
list_dict_eqtl = []
with open(file_eqtl_peaks, 'r') as r_po:
for line in r_po:
list_line = line.strip().split('\t')
peak = list_line[3]
gene_symbol = list_line[8]
if gene_symbol in self.all_promoter_genes:
list_dict_eqtl.append({"region1": gene_symbol, "region2": peak})
df_eqtl = pd.DataFrame(list_dict_eqtl)
df_eqtl = df_eqtl.drop_duplicates()
df_eqtl['type'] = ['eQTL']*df_eqtl.shape[0]
self.df_eqtl = df_eqtl
set_gene = set(self.df_rna.columns)
self.df_eqtl = \
self.df_eqtl.loc[self.df_eqtl["region1"].apply(lambda x: x in set_gene), :]
self.df_graph = pd.concat([self.df_graph, self.df_eqtl], axis=0)
self.df_graph = self.df_graph.drop_duplicates(subset=["region1", "region2"], keep='first')
def build_tf_graph(self, file_tf):
df_tf = pd.read_csv(file_tf, sep='\t', header=None)
df_tf = df_tf.iloc[:, :2]
df_tf.columns = ['TF', 'TargetGene']
set_gene = set(self.df_rna.columns).intersection(self.all_promoter_genes)
df_tf = df_tf.loc[df_tf.apply(
lambda x: x.iloc[0] in set_gene and x.iloc[1] in set_gene, axis=1), :]
df_tf_self = pd.DataFrame({'TF': sorted(list(set_gene)),
'TargetGene': sorted(list(set_gene))})
self.df_tf = pd.concat([df_tf_self, df_tf], axis=0)
def generate_data_list(self):
graph_data = self.df_graph
graph_tf = self.df_tf
adata_atac = self.adata
adata_merge = self.adata_merge
all_cre_gene = set(graph_data['region1']).union(set(graph_data['region2']))
all_tf_gene = set(graph_tf['TF']).union(set(graph_tf['TargetGene']))
all_peaks = all_cre_gene.union(all_tf_gene)
adata_merge_peak = adata_merge[:, [one_peak for one_peak in adata_merge.var.index
if one_peak in all_peaks]]
array_peak = np.array(adata_merge_peak.var.index)
list_gene_peak = [one_peak for one_peak in array_peak if one_peak[:3] != 'chr']
self.df_rna = self.df_rna.loc[:, list_gene_peak]
self.df_rna = self.df_rna / np.array(np.sum(self.df_rna, axis=1))[:, np.newaxis]
array_celltype = np.unique(np.array(adata_atac.obs['celltype']))
# cRE-Gene
array_region1 = graph_data['region1'].apply(lambda x: np.argwhere(array_peak == x)[0, 0])
array_region2 = graph_data['region2'].apply(lambda x: np.argwhere(array_peak == x)[0, 0])
df_graph_index = torch.tensor([np.array(array_region2), np.array(array_region1)],
dtype=torch.int64)
# TF-Gene
array_tf = graph_tf['TF'].apply(lambda x: np.argwhere(array_peak == x)[0, 0])
array_target = graph_tf['TargetGene'].apply(lambda x: np.argwhere(array_peak == x)[0, 0])
df_graph_tf = torch.tensor([np.array(array_tf), np.array(array_target)], dtype=torch.int64)
df_merge_peak = adata_merge_peak.to_df()
list_graph = []
for i_cell in range(0, adata_atac.n_obs):
one_cell = adata_atac.obs.index[i_cell]
label = adata_atac.obs.loc[one_cell, 'celltype']
label_rna = adata_atac.obs.loc[one_cell, 'celltype_rna']
label_exp = self.df_rna.loc[label_rna, list_gene_peak].tolist()
label_idx = torch.tensor(np.argwhere(array_celltype == label)[0], dtype=torch.int64)
cell_data = Data(x=torch.reshape(torch.Tensor(df_merge_peak.loc[one_cell, :]),
(adata_merge_peak.shape[1], 1)),
edge_index=df_graph_index, edge_tf=df_graph_tf.T,
y=label_idx, y_exp=torch.tensor(label_exp), cell=one_cell)
list_graph.append(cell_data)
self.list_graph = list_graph
self.array_peak = array_peak
self.array_celltype = array_celltype
return
class ATACGraphDataset(InMemoryDataset):
def __init__(self, root: str, data_list: List = None):
self.data_list = data_list
super(ATACGraphDataset, self).__init__(root)
self.data, self.slices = torch.load(self.processed_paths[0])
@property
def raw_file_names(self):
return ['some_file_1']
@property
def processed_file_names(self):
return ['data.pt']
def download(self):
pass
def process(self):
# Read data into huge `Data` list.
data_list = self.data_list
data, slices = self.collate(data_list)
torch.save((data, slices), self.processed_paths[0])
def prepare_model_input(path_data_root, file_atac, df_rna_celltype,
min_features=None, max_features=None, min_percent=0.05,
hg19tohg38=False, deepen_data=True):
if not os.path.exists(path_data_root):
os.mkdir(path_data_root)
file_chrom_hg38 = '/root/gene_activity/data/genome/hg38.chrom.sizes'
# file_atac = '../raw_data/pbmc_10XM_ATAC_2.h5ad'
dataset_ATAC = ATACDataset(data_root=path_data_root, raw_filename=file_atac,
file_chrom=file_chrom_hg38)
# dataset_ATAC.adata.obs['celltype'] = dataset_ATAC.adata.obs['seurat_annotations']
if hg19tohg38:
dataset_ATAC.hg19tohg38()
vec_num_feature = np.array(np.sum(dataset_ATAC.adata.X != 0, axis=1))
if min_features is None:
default_min = int(np.percentile(vec_num_feature, 1))
min_features = default_min
if max_features is None:
default_max = int(np.percentile(vec_num_feature, 99))
max_features = default_max
dataset_ATAC.quality_control(min_features=min_features, max_features=max_features,
min_percent=min_percent)
# dataset_ATAC.quality_control(min_features=3000, min_cells=5)
# deep atac
if deepen_data:
dataset_ATAC.deepen_atac(num_cell_merge=10)
# add RNA-seq data
dataset_ATAC.df_rna = df_rna_celltype
file_gene_hg38 = '/root/scATAC/Gene_anno/Gene_hg38/genes.protein.tss.tsv'
dataset_ATAC.add_promoter(file_gene_hg38)
# Hi-C
path_hic = '/root/scATAC/pcHi-C/all_pcHiC/hg38_3'
dataset_ATAC.build_graph(path_hic, sel_interaction='ALL')
dataset_ATAC.add_eqtl('/root/scATAC/eQTL/eQTL_process/all_tissue_SNP_Gene.txt')
# df_graph_PLAC = dataset_ATAC.df_graph
# TF
path_tf = '/root/scATAC/TRRUST/trrust_rawdata.human.tsv'
dataset_ATAC.build_tf_graph(path_tf)
# df_graph_TF = dataset_ATAC.df_tf
dataset_ATAC.generate_data_list()
list_graph_data = dataset_ATAC.list_graph
path_graph_input = os.path.join(path_data_root, 'input_graph')
os.system(f"rm -rf {path_graph_input}")
os.mkdir(path_graph_input)
dataset_atac_graph = ATACGraphDataset(path_graph_input, list_graph_data)
# save data
file_atac_test = os.path.join(path_data_root, 'dataset_atac.pkl')
with open(file_atac_test, 'wb') as w_pkl:
str_pkl = pickle.dumps(dataset_ATAC)
w_pkl.write(str_pkl)
return dataset_ATAC, dataset_atac_graph
if __name__ == '__main__':
time_start = time()
time_end = time()
print(time_end - time_start)
|
/scReGAT-0.0.4.tar.gz/scReGAT-0.0.4/scregat/data_process_2.py
| 0.867485 | 0.419767 |
data_process_2.py
|
pypi
|
from time import time
import os
import torch
from torch_geometric.data import InMemoryDataset, Data
from collections import defaultdict
import episcanpy.api as epi
import scanpy as sc
import numpy as np
import pandas as pd
from pandas import DataFrame
import anndata as ad
from anndata import AnnData
from typing import Optional, Mapping, List, Union
from scipy import sparse
import sklearn
from statsmodels.distributions.empirical_distribution import ECDF
import pickle
import random
def tfidf(X: Union[np.ndarray, sparse.spmatrix]) -> Union[np.ndarray, sparse.spmatrix]:
r"""
TF-IDF normalization (following the Seurat v3 approach)
Parameters
----------
X
Input matrix
Returns
-------
X_tfidf
TF-IDF normalized matrix
"""
idf = X.shape[0] / X.sum(axis=0)
if sparse.issparse(X):
tf = X.multiply(1 / X.sum(axis=1))
return tf.multiply(idf)
else:
tf = X / X.sum(axis=1, keepdims=True)
return tf * idf
def lsi(
adata: AnnData, n_components: int = 20,
use_top_features: Optional[bool] = False, min_cutoff: float = 0.05, **kwargs
) -> None:
r"""
LSI analysis
Parameters
----------
adata
Input dataset
n_components
Number of dimensions to use
use_top_features
Whether to find most frequently observed features and use them
min_cutoff
Cutoff for feature to be included in the ``adata.var['select_feature']``.
For example, '0.05' to set the top 95% most common features as the selected features.
**kwargs
Additional keyword arguments are passed to
:func:`sklearn.utils.extmath.randomized_svd`
"""
if "random_state" not in kwargs:
kwargs["random_state"] = 0 # Keep deterministic as the default behavior
adata_use = adata.copy()
if use_top_features:
adata_use.var['featurecounts'] = np.array(np.sum(adata_use.X, axis=0))[0]
df_var = adata_use.var.sort_values(by='featurecounts')
ecdf = ECDF(df_var['featurecounts'])
df_var['percentile'] = ecdf(df_var['featurecounts'])
df_var["selected_feature"] = (df_var['percentile'] > min_cutoff)
adata_use.var = df_var.loc[adata_use.var.index, :]
# factor_size = int(np.median(np.array(np.sum(adata_use.X, axis=1))))
X_norm = np.log1p(tfidf(adata_use.X) * 1e4)
if use_top_features:
X_norm = X_norm.toarray()[:, adata_use.var["selected_feature"]]
else:
X_norm = X_norm.toarray()
svd = sklearn.decomposition.TruncatedSVD(n_components=n_components, algorithm='arpack')
X_lsi = svd.fit_transform(X_norm)
X_lsi -= X_lsi.mean(axis=1, keepdims=True)
X_lsi /= X_lsi.std(axis=1, ddof=1, keepdims=True)
adata.obsm["X_lsi"] = X_lsi
class ATACDataset(object):
def __init__(self, data_root: str, raw_filename: str, file_chrom: str):
self.data_root = data_root
self.raw_filename = raw_filename
self.adata = self.load_matrix()
# self.adata.raw = self.adata.copy()
self.path_process = os.path.join(data_root, 'processed_files')
if not os.path.exists(self.path_process):
os.mkdir(self.path_process)
self.file_peaks_sort = os.path.join(self.path_process, 'peaks.sort.bed')
if os.path.exists(self.file_peaks_sort):
os.remove(self.file_peaks_sort)
self.file_chrom = file_chrom
# tools
basepath = os.path.abspath(__file__)
folder = os.path.dirname(basepath)
self.bedtools = os.path.join(folder, '../tools/bedtools/bin/bedtools')
self.liftover = os.path.join(folder, '../tools/liftOver')
self.file_chain = os.path.join(folder, '../tools/files_liftOver/hg19ToHg38.over.chain.gz')
self.generate_peaks_file()
self.all_promoter_genes = None
self.all_proximal_genes = None
self.adata_merge = None
self.other_peaks = None
self.df_graph = None
self.list_graph = None
self.array_peak = None
self.array_celltype = None
self.df_rna = None
self.dict_promoter = None
self.df_gene_peaks = None
self.df_proximal = None
self.df_distal = None
self.df_eqtl = None
self.df_tf = None
def load_matrix(self):
if self.raw_filename[-5:] == '.h5ad':
adata_atac = sc.read_h5ad(os.path.join(self.data_root, self.raw_filename))
elif self.raw_filename[-4:] == '.tsv':
adata_atac = ad.read_text(
os.path.join(self.data_root, self.raw_filename),
delimiter='\t', first_column_names=True, dtype='int')
epi.pp.sparse(adata_atac)
else:
raise ImportError("Input format error!")
return adata_atac
def generate_peaks_file(self):
df_chrom = pd.read_csv(self.file_chrom, sep='\t', header=None, index_col=0)
df_chrom = df_chrom.iloc[:24]
file_peaks_atac = os.path.join(self.path_process, 'peaks.bed')
fmt_peak = "{chrom_peak}\t{start_peak}\t{end_peak}\t{peak_id}\n"
with open(file_peaks_atac, 'w') as w_peak:
for one_peak in self.adata.var.index:
chrom_peak = one_peak.strip().split('-')[0]
# locs = one_peak.strip().split(':')[1]
if chrom_peak in df_chrom.index:
start_peak = one_peak.strip().split('-')[1]
end_peak = one_peak.strip().split('-')[2]
peak_id = one_peak
w_peak.write(fmt_peak.format(**locals()))
os.system(f"{self.bedtools} sort -i {file_peaks_atac} > {self.file_peaks_sort}")
def hg19tohg38(self):
path_peak = os.path.join(self.data_root, 'peaks_process')
if not os.path.exists(path_peak):
os.mkdir(path_peak)
file_ummap = os.path.join(path_peak, 'unmap.bed')
file_peaks_hg38 = os.path.join(path_peak, 'peaks_hg38.bed')
os.system(f"{self.liftover} {self.file_peaks_sort} {self.file_chain} "
f"{file_peaks_hg38} {file_ummap}")
df_hg19 = pd.read_csv(self.file_peaks_sort, sep='\t', header=None)
df_hg19['length'] = df_hg19.iloc[:, 2] - df_hg19.iloc[:, 1]
len_down = np.min(df_hg19['length']) - 20
len_up = np.max(df_hg19['length']) + 100
df_hg38 = pd.read_csv(file_peaks_hg38, sep='\t', header=None)
df_hg38['peak_hg38'] = df_hg38.apply(lambda x: f"{x[0]}-{x[1]}-{x[2]}", axis=1)
df_hg38['length'] = df_hg38.iloc[:, 2] - df_hg38.iloc[:, 1]
df_hg38 = df_hg38.loc[df_hg38['length'] < len_up, :]
df_hg38 = df_hg38.loc[df_hg38['length'] > len_down, :]
sel_peaks_hg19 = df_hg38.iloc[:, 3]
adata_atac_out = self.adata[:, sel_peaks_hg19]
adata_atac_out.var['peaks_hg19'] = adata_atac_out.var.index
adata_atac_out.var.index = df_hg38['peak_hg38']
self.adata = adata_atac_out
def quality_control(self, min_features: int = 1000, max_features: int = 60000,
min_percent: Optional[float] = None, min_cells: Optional[int] = None):
adata_atac = self.adata
epi.pp.filter_cells(adata_atac, min_features=min_features)
epi.pp.filter_cells(adata_atac, max_features=max_features)
if min_percent is not None:
by = adata_atac.obs['celltype']
agg_idx = pd.Index(by.cat.categories) \
if pd.api.types.is_categorical_dtype(by) \
else pd.Index(np.unique(by))
agg_sum = sparse.coo_matrix((
np.ones(adata_atac.shape[0]), (
agg_idx.get_indexer(by),
np.arange(adata_atac.shape[0])
)
)).tocsr()
sum_x = agg_sum @ (adata_atac.X != 0)
df_percent = pd.DataFrame(
sum_x.toarray(), index=agg_idx, columns=adata_atac.var.index
) / adata_atac.obs.value_counts('celltype').loc[agg_idx].to_numpy()[:, np.newaxis]
df_percent_max = np.max(df_percent, axis=0)
sel_peaks = df_percent.columns[df_percent_max > min_percent]
self.adata = self.adata[:, sel_peaks]
elif min_cells is not None:
epi.pp.filter_features(adata_atac, min_cells=min_cells)
def deepen_atac(self, num_pc: int = 50, num_cell_merge: int = 10):
random.seed(1234)
adata_atac_sample_cluster = self.adata.copy()
lsi(adata_atac_sample_cluster, n_components=num_pc)
adata_atac_sample_cluster.obsm["X_lsi"] = adata_atac_sample_cluster.obsm["X_lsi"][:, 1:]
sc.pp.neighbors(adata_atac_sample_cluster, use_rep="X_lsi", metric="cosine",
n_neighbors=int(num_cell_merge), n_pcs=num_pc)
list_atac_index = []
list_neigh_index = []
for cell_atac in list(adata_atac_sample_cluster.obs.index):
cell_atac = [cell_atac]
cell_atac_index = np.where(adata_atac_sample_cluster.obs.index == cell_atac[0])[0]
cell_neighbor_idx = \
np.nonzero(
adata_atac_sample_cluster.obsp['connectivities'].getcol(
cell_atac_index).toarray())[0]
if num_cell_merge >= len(cell_neighbor_idx):
cell_sample_atac = np.hstack([cell_atac_index, cell_neighbor_idx])
else:
cell_sample_atac = np.hstack([cell_atac_index,
np.random.choice(cell_neighbor_idx, num_cell_merge,
replace=False)])
list_atac_index.extend([cell_atac_index[0] for _ in range(len(cell_sample_atac))])
list_neigh_index.append(cell_sample_atac)
agg_sum = sparse.coo_matrix((
np.ones(len(list_atac_index)), (np.array(list_atac_index), np.hstack(list_neigh_index))
)).tocsr()
array_atac = agg_sum @ self.adata.X
# self.adata = self.adata.copy()
self.adata.X = None
self.adata.X = array_atac
def add_promoter(self, file_tss: str, flank_proximal: int = 2000):
sc.pp.normalize_total(self.adata)
sc.pp.log1p(self.adata)
df_tss = pd.read_csv(file_tss, sep='\t', header=None)
df_tss.columns = ['chrom', 'tss', 'symbol', 'ensg_id', 'strand']
df_tss = df_tss.drop_duplicates(subset='symbol')
df_tss.index = df_tss['symbol']
df_tss['tss_start'] = df_tss['tss'] - 2000
df_tss['tss_end'] = df_tss['tss'] + 2000
df_tss['proximal_start'] = df_tss['tss'] - flank_proximal
df_tss['proximal_end'] = df_tss['tss'] + flank_proximal
file_promoter = os.path.join(self.path_process, 'promoter.txt')
file_proximal = os.path.join(self.path_process, 'proximal.txt')
df_promoter = \
df_tss.loc[:, ['chrom', 'tss_start', 'tss_end', 'symbol', 'ensg_id', 'strand']]
df_promoter.to_csv(file_promoter, sep='\t', header=False, index=False)
df_proximal = \
df_tss.loc[:, ['chrom', 'proximal_start', 'proximal_end',
'symbol', 'ensg_id', 'strand']]
df_proximal.to_csv(file_proximal, sep='\t', header=False, index=False)
self.generate_peaks_file()
# add promoter to adata
file_peaks_promoter = os.path.join(self.path_process, 'peaks_promoter.txt')
os.system(f"{self.bedtools} intersect -a {self.file_peaks_sort} -b {file_promoter} -wao "
f"> {file_peaks_promoter}")
dict_promoter = defaultdict(list)
with open(file_peaks_promoter, 'r') as w_pro:
for line in w_pro:
list_line = line.strip().split('\t')
if list_line[4] == '.':
continue
gene_symbol = list_line[7]
peak = list_line[3]
gene_tss = df_tss.loc[gene_symbol, 'tss']
coor_cre = (int(list_line[2]) + int(list_line[1]))/2
dist_gene_cre = abs(gene_tss - coor_cre)
dict_promoter[gene_symbol].append((peak, dist_gene_cre))
all_genes = dict_promoter.keys()
list_peaks_promoter = []
list_genes_promoter = []
for gene_symbol in all_genes:
sub_peaks = dict_promoter[gene_symbol]
sel_peak = ''
min_dist = 2000
for sub_peak in sub_peaks:
if sub_peak[1] < min_dist:
sel_peak = sub_peak[0]
min_dist = sub_peak[1]
if sel_peak != '':
list_peaks_promoter.append(sel_peak)
list_genes_promoter.append(gene_symbol)
self.all_promoter_genes = list_genes_promoter
adata_gene_promoter = self.adata[:, list_peaks_promoter]
adata_promoter = \
ad.AnnData(X=adata_gene_promoter.X,
var=pd.DataFrame(data={'cRE_type': np.full(len(list_genes_promoter),
'Promoter')},
index=list_genes_promoter),
obs=pd.DataFrame(index=adata_gene_promoter.obs.index))
adata_peak = self.adata.copy()
adata_peak.obs = pd.DataFrame(index=self.adata.obs.index)
adata_peak.var = pd.DataFrame(data={'node_type': np.full(adata_peak.var.shape[0], 'cRE')},
index=adata_peak.var.index)
adata_merge = ad.concat([adata_promoter, adata_peak], axis=1)
self.adata_merge = adata_merge
# proximal regulation
file_peaks_proximal = os.path.join(self.path_process, 'peaks_proximal.txt')
os.system(f"{self.bedtools} intersect -a {self.file_peaks_sort} -b {file_proximal} -wao "
f"> {file_peaks_proximal}")
dict_proximal = defaultdict(list)
with open(file_peaks_proximal, 'r') as w_pro:
for line in w_pro:
list_line = line.strip().split('\t')
if list_line[4] == '.':
continue
gene_symbol = list_line[7].strip().split('<-')[0]
peak = list_line[3]
dict_proximal[gene_symbol].append(peak)
self.dict_promoter = dict_proximal
all_genes = dict_proximal.keys()
list_peaks_proximal = []
list_genes_proximal = []
for gene_symbol in all_genes:
sub_peaks = dict_proximal[gene_symbol]
list_genes_proximal.extend([gene_symbol for _ in range(len(sub_peaks))])
list_peaks_proximal.extend(sub_peaks)
self.all_proximal_genes = set(list_genes_proximal)
self.df_gene_peaks = \
pd.DataFrame({'gene': list_genes_proximal, 'peak': list_peaks_proximal})
self.df_proximal = \
pd.DataFrame({'region1': list_genes_proximal, 'region2': list_peaks_proximal,
'type': ['proximal']*len(list_peaks_proximal)})
set_gene = set(self.df_rna.columns).intersection(self.all_promoter_genes)
self.df_proximal = \
self.df_proximal.loc[self.df_proximal["region1"].apply(lambda x: x in set_gene), :]
return
def build_graph(self, path_interaction: str, sel_interaction: str = 'PO'):
file_pp = os.path.join(path_interaction, 'PP.txt')
file_po = os.path.join(path_interaction, 'PO.txt')
if sel_interaction == 'PP' or sel_interaction == 'ALL':
df_pp_pre = pd.read_csv(file_pp, sep='\t', header=None)
df_pp_pre = \
df_pp_pre.loc[df_pp_pre.apply(
lambda x: x.iloc[0] in self.all_promoter_genes and x.iloc[1] in self.all_promoter_genes, axis=1), :]
df_pp_pre.columns = ['region1', 'gene']
df_gene_peaks = self.df_gene_peaks.copy()
df_gene_peaks.columns = ['gene', 'region2']
df_pp = pd.merge(left=df_pp_pre, right=df_gene_peaks, on='gene')
df_pp = df_pp.loc[:, ['region1', 'region2']]
if sel_interaction == 'PO' or sel_interaction == 'ALL':
file_po_peaks = os.path.join(self.path_process, 'peaks_PO.bed')
os.system(f"{self.bedtools} intersect -a {self.file_peaks_sort} -b {file_po} -wao "
f"> {file_po_peaks}")
list_dict = []
with open(file_po_peaks, 'r') as r_po:
for line in r_po:
list_line = line.strip().split('\t')
peak = list_line[3]
gene_symbol = list_line[8]
if gene_symbol in self.all_promoter_genes:
list_dict.append({"region1": gene_symbol, "region2": peak})
df_po = pd.DataFrame(list_dict)
if sel_interaction == 'PP':
df_interaction = df_pp
elif sel_interaction == 'PO':
df_interaction = df_po
elif sel_interaction == 'ALL':
df_interaction = pd.concat([df_pp, df_po])
else:
print("Error: please set correct parameter 'sel_interaction'! ")
return
self.df_distal = df_interaction.drop_duplicates()
self.df_distal['type'] = ['distal']*self.df_distal.shape[0]
set_gene = set(self.df_rna.columns)
self.df_distal = \
self.df_distal.loc[self.df_distal["region1"].apply(lambda x: x in set_gene), :]
self.df_graph = pd.concat([self.df_proximal, self.df_distal], axis=0)
return
def add_eqtl(self, file_eqtl: str):
file_eqtl_peaks = os.path.join(self.path_process, 'peaks_eQTL.bed')
os.system(f"{self.bedtools} intersect -a {self.file_peaks_sort} -b {file_eqtl} -wao "
f"> {file_eqtl_peaks}")
list_dict_eqtl = []
with open(file_eqtl_peaks, 'r') as r_po:
for line in r_po:
list_line = line.strip().split('\t')
peak = list_line[3]
gene_symbol = list_line[8]
if gene_symbol in self.all_promoter_genes:
list_dict_eqtl.append({"region1": gene_symbol, "region2": peak})
df_eqtl = pd.DataFrame(list_dict_eqtl)
df_eqtl = df_eqtl.drop_duplicates()
df_eqtl['type'] = ['eQTL']*df_eqtl.shape[0]
self.df_eqtl = df_eqtl
set_gene = set(self.df_rna.columns)
self.df_eqtl = \
self.df_eqtl.loc[self.df_eqtl["region1"].apply(lambda x: x in set_gene), :]
self.df_graph = pd.concat([self.df_graph, self.df_eqtl], axis=0)
self.df_graph = self.df_graph.drop_duplicates(subset=["region1", "region2"], keep='first')
def build_tf_graph(self, file_tf: str):
df_tf = pd.read_csv(file_tf, sep='\t', header=None)
df_tf = df_tf.iloc[:, :2]
df_tf.columns = ['TF', 'TargetGene']
set_gene = set(self.df_rna.columns).intersection(self.all_promoter_genes)
df_tf = df_tf.loc[df_tf.apply(
lambda x: x.iloc[0] in set_gene and x.iloc[1] in set_gene, axis=1), :]
df_tf_self = pd.DataFrame({'TF': sorted(list(set_gene)),
'TargetGene': sorted(list(set_gene))})
self.df_tf = pd.concat([df_tf_self, df_tf], axis=0)
def generate_data_list(self):
graph_data = self.df_graph
graph_tf = self.df_tf
adata_atac = self.adata
adata_merge = self.adata_merge
all_cre_gene = set(graph_data['region1']).union(set(graph_data['region2']))
all_tf_gene = set(graph_tf['TF']).union(set(graph_tf['TargetGene']))
all_peaks = all_cre_gene.union(all_tf_gene)
adata_merge_peak = adata_merge[:, [one_peak for one_peak in adata_merge.var.index
if one_peak in all_peaks]]
array_peak = np.array(adata_merge_peak.var.index)
list_gene_peak = [one_peak for one_peak in array_peak if one_peak[:3] != 'chr']
self.df_rna = self.df_rna.loc[:, list_gene_peak]
self.df_rna = self.df_rna / np.array(np.sum(self.df_rna, axis=1))[:, np.newaxis]
array_celltype = np.unique(np.array(adata_atac.obs['celltype']))
# cRE-Gene
array_region1 = graph_data['region1'].apply(lambda x: np.argwhere(array_peak == x)[0, 0])
array_region2 = graph_data['region2'].apply(lambda x: np.argwhere(array_peak == x)[0, 0])
df_graph_index = torch.tensor([np.array(array_region2), np.array(array_region1)],
dtype=torch.int64)
# TF-Gene
array_tf = graph_tf['TF'].apply(lambda x: np.argwhere(array_peak == x)[0, 0])
array_target = graph_tf['TargetGene'].apply(lambda x: np.argwhere(array_peak == x)[0, 0])
df_graph_tf = torch.tensor([np.array(array_tf), np.array(array_target)], dtype=torch.int64)
df_merge_peak = adata_merge_peak.to_df()
list_graph = []
for i_cell in range(0, adata_atac.n_obs):
one_cell = adata_atac.obs.index[i_cell]
label = adata_atac.obs.loc[one_cell, 'celltype']
label_rna = adata_atac.obs.loc[one_cell, 'celltype_rna']
label_exp = self.df_rna.loc[label_rna, list_gene_peak].tolist()
label_idx = torch.tensor(np.argwhere(array_celltype == label)[0], dtype=torch.int64)
cell_data = Data(x=torch.reshape(torch.Tensor(df_merge_peak.loc[one_cell, :]),
(adata_merge_peak.shape[1], 1)),
edge_index=df_graph_index, edge_tf=df_graph_tf.T,
y=label_idx, y_exp=torch.tensor(label_exp), cell=one_cell)
list_graph.append(cell_data)
self.list_graph = list_graph
self.array_peak = array_peak
self.array_celltype = array_celltype
return
class ATACGraphDataset(InMemoryDataset):
def __init__(self, root: str, data_list: List = None):
self.data_list = data_list
super(ATACGraphDataset, self).__init__(root)
self.data, self.slices = torch.load(self.processed_paths[0])
@property
def raw_file_names(self):
return ['some_file_1']
@property
def processed_file_names(self):
return ['data.pt']
def download(self):
pass
def process(self):
# Read data into huge `Data` list.
data_list = self.data_list
data, slices = self.collate(data_list)
torch.save((data, slices), self.processed_paths[0])
def prepare_model_input(path_data_root: str, file_atac: str, df_rna_celltype: DataFrame,
min_features: Optional[float] = None, max_features: Optional[float] = None,
min_percent: Optional[float] = 0.05,
hg19tohg38: bool = False, deepen_data: bool = True):
if not os.path.exists(path_data_root):
os.mkdir(path_data_root)
basepath = os.path.abspath(__file__)
file_chrom_hg38 = os.path.join(os.path.dirname(basepath), '../data/hg38.chrom.sizes')
# file_atac = '../raw_data/pbmc_10XM_ATAC_2.h5ad'
dataset_ATAC = ATACDataset(data_root=path_data_root, raw_filename=file_atac,
file_chrom=file_chrom_hg38)
# dataset_ATAC.adata.obs['celltype'] = dataset_ATAC.adata.obs['seurat_annotations']
if hg19tohg38:
dataset_ATAC.hg19tohg38()
vec_num_feature = np.array(np.sum(dataset_ATAC.adata.X != 0, axis=1))
if min_features is None:
default_min = int(np.percentile(vec_num_feature, 1))
min_features = default_min
if max_features is None:
default_max = int(np.percentile(vec_num_feature, 99))
max_features = default_max
dataset_ATAC.quality_control(min_features=min_features, max_features=max_features,
min_percent=min_percent)
# dataset_ATAC.quality_control(min_features=3000, min_cells=5)
# deep atac
if deepen_data:
dataset_ATAC.deepen_atac(num_cell_merge=10)
# add RNA-seq data
dataset_ATAC.df_rna = df_rna_celltype
file_gene_hg38 = os.path.join(os.path.dirname(basepath), '../data/genes.protein.tss.tsv')
dataset_ATAC.add_promoter(file_gene_hg38)
# Hi-C
path_hic = os.path.join(os.path.dirname(basepath), '../data')
dataset_ATAC.build_graph(path_hic, sel_interaction='ALL')
dataset_ATAC.add_eqtl(
os.path.join(os.path.dirname(basepath), '../data/all_tissue_SNP_Gene.txt'))
# df_graph_PLAC = dataset_ATAC.df_graph
# TF
path_tf = os.path.join(os.path.dirname(basepath), '../data/trrust_rawdata.human.tsv')
dataset_ATAC.build_tf_graph(path_tf)
# df_graph_TF = dataset_ATAC.df_tf
dataset_ATAC.generate_data_list()
list_graph_data = dataset_ATAC.list_graph
path_graph_input = os.path.join(path_data_root, 'input_graph')
os.system(f"rm -rf {path_graph_input}")
os.mkdir(path_graph_input)
dataset_atac_graph = ATACGraphDataset(path_graph_input, list_graph_data)
# save data
file_atac_test = os.path.join(path_data_root, 'dataset_atac.pkl')
with open(file_atac_test, 'wb') as w_pkl:
str_pkl = pickle.dumps(dataset_ATAC)
w_pkl.write(str_pkl)
return dataset_ATAC, dataset_atac_graph
if __name__ == '__main__':
time_start = time()
time_end = time()
print(time_end - time_start)
|
/scReGAT-0.0.4.tar.gz/scReGAT-0.0.4/scregat/data_process.py
| 0.813127 | 0.342544 |
data_process.py
|
pypi
|
import os
import numpy as np
import torch
import torch.nn as nn
import random
def seed_all(seed_value, cuda_deterministic=False):
"""
设置所有的随机种子
"""
random.seed(seed_value)
os.environ['PYTHONHASHSEED'] = str(seed_value)
np.random.seed(seed_value)
torch.manual_seed(seed_value)
if torch.cuda.is_available():
torch.cuda.manual_seed(seed_value)
torch.cuda.manual_seed_all(seed_value)
# Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html
if cuda_deterministic: # slower, more reproducible
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
else: # faster, less reproducible
torch.backends.cudnn.deterministic = False
torch.backends.cudnn.benchmark = True
class MMDLoss(nn.Module):
def __init__(self, kernel_type='rbf', kernel_mul=2.0, kernel_num=5, fix_sigma=None, **kwargs):
super(MMDLoss, self).__init__()
self.kernel_num = kernel_num
self.kernel_mul = kernel_mul
self.fix_sigma = None
self.kernel_type = kernel_type
def guassian_kernel(self, source, target, kernel_mul, kernel_num, fix_sigma):
n_samples = int(source.size()[0]) + int(target.size()[0])
total = torch.cat([source, target], dim=0)
total0 = total.unsqueeze(0).expand(
int(total.size(0)), int(total.size(0)), int(total.size(1)))
total1 = total.unsqueeze(1).expand(
int(total.size(0)), int(total.size(0)), int(total.size(1)))
L2_distance = ((total0-total1)**2).sum(2)
if fix_sigma:
bandwidth = fix_sigma
else:
bandwidth = torch.sum(L2_distance.data) / (n_samples**2-n_samples)
bandwidth /= kernel_mul ** (kernel_num // 2)
bandwidth_list = [bandwidth * (kernel_mul**i)
for i in range(kernel_num)]
kernel_val = [torch.exp(-L2_distance / bandwidth_temp)
for bandwidth_temp in bandwidth_list]
tmp = 0
for x in kernel_val:
tmp += x
return tmp
def linear_mmd2(self, f_of_X, f_of_Y):
loss = 0.0
delta = f_of_X.float().mean(0) - f_of_Y.float().mean(0)
loss = delta.dot(delta.T)
return loss
def forward(self, source, target):
if self.kernel_type == 'linear':
return self.linear_mmd2(source, target)
elif self.kernel_type == 'rbf':
batch_size = int(source.size()[0])
kernels = self.guassian_kernel(
source, target, kernel_mul=self.kernel_mul, kernel_num=self.kernel_num, fix_sigma=self.fix_sigma)
XX = torch.mean(kernels[:batch_size, :batch_size])
YY = torch.mean(kernels[batch_size:, batch_size:])
XY = torch.mean(kernels[:batch_size, batch_size:])
YX = torch.mean(kernels[batch_size:, :batch_size])
loss = torch.mean(XX + YY - XY - YX)
return loss
|
/scSTEM-0.0.2-py3-none-any.whl/STEM/utils.py
| 0.801392 | 0.336372 |
utils.py
|
pypi
|
import torch
from torch.utils.data import DataLoader, Dataset
from torch import nn, optim
from torch.nn import functional as F
import torch.optim.lr_scheduler as lr_scheduler
import os
import numpy as np
import time
from .utils import *
import scipy
class STData(Dataset):
def __init__(self,data,coord):
self.data = data
self.coord = coord
def __getitem__(self, index):
return self.data[index], self.coord[index]
def __len__(self):
return self.data.shape[0]
class SCData(Dataset):
def __init__(self,data):
self.data = data
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return self.data.shape[0]
class FeatureNet(nn.Module):
def __init__(self, n_genes, n_embedding=[512,256,128],dp=0):
super(FeatureNet, self).__init__()
self.fc1 = nn.Linear(n_genes, n_embedding[0])
self.bn1 = nn.LayerNorm(n_embedding[0])
self.fc2 = nn.Linear(n_embedding[0], n_embedding[1])
self.bn2 = nn.LayerNorm(n_embedding[1])
self.fc3 = nn.Linear(n_embedding[1], n_embedding[2])
self.dp = nn.Dropout(dp)
def forward(self, x,isdp = False):
if isdp:
x = self.dp(x)
x = F.relu(self.bn1(self.fc1(x)))
x = F.relu(self.bn2(self.fc2(x)))
x = self.fc3(x)
return x
class BaseModel(nn.Module):
def __init__(self, opt):
super(BaseModel, self).__init__()
self.opt = opt
self.device = opt.device
self.train_log = opt.outf + '/train.log'
self.model_path = opt.outf + '/model.pth'
if not os.path.exists(opt.outf):
os.mkdir(opt.outf)
self.best_acc_tgt = 0
with open(self.train_log, 'a') as f:
localtime = time.asctime( time.localtime(time.time()) )
f.write(localtime+str((opt.device,opt.outf,opt.n_genes,opt.no_bn,opt.lr,opt.sigma,opt.alpha,opt.verbose,opt.mmdbatch,opt.dp))+'\n')
def set_requires_grad(self, nets, requires_grad=False):
if not isinstance(nets, list):
nets = [nets]
for net in nets:
if net is not None:
for param in net.parameters():
param.requires_grad = requires_grad
def save(self):
torch.save(self.state_dict(), self.model_path)
def load(self):
print('===> Loading model from {}'.format(self.model_path))
try:
self.load_state_dict(torch.load(self.model_path))
print('<=== Success!')
except:
print('<==== Failed!')
class SOmodel(BaseModel):
def __init__(self, opt):
super(SOmodel, self).__init__(opt)
self.netE = FeatureNet(opt.n_genes,dp=opt.dp)
self.optimizer = torch.optim.AdamW(self.netE.parameters(), lr=opt.lr)
self.lr_scheduler = lr_scheduler.StepLR(optimizer=self.optimizer,step_size=200, gamma=0.5)
self.loss_names = ['E','E_pred','E_circle','E_mmd']
self.mmd_fn = MMDLoss()
self.sigma = opt.sigma
self.alpha = opt.alpha
self.verbose = opt.verbose
self.mmdbatch = opt.mmdbatch
def train_onestep(self,stdata,scdata,coord,ratio):
if self.sigma == 0:
self.nettrue = torch.eye(coord.shape[0])
else:
self.nettrue = torch.tensor(scipy.spatial.distance.cdist(coord,coord)).to(torch.float32)
sigma = self.sigma
self.nettrue = torch.exp(-self.nettrue**2/(2*sigma**2))/(np.sqrt(2*np.pi)*sigma)
self.nettrue = F.normalize(self.nettrue,p=1,dim=1)
self.nettrue = self.nettrue.to(self.device)
stdata = stdata.to(self.device)
scdata = scdata.to(self.device)
self.e_seq_st = self.netE(stdata,True)
self.e_seq_sc = self.netE(scdata,False)
self.optimizer.zero_grad()
self.netpred = self.e_seq_st.mm(self.e_seq_st.t())
self.st2sc = F.softmax(self.e_seq_st.mm(self.e_seq_sc.t()),dim=1)
self.sc2st = F.softmax(self.e_seq_sc.mm(self.e_seq_st.t()),dim=1)
self.st2st = torch.log(self.st2sc.mm(self.sc2st)+1e-7)
self.loss_E_pred = F.cross_entropy(self.netpred, self.nettrue,reduction='mean')
self.loss_E_circle = F.kl_div(self.st2st,self.nettrue,reduction='none').sum(1).mean()
ranidx = np.random.randint(0,self.e_seq_sc.shape[0],self.mmdbatch)
self.loss_E_mmd = self.mmd_fn(self.e_seq_st,self.e_seq_sc[ranidx])
self.loss_E = self.loss_E_pred + self.alpha*self.loss_E_mmd + ratio*self.loss_E_circle
self.loss_E.backward()
self.optimizer.step()
def togpu(self):
self.netE.to(self.device)
def modeleval(self):
self.netE.eval()
def train(self,epoch,scdataloader,stdata,coord):
with open(self.train_log, 'a') as f:
localtime = time.asctime( time.localtime(time.time()) )
f.write(localtime+'\n')
loss_curve = {
loss: []
for loss in self.loss_names
}
for i in range(epoch):
self.netE.train()
for batch_idx, (scdata) in enumerate(scdataloader):
scdata = scdata.to(torch.float32)
self.train_onestep(stdata,scdata,coord,max((i-50)/(epoch-50),0))
for loss in self.loss_names:
loss_curve[loss].append(getattr(self, 'loss_' + loss).item())
self.lr_scheduler.step()
loss_msg = '[Train][{}] Loss:'.format(i+1)
for loss in self.loss_names:
loss_msg += ' {} {:.3f}'.format(loss, loss_curve[loss][-1])
if (i + 1) % 1 == 0:
print(loss_msg)
print(self.lr_scheduler.get_last_lr())
with open(self.train_log, 'a') as f:
f.write(loss_msg + "\n")
return loss_curve
def train_spatialbatch(self,epoch,scdata,stdataloader):
with open(self.train_log, 'a') as f:
localtime = time.asctime( time.localtime(time.time()) )
f.write(localtime+'\n')
loss_curve = {
loss: []
for loss in self.loss_names
}
for i in range(epoch):
self.netE.train()
self.netD.train()
for batch_idx, (stdata,coord) in enumerate(stdataloader):
stdata = stdata.to(torch.float32)
self.train_onestep(stdata,scdata,coord,max((i-50)/(epoch-50),0))
for loss in self.loss_names:
loss_curve[loss].append(getattr(self, 'loss_' + loss).item())
for lr_scheduler in self.lr_schedulers:
lr_scheduler.step()
loss_msg = '[Train][{}] Loss:'.format(i+1)
for loss in self.loss_names:
loss_msg += ' {} {:.3f}'.format(loss, loss_curve[loss][-1])
if (i + 1) % 1 == 0:
print(loss_msg)
print(self.lr_scheduler_D.get_last_lr(),self.lr_scheduler_G.get_last_lr())
with open(self.train_log, 'a') as f:
f.write(loss_msg + "\n")
return loss_curve
def train_wholedata(self,epoch,scdata,stdata,coord):
with open(self.train_log, 'a') as f:
localtime = time.asctime( time.localtime(time.time()) )
f.write(localtime+'\n')
loss_curve = {
loss: []
for loss in self.loss_names
}
for i in range(epoch):
self.netE.train()
scdata = scdata.to(torch.float32)
if isinstance(stdata,list):
shuffle_list = np.random.randint(0,len(stdata),len(stdata))
for idx in shuffle_list:
self.train_onestep(stdata[idx],scdata,coord[idx],max((i-50)/(epoch-50),0))
else:
self.train_onestep(stdata,scdata,coord,max((i-50)/(epoch-50),0))
for loss in self.loss_names:
loss_curve[loss].append(getattr(self, 'loss_' + loss).item())
self.lr_scheduler.step()
loss_msg = '[Train][{}] Loss:'.format(i)
for loss in self.loss_names:
loss_msg += ' {} {:.3f}'.format(loss, loss_curve[loss][-1])
if (i + 1) % 1 == 0:
if self.verbose:
print(loss_msg)
print(self.lr_scheduler.get_last_lr())
with open(self.train_log, 'a') as f:
f.write(loss_msg + "\n")
return loss_curve
|
/scSTEM-0.0.2-py3-none-any.whl/STEM/model.py
| 0.846101 | 0.339499 |
model.py
|
pypi
|
import tensorflow as tf
def _variable_with_weight_decay(name, shape, stddev, wd):
"""
Helper to create an initialized Variable with weight decay.
Note that the Variable is initialized with a truncated normal distribution.
A weight decay is added only if one is specified.
Args:
name: name of the variable
shape: list of ints
stddev: standard deviation of a truncated Gaussian
wd: add L2Loss weight decay multiplied by this float. If None, weight
decay is not added for this Variable.
Returns:
Variable Tensor
Altschuler & Wu Lab 2018.
Software provided as is under Apache License 2.0.
"""
dtype = tf.float32
var = _variable_on_cpu(
name,
shape,
tf.truncated_normal_initializer(stddev=stddev, dtype=dtype))
if wd != 0:
weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss')
tf.add_to_collection('losses', weight_decay)
return var
def _variable_on_cpu(name, shape, initializer):
"""Helper to create a Variable stored on CPU memory.
Args:
name: name of the variable
shape: list of ints
initializer: initializer for Variable
Returns:
Variable Tensor
Altschuler & Wu Lab 2018.
Software provided as is under Apache License 2.0.
"""
with tf.device('/cpu:0'):
dtype = tf.float32
var = tf.get_variable(
name, shape, initializer=initializer, dtype=dtype)
return var
def average_gradients(tower_grads):
""" Summarize the gradient calculated by each GPU.
Altschuler & Wu Lab 2018.
Software provided as is under Apache License 2.0.
"""
average_grads = []
for grad_and_vars in zip(*tower_grads):
# Note that each grad_and_vars looks like the following:
# ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))
grads = []
for g, var1 in grad_and_vars:
# Add 0 dimension to the gradients to represent the tower.
expanded_g = tf.expand_dims(g, 0)
# Append on a 'tower' dimension which we will average over below.
grads.append(expanded_g)
# Average over the 'tower' dimension.
grad = tf.concat(axis=0, values=grads)
grad = tf.reduce_mean(grad, 0)
v = grad_and_vars[0][1]
grad_and_var = (grad, v)
average_grads.append(grad_and_var)
return average_grads
|
/scScope_cpu-0.1.5.tar.gz/scScope_cpu-0.1.5/scscope/ops.py
| 0.844409 | 0.578865 |
ops.py
|
pypi
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.