-
Notifications
You must be signed in to change notification settings - Fork 1.6k
2571 add DecollateBatch handler #2584
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
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
42a45e0
Merge pull request #19 from Project-MONAI/master
Nic-Ma cd16a13
Merge pull request #32 from Project-MONAI/master
Nic-Ma a5b2615
Merge pull request #171 from Project-MONAI/dev
Nic-Ma 781ec5c
[DLMED] add DecollateBatch handler
Nic-Ma 36225cb
[DLMED] add unit tests
Nic-Ma 82c630a
[DLMED] enhance doc-string
Nic-Ma b46d30a
Merge branch 'dev' into 2571-add-decollate-handler
Nic-Ma 67b4e34
[MONAI] python code formatting
monai-bot 591fa09
[DLMED] skip in min tests
Nic-Ma 7656fcd
Merge branch 'dev' into 2571-add-decollate-handler
Nic-Ma 1c0206b
Merge branch 'dev' into 2571-add-decollate-handler
Nic-Ma 70a9665
[DLMED] update according to comments
Nic-Ma c9b696c
[DLMED] fix flake8
Nic-Ma 182df87
[DLMED] remove rep_scalar option
Nic-Ma 659afcb
Merge branch 'dev' into 2571-add-decollate-handler
Nic-Ma 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
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 |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| # Copyright 2020 - 2021 MONAI Consortium | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from typing import TYPE_CHECKING, Optional | ||
|
|
||
| from monai.config import IgniteInfo, KeysCollection | ||
| from monai.engines.utils import IterationEvents | ||
| from monai.transforms import Decollated | ||
| from monai.utils import min_version, optional_import | ||
|
|
||
| Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events") | ||
| if TYPE_CHECKING: | ||
| from ignite.engine import Engine | ||
| else: | ||
| Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") | ||
|
|
||
|
|
||
| class DecollateBatch: | ||
| """ | ||
| Ignite handler to execute the `decollate batch` logic for `engine.state.batch` and `engine.state.output`. | ||
| Typical usage is to set `decollate=False` in the engine and execute some postprocessing logic first | ||
| then decollate the batch, otherwise, engine will decollate batch before the postprocessing. | ||
|
|
||
| Args: | ||
| event: expected EVENT to attach the handler, should be "MODEL_COMPLETED" or "ITERATION_COMPLETED". | ||
| default to "MODEL_COMPLETED". | ||
| detach: whether to detach the tensors. scalars tensors will be detached into number types | ||
| instead of torch tensors. | ||
| decollate_batch: whether to decollate `engine.state.batch` of ignite engine. | ||
| batch_keys: if `decollate_batch=True`, specify the keys of the corresponding items to decollate | ||
| in `engine.state.batch`, note that it will delete other keys not specified. if None, | ||
| will decollate all the keys. it replicates the scalar values to every item of the decollated list. | ||
| decollate_output: whether to decollate `engine.state.output` of ignite engine. | ||
| output_keys: if `decollate_output=True`, specify the keys of the corresponding items to decollate | ||
| in `engine.state.output`, note that it will delete other keys not specified. if None, | ||
| will decollate all the keys. it replicates the scalar values to every item of the decollated list. | ||
| allow_missing_keys: don't raise exception if key is missing. | ||
|
|
||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| event: str = "MODEL_COMPLETED", | ||
| detach: bool = True, | ||
| decollate_batch: bool = True, | ||
| batch_keys: Optional[KeysCollection] = None, | ||
| decollate_output: bool = True, | ||
| output_keys: Optional[KeysCollection] = None, | ||
| allow_missing_keys: bool = False, | ||
| ): | ||
| event = event.upper() | ||
| if event not in ("MODEL_COMPLETED", "ITERATION_COMPLETED"): | ||
| raise ValueError("event should be `MODEL_COMPLETED` or `ITERATION_COMPLETED`.") | ||
| self.event = event | ||
|
|
||
| self.batch_transform = ( | ||
| Decollated(keys=batch_keys, detach=detach, allow_missing_keys=allow_missing_keys) | ||
| if decollate_batch | ||
| else None | ||
| ) | ||
|
|
||
| self.output_transform = ( | ||
| Decollated(keys=output_keys, detach=detach, allow_missing_keys=allow_missing_keys) | ||
| if decollate_output | ||
| else None | ||
| ) | ||
|
|
||
| def attach(self, engine: Engine) -> None: | ||
| """ | ||
| Args: | ||
| engine: Ignite Engine, it can be a trainer, validator or evaluator. | ||
| """ | ||
| if self.event == "MODEL_COMPLETED": | ||
| engine.add_event_handler(IterationEvents.MODEL_COMPLETED, self) | ||
| else: | ||
| engine.add_event_handler(Events.ITERATION_COMPLETED, self) | ||
|
|
||
| def __call__(self, engine: Engine) -> None: | ||
| """ | ||
| Args: | ||
| engine: Ignite Engine, it can be a trainer, validator or evaluator. | ||
| """ | ||
| if self.batch_transform is not None: | ||
| engine.state.batch = self.batch_transform(engine.state.batch) | ||
| if self.output_transform is not None: | ||
| engine.state.output = self.output_transform(engine.state.output) | ||
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
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 |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| # Copyright 2020 - 2021 MONAI Consortium | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import unittest | ||
|
|
||
| import torch | ||
|
|
||
| from monai.engines import SupervisedEvaluator | ||
| from monai.handlers import DecollateBatch, PostProcessing | ||
| from monai.transforms import Activationsd, AsDiscreted, Compose, CopyItemsd | ||
|
|
||
|
|
||
| class TestHandlerDecollateBatch(unittest.TestCase): | ||
| def test_compute(self): | ||
| data = [ | ||
| {"image": torch.tensor([[[[2.0], [3.0]]]]), "filename": ["test1"]}, | ||
| {"image": torch.tensor([[[[6.0], [8.0]]]]), "filename": ["test2"]}, | ||
| ] | ||
|
|
||
| handlers = [ | ||
| DecollateBatch(event="MODEL_COMPLETED"), | ||
| PostProcessing( | ||
| transform=Compose( | ||
| [ | ||
| Activationsd(keys="pred", sigmoid=True), | ||
| CopyItemsd(keys="filename", times=1, names="filename_bak"), | ||
| AsDiscreted(keys="pred", threshold_values=True, to_onehot=True, n_classes=2), | ||
| ] | ||
| ) | ||
| ), | ||
| ] | ||
| # set up engine, PostProcessing handler works together with postprocessing transforms of engine | ||
| engine = SupervisedEvaluator( | ||
| device=torch.device("cpu:0"), | ||
| val_data_loader=data, | ||
| epoch_length=2, | ||
| network=torch.nn.PReLU(), | ||
| # set decollate=False and execute some postprocessing first, then decollate in handlers | ||
| postprocessing=lambda x: dict(pred=x["pred"] + 1.0), | ||
| decollate=False, | ||
| val_handlers=handlers, | ||
| ) | ||
| engine.run() | ||
|
|
||
| expected = torch.tensor([[[[1.0], [1.0]], [[0.0], [0.0]]]]) | ||
|
|
||
| for o, e in zip(engine.state.output, expected): | ||
| torch.testing.assert_allclose(o["pred"], e) | ||
| filename = o.get("filename_bak") | ||
| if filename is not None: | ||
| self.assertEqual(filename, "test2") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
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
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.
Uh oh!
There was an error while loading. Please reload this page.