-
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
Open
LeonStadelmann
wants to merge
9
commits into
main
Choose a base branch
from
add/new_PCAMetrics
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 5 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
54e2e9e
init
LeonStadelmann 577da5a
Add method
LeonStadelmann 5574c8f
Add test
LeonStadelmann e960ee1
fix typo
LeonStadelmann ca25068
Allow for dense and layer input
LeonStadelmann 41a7dff
Pass validation adata in init
LeonStadelmann dea483f
Add new matrix to docs
LeonStadelmann 4eb6182
Merge branch 'main' into add/new_PCAMetrics
LeonStadelmann c37431c
Add func arguments
LeonStadelmann File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,6 +6,7 @@ | |
| import jax.tree as jt | ||
| import jax.tree_util as jtu | ||
| import numpy as np | ||
| import scipy | ||
|
|
||
| from cellflow._types import ArrayLike | ||
| from cellflow.metrics._metrics import ( | ||
|
|
@@ -14,6 +15,7 @@ | |
| compute_scalar_mmd, | ||
| compute_sinkhorn_div, | ||
| ) | ||
| from cellflow.solvers import _genot, _otfm | ||
|
|
||
| __all__ = [ | ||
| "BaseCallback", | ||
|
|
@@ -23,6 +25,7 @@ | |
| "WandbLogger", | ||
| "CallbackRunner", | ||
| "PCADecodedMetrics", | ||
| "PCADecodedMetrics2", | ||
| "VAEDecodedMetrics", | ||
| ] | ||
|
|
||
|
|
@@ -266,6 +269,103 @@ 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. | ||
| layer | ||
| Key in :attr:`~anndata.AnnData.layers` from which to get the counts. | ||
| If :obj:`None`, use :attr:`~anndata.AnnData.X`. | ||
| 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", | ||
| layers: str | None = None, | ||
| 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.layers = layers | ||
| 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: | ||
| condition_mask = self.validation_adata[name].obs[self.condition_id_key] == cond | ||
| counts = ( | ||
| self.validation_adata[name][condition_mask].X | ||
| if self.layers is None | ||
| else self.validation_adata[name][condition_mask].layers[self.layers] | ||
| ) | ||
| true_counts[name][cond] = counts.toarray() if scipy.sparse.issparse(counts) else counts | ||
|
|
||
| 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 | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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( | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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?