-
Notifications
You must be signed in to change notification settings - Fork 16
Add PCADecoderMetrics2 #242
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 4 commits
54e2e9e
577da5a
5574c8f
e960ee1
ca25068
41a7dff
dea483f
4eb6182
c37431c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,6 +14,7 @@ | |
| compute_scalar_mmd, | ||
| compute_sinkhorn_div, | ||
| ) | ||
| from cellflow.solvers import _genot, _otfm | ||
|
|
||
| __all__ = [ | ||
| "BaseCallback", | ||
|
|
@@ -23,6 +24,7 @@ | |
| "WandbLogger", | ||
| "CallbackRunner", | ||
| "PCADecodedMetrics", | ||
| "PCADecodedMetrics2", | ||
| "VAEDecodedMetrics", | ||
| ] | ||
|
|
||
|
|
@@ -266,6 +268,94 @@ def on_log_iteration( | |
| return metrics | ||
|
|
||
|
|
||
| class PCADecodedMetrics2(Metrics): | ||
| """Callback to compute metrics on true validation data during training | ||
|
|
||
| Parameters | ||
| ---------- | ||
| ref_adata | ||
| An :class:`~anndata.AnnData` object with the reference data containing | ||
| ``adata.varm["X_mean"]`` and ``adata.varm["PCs"]``. | ||
| metrics | ||
| List of metrics to compute. Supported metrics are ``"r_squared"``, ``"mmd"``, | ||
| ``"sinkhorn_div"``, and ``"e_distance"``. | ||
| metric_aggregations | ||
| List of aggregation functions to use for each metric. Supported aggregations are ``"mean"`` | ||
| and ``"median"``. | ||
| condition_id_key | ||
| Key in :attr:`~anndata.AnnData.obs` that defines the condition id. | ||
| log_prefix | ||
| Prefix to add to the log keys. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| ref_adata: ad.AnnData, | ||
| metrics: list[Literal["r_squared", "mmd", "sinkhorn_div", "e_distance"]], | ||
| metric_aggregations: list[Literal["mean", "median"]] = None, | ||
| condition_id_key: str = "condition", | ||
| log_prefix: str = "pca_decoded_2_", | ||
| ): | ||
| super().__init__(metrics, metric_aggregations) | ||
| self.pcs = ref_adata.varm["PCs"] | ||
| self.means = ref_adata.varm["X_mean"] | ||
| self.reconstruct_data = lambda x: x @ np.transpose(self.pcs) + np.transpose(self.means) | ||
| self.condition_id_key = condition_id_key | ||
| self.log_prefix = log_prefix | ||
|
|
||
| def add_validation_adata( | ||
|
||
| self, | ||
| validation_adata: dict[str, ad.AnnData], | ||
| ) -> None: | ||
| self.validation_adata = validation_adata | ||
|
|
||
| def on_log_iteration( | ||
| self, | ||
| valid_source_data: dict[str, dict[str, ArrayLike]], | ||
| valid_true_data: dict[str, dict[str, ArrayLike]], | ||
| valid_pred_data: dict[str, dict[str, ArrayLike]], | ||
| solver: _genot.GENOT | _otfm.OTFlowMatching, | ||
| ) -> dict[str, float]: | ||
| """Called at each validation/log iteration to reconstruct the data and compute metrics on the reconstruction | ||
|
|
||
| Parameters | ||
| ---------- | ||
| valid_source_data | ||
| Source data in nested dictionary format with same keys as ``valid_true_data`` | ||
| valid_true_data | ||
| Validation data in nested dictionary format with same keys as ``valid_pred_data`` | ||
| valid_pred_data | ||
| Predicted data in nested dictionary format with same keys as ``valid_true_data`` | ||
| solver | ||
| :class:`~cellflow.solvers.OTFlowMatching` solver or :class:`~cellflow.solvers.GENOT` | ||
| solver with a conditional velocity field. | ||
| """ | ||
| true_counts = {} | ||
| for name in self.validation_adata.keys(): | ||
| true_counts[name] = {} | ||
| conditions_adata = set(self.validation_adata[name].obs[self.condition_id_key].unique()) | ||
| conditions_pred = valid_pred_data[name].keys() | ||
| for cond in conditions_adata & conditions_pred: | ||
| true_counts[name][cond] = self.validation_adata[name][ | ||
| self.validation_adata[name].obs[self.condition_id_key] == cond | ||
| ].X.toarray() | ||
|
||
|
|
||
| predicted_data_decoded = jtu.tree_map(self.reconstruct_data, valid_pred_data) | ||
|
|
||
| metrics = super().on_log_iteration(true_counts, predicted_data_decoded) | ||
| metrics = {f"{self.log_prefix}{k}": v for k, v in metrics.items()} | ||
| return metrics | ||
|
|
||
| def on_train_end( | ||
| self, | ||
| valid_source_data: dict[str, dict[str, ArrayLike]], | ||
| valid_true_data: dict[str, dict[str, ArrayLike]], | ||
| valid_pred_data: dict[str, dict[str, ArrayLike]], | ||
| solver: _genot.GENOT | _otfm.OTFlowMatching, | ||
| ) -> dict[str, float]: | ||
| return self.on_log_iteration(valid_source_data, valid_true_data, valid_pred_data, solver) | ||
|
|
||
|
|
||
| class VAEDecodedMetrics(Metrics): | ||
| """Callback to compute metrics on decoded validation data during training | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,14 +1,15 @@ | ||
| from collections.abc import Sequence | ||
| from typing import Any, Literal | ||
|
|
||
| import anndata as ad | ||
| import jax | ||
| import numpy as np | ||
| from numpy.typing import ArrayLike | ||
| from tqdm import tqdm | ||
|
|
||
| from cellflow.data._dataloader import TrainSampler, ValidationSampler | ||
| from cellflow.solvers import _genot, _otfm | ||
| from cellflow.training._callbacks import BaseCallback, CallbackRunner | ||
| from cellflow.training._callbacks import BaseCallback, CallbackRunner, PCADecodedMetrics2 | ||
|
|
||
|
|
||
| class CellFlowTrainer: | ||
|
|
@@ -31,12 +32,14 @@ class CellFlowTrainer: | |
| def __init__( | ||
| self, | ||
| solver: _otfm.OTFlowMatching | _genot.GENOT, | ||
| validation_adata: dict[str, ad.AnnData], | ||
| seed: int = 0, | ||
| ): | ||
| if not isinstance(solver, (_otfm.OTFlowMatching | _genot.GENOT)): | ||
| raise NotImplementedError(f"Solver must be an instance of OTFlowMatching or GENOT, got {type(solver)}") | ||
|
|
||
| self.solver = solver | ||
| self.validation_adata = validation_adata | ||
| self.rng_subsampling = np.random.default_rng(seed) | ||
| self.training_logs: dict[str, Any] = {} | ||
|
|
||
|
|
@@ -103,6 +106,10 @@ def train( | |
| self.training_logs = {"loss": []} | ||
| rng = jax.random.PRNGKey(0) | ||
|
|
||
| for callback in callbacks: | ||
| if isinstance(callback, PCADecodedMetrics2): | ||
| callback.add_validation_adata(self.validation_adata) | ||
|
||
|
|
||
| # Initiate callbacks | ||
| valid_loaders = valid_loaders or {} | ||
| crun = CallbackRunner( | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can we make these attributes of the callbacks directly?