Upload pathology_nuclei_classification version 0.2.1
Browse filesFiles changed (19)
- .gitattributes+1
- LICENSEAdded+201
- configs/evaluate.jsonAdded+77
- configs/inference.jsonAdded+120
- configs/inference_trt.jsonAdded+6
- configs/logging.confAdded+21
- configs/metadata.jsonAdded+108
- configs/multi_gpu_evaluate.jsonAdded+36
- configs/multi_gpu_train.jsonAdded+44
- configs/train.jsonAdded+364
- docs/README.mdAdded+232
- docs/data_license.txtAdded+6
- models/model.ptAdded+3
- models/model.tsAdded+3
- scripts/__init__.pyAdded+13
- scripts/data_process.pyAdded+79
- scripts/dataset.pyAdded+189
- scripts/handlers.pyAdded+141
- scripts/writer.pyAdded+54
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textmodels/model.ts filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677{ "validate#dataset#cache_rate": 0, "validate#postprocessing": { "_target_": "Compose", "transforms": [ { "_target_": "Activationsd", "keys": "pred", "softmax": true }, { "_target_": "AsDiscreted", "keys": [ "pred", "label" ], "argmax": [ true, false ], "to_onehot": 4 }, { "_target_": "ToTensord", "keys": [ "pred", "label" ], "device": "@device" }, { "_target_": "SaveImaged", "_disabled_": true, "keys": "pred", "meta_keys": "pred_meta_dict", "output_dir": "@output_dir", "output_ext": ".json" } ] }, "validate#handlers": [ { "_target_": "CheckpointLoader", "load_path": "$@ckpt_dir + '/model.pt'", "load_dict": { "model": "@network" } }, { "_target_": "StatsHandler", "iteration_log": false }, { "_target_": "MetricsSaver", "save_dir": "@output_dir", "metrics": [ "val_f1", "val_accuracy" ], "metric_details": [ "val_f1" ], "batch_transform": "$monai.handlers.from_engine(['image_meta_dict'])", "summary_ops": "*" } ], "initialize": [ "$import sys", "$sys.path.append(@bundle_root)", "$monai.utils.set_determinism(seed=123)", "$import scripts", "$monai.data.register_writer('json', scripts.ClassificationWriter)" ], "run": [ "$@validate#evaluator.run()" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120{ "imports": [ "$import glob", "$import json", "$import pathlib", "$import os" ], "bundle_root": ".", "checkpoint": "$@bundle_root + '/models/model.pt'", "output_dir": "$@bundle_root + '/eval'", "dataset_dir": "/workspace/data/CoNSePNuclei", "images": "$list(sorted(glob.glob(@dataset_dir + '/Test/Images/*.png')))[:1]", "labels": "$list(sorted(glob.glob(@dataset_dir + '/Test/Labels/*.png')))[:1]", "input_data": "$[{'image': i, 'label': l} for i,l in zip(@images, @labels)]", "device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')", "network_def": { "_target_": "DenseNet121", "spatial_dims": 2, "in_channels": 4, "out_channels": 4 }, "network": "$@network_def.to(@device)", "preprocessing": { "_target_": "Compose", "transforms": [ { "_target_": "LoadImaged", "keys": [ "image", "label" ], "dtype": "uint8", "image_only": false }, { "_target_": "EnsureChannelFirstd", "keys": [ "image", "label" ] }, { "_target_": "ScaleIntensityRanged", "keys": "image", "a_min": 0.0, "a_max": 255.0, "b_min": -1.0, "b_max": 1.0 }, { "_target_": "AddLabelAsGuidanced", "keys": "image", "source": "label" } ] }, "dataset": { "_target_": "Dataset", "data": "@input_data", "transform": "@preprocessing" }, "dataloader": { "_target_": "DataLoader", "dataset": "@dataset", "batch_size": 1, "shuffle": false, "num_workers": 4 }, "inferer": { "_target_": "SimpleInferer" }, "postprocessing": { "_target_": "Compose", "transforms": [ { "_target_": "Activationsd", "keys": "pred", "softmax": true }, { "_target_": "SaveImaged", "keys": "pred", "meta_keys": "pred_meta_dict", "output_dir": "@output_dir", "output_ext": ".json" } ] }, "handlers": [ { "_target_": "CheckpointLoader", "load_path": "$@checkpoint", "load_dict": { "model": "@network" } }, { "_target_": "StatsHandler", "iteration_log": false } ], "evaluator": { "_target_": "SupervisedEvaluator", "device": "@device", "val_data_loader": "@dataloader", "network": "@network", "inferer": "@inferer", "postprocessing": "@postprocessing", "val_handlers": "@handlers", "amp": true }, "initialize": [ "$monai.utils.set_determinism(seed=123)", "$import scripts", "$monai.data.register_writer('json', scripts.ClassificationWriter)" ], "run": [ "$@evaluator.run()" ]}123456{ "+imports": [ "$from monai.networks import trt_compile" ], "network": "$trt_compile(@network_def.to(@device), @checkpoint)"}123456789101112131415161718192021[loggers]keys=root
[handlers]keys=consoleHandler
[formatters]keys=fullFormatter
[logger_root]level=INFOhandlers=consoleHandler
[handler_consoleHandler]class=StreamHandlerlevel=INFOformatter=fullFormatterargs=(sys.stdout,)
[formatter_fullFormatter]format=%(asctime)s - %(name)s - %(levelname)s - %(message)s123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108{ "schema": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/meta_schema_20240725.json", "version": "0.2.1", "changelog": { "0.2.1": "update to huggingface hosting", "0.2.0": "update issue for IgniteInfo", "0.1.9": "update tensorrt benchmark results", "0.1.8": "enable tensorrt", "0.1.7": "update to use monai 1.3.1", "0.1.6": "set image_only to False", "0.1.5": "add support for TensorRT conversion and inference", "0.1.4": "fix the wrong GPU index issue of multi-node", "0.1.3": "remove error dollar symbol in readme", "0.1.2": "add RAM warning", "0.1.1": "enable deterministic eval and inference", "0.1.0": "Update deterministic results", "0.0.9": "Update README Formatting", "0.0.8": "enable deterministic training", "0.0.7": "update benchmark on A100", "0.0.6": "adapt to BundleWorkflow interface", "0.0.5": "add name tag", "0.0.4": "Fix evaluation", "0.0.3": "Update to use MONAI 1.1.0", "0.0.2": "Update The Torch Vision Transform", "0.0.1": "initialize the model package structure" }, "monai_version": "1.4.0", "pytorch_version": "2.4.0", "numpy_version": "1.24.4", "required_packages_version": { "nibabel": "5.2.1", "pytorch-ignite": "0.4.11", "torchvision": "0.19.0", "scipy": "1.13.1", "scikit-learn": "1.5.1", "tensorboard": "2.17.0", "scikit-image": "0.23.2" }, "supported_apps": {}, "name": "Pathology nuclei classification", "task": "Pathology Nuclei classification", "description": "A pre-trained model for Nuclei Classification within Haematoxylin & Eosin stained histology images", "authors": "MONAI team", "copyright": "Copyright (c) MONAI Consortium", "data_source": "consep_dataset.zip from https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet", "data_type": "png", "image_classes": "RGB channel data, intensity scaled to [0, 1]", "label_classes": "single channel data", "pred_classes": "4 channels OneHot data, channel 0 is Other, channel 1 is Inflammatory, channel 2 is Epithelial, channel 3 is Spindle-Shaped", "eval_metrics": { "f1_score": 0.852 }, "intended_use": "This is an example, not to be used for diagnostic purposes", "references": [ "S. Graham, Q. D. Vu, S. E. A. Raza, A. Azam, Y-W. Tsang, J. T. Kwak and N. Rajpoot. \"HoVer-Net: Simultaneous Segmentation and Classification of Nuclei in Multi-Tissue Histology Images.\" Medical Image Analysis, Sept. 2019. https://doi.org/10.1016/j.media.2019.101563" ], "network_data_format": { "inputs": { "image": { "type": "magnitude", "format": "RGB", "modality": "regular", "num_channels": 4, "spatial_shape": [ 128, 128 ], "dtype": "float32", "value_range": [ 0, 1 ], "is_patch_data": false, "channel_def": { "0": "R", "1": "G", "2": "B", "3": "Mask" } } }, "outputs": { "pred": { "type": "probabilities", "format": "classes", "num_channels": 4, "spatial_shape": [ 1, 4 ], "dtype": "float32", "value_range": [ 0, 1, 2, 3 ], "is_patch_data": false, "channel_def": { "0": "Other", "1": "Inflammatory", "2": "Epithelial", "3": "Spindle-Shaped" } } } }}123456789101112131415161718192021222324252627282930313233343536{ "device": "$torch.device('cuda:' + os.environ['LOCAL_RANK'])", "network": { "_target_": "torch.nn.parallel.DistributedDataParallel", "module": "$@network_def.to(@device)", "device_ids": [ "@device" ] }, "validate#sampler": { "_target_": "DistributedSampler", "dataset": "@validate#dataset", "even_divisible": false, "shuffle": false }, "validate#dataloader#sampler": "@validate#sampler", "validate#handlers#1#_disabled_": "$dist.get_rank() > 0", "initialize": [ "$import sys", "$sys.path.append(@bundle_root)", "$import torch.distributed as dist", "$dist.is_initialized() or dist.init_process_group(backend='nccl')", "$torch.cuda.set_device(@device)", "$monai.utils.set_determinism(seed=123)", "$import logging", "$@validate#evaluator.logger.setLevel(logging.WARNING if dist.get_rank() > 0 else logging.INFO)", "$import scripts", "$monai.data.register_writer('json', scripts.ClassificationWriter)" ], "run": [ "$@validate#evaluator.run()" ], "finalize": [ "$dist.is_initialized() and dist.destroy_process_group()" ]}1234567891011121314151617181920212223242526272829303132333435363738394041424344{ "device": "$torch.device('cuda:' + os.environ['LOCAL_RANK'])", "network": { "_target_": "torch.nn.parallel.DistributedDataParallel", "module": "$@network_def.to(@device)", "device_ids": [ "@device" ] }, "train#sampler": { "_target_": "DistributedSampler", "dataset": "@train#dataset", "even_divisible": true, "shuffle": true }, "train#dataloader#sampler": "@train#sampler", "train#dataloader#shuffle": false, "train#trainer#train_handlers": "$@train#handlers[: -2 if dist.get_rank() > 0 else None]", "validate#sampler": { "_target_": "DistributedSampler", "dataset": "@validate#dataset", "even_divisible": false, "shuffle": false }, "validate#dataloader#sampler": "@validate#sampler", "validate#evaluator#val_handlers": "$None if dist.get_rank() > 0 else @validate#handlers", "initialize": [ "$import sys", "$sys.path.append(@bundle_root)", "$import torch.distributed as dist", "$dist.is_initialized() or dist.init_process_group(backend='nccl')", "$torch.cuda.set_device(@device)", "$monai.utils.set_determinism(seed=123)", "$import logging", "$@train#trainer.logger.setLevel(logging.WARNING if dist.get_rank() > 0 else logging.INFO)", "$@validate#evaluator.logger.setLevel(logging.WARNING if dist.get_rank() > 0 else logging.INFO)" ], "run": [ "$@train#trainer.run()" ], "finalize": [ "$dist.is_initialized() and dist.destroy_process_group()" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364{ "imports": [ "$import glob", "$import ignite", "$import json", "$import pathlib", "$import os" ], "bundle_root": ".", "ckpt_dir": "$@bundle_root + '/models'", "output_dir": "$@bundle_root + '/eval'", "dataset_dir": "/workspace/data/CoNSePNuclei", "dataset_json": "$@dataset_dir + '/dataset.json'", "train_datalist": "$json.loads(pathlib.Path(@dataset_json).read_text())['training']", "val_datalist": "$json.loads(pathlib.Path(@dataset_json).read_text())['validation']", "val_interval": 1, "device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')", "network_def": { "_target_": "DenseNet121", "spatial_dims": 2, "in_channels": 4, "out_channels": 4 }, "network": "$@network_def.to(@device)", "loss": { "_target_": "torch.nn.CrossEntropyLoss" }, "optimizer": { "_target_": "torch.optim.Adam", "params": "$@network.parameters()", "lr": 0.0001, "weight_decay": 1e-05 }, "lr_scheduler": { "_target_": "torch.optim.lr_scheduler.StepLR", "optimizer": "@optimizer", "step_size": 50 }, "max_epochs": 100, "train": { "preprocessing": { "_target_": "Compose", "transforms": [ { "_target_": "LoadImaged", "keys": [ "image", "label" ], "dtype": "uint8", "image_only": false }, { "_target_": "EnsureChannelFirstd", "keys": [ "image", "label" ] }, { "_target_": "SplitLabeld", "keys": "label", "mask_value": "", "others_value": 255, "to_binary_mask": false }, { "_target_": "RandTorchVisiond", "keys": "image", "name": "ColorJitter", "brightness": 0.25, "contrast": 0.75, "saturation": 0.25, "hue": 0.04 }, { "_target_": "RandFlipd", "keys": [ "image", "label", "others" ], "prob": 0.5 }, { "_target_": "RandRotate90d", "keys": [ "image", "label", "others" ], "prob": 0.5 }, { "_target_": "ScaleIntensityRanged", "keys": "image", "a_min": 0.0, "a_max": 255.0, "b_min": -1.0, "b_max": 1.0 }, { "_target_": "AddLabelAsGuidanced", "keys": "image", "source": "label" }, { "_target_": "SetLabelClassd", "keys": "label", "offset": -1 }, { "_target_": "SelectItemsd", "keys": [ "image", "label" ] } ] }, "dataset": { "_target_": "CacheDataset", "data": "@train_datalist", "transform": "@train#preprocessing", "cache_rate": 1.0, "num_workers": 4 }, "dataloader": { "_target_": "DataLoader", "dataset": "@train#dataset", "batch_size": 64, "shuffle": true, "num_workers": 4 }, "inferer": { "_target_": "SimpleInferer" }, "postprocessing": { "_target_": "Compose", "transforms": [ { "_target_": "Activationsd", "keys": "pred", "softmax": true }, { "_target_": "AsDiscreted", "keys": [ "pred", "label" ], "argmax": [ true, false ], "to_onehot": 4 }, { "_target_": "ToTensord", "keys": [ "pred", "label" ], "device": "@device" } ] }, "handlers": [ { "_target_": "LrScheduleHandler", "lr_scheduler": "@lr_scheduler", "print_lr": true }, { "_target_": "ValidationHandler", "validator": "@validate#evaluator", "epoch_level": true, "interval": "@val_interval" }, { "_target_": "StatsHandler", "tag_name": "train_loss", "output_transform": "$monai.handlers.from_engine(['loss'], first=True)" }, { "_target_": "TensorBoardStatsHandler", "log_dir": "@output_dir", "tag_name": "train_loss", "output_transform": "$monai.handlers.from_engine(['loss'], first=True)" }, { "_target_": "scripts.TensorBoardImageHandler", "class_names": { "0": "Other", "1": "Inflammatory", "2": "Epithelial", "3": "Spindle-Shaped" }, "log_dir": "@output_dir", "batch_limit": 4, "tag_name": "train" } ], "key_metric": { "train_f1": { "_target_": "ConfusionMatrix", "metric_name": "f1 score", "output_transform": "$monai.handlers.from_engine(['pred', 'label'])" } }, "trainer": { "_target_": "SupervisedTrainer", "max_epochs": "@max_epochs", "device": "@device", "train_data_loader": "@train#dataloader", "network": "@network", "loss_function": "@loss", "optimizer": "@optimizer", "inferer": "@train#inferer", "postprocessing": "@train#postprocessing", "key_train_metric": "@train#key_metric", "train_handlers": "@train#handlers", "amp": true } }, "validate": { "preprocessing": { "_target_": "Compose", "transforms": [ { "_target_": "LoadImaged", "keys": [ "image", "label" ], "dtype": "uint8", "image_only": false }, { "_target_": "EnsureChannelFirstd", "keys": [ "image", "label" ] }, { "_target_": "SplitLabeld", "keys": "label", "mask_value": "", "others_value": 255, "to_binary_mask": false }, { "_target_": "ScaleIntensityRanged", "keys": "image", "a_min": 0.0, "a_max": 255.0, "b_min": -1.0, "b_max": 1.0 }, { "_target_": "AddLabelAsGuidanced", "keys": "image", "source": "label" }, { "_target_": "SetLabelClassd", "keys": "label", "offset": -1 }, { "_target_": "SelectItemsd", "keys": [ "image", "label", "image_meta_dict" ] } ] }, "dataset": { "_target_": "CacheDataset", "data": "@val_datalist", "transform": "@validate#preprocessing", "cache_rate": 1.0 }, "dataloader": { "_target_": "DataLoader", "dataset": "@validate#dataset", "batch_size": 64, "shuffle": false, "num_workers": 4 }, "inferer": { "_target_": "SimpleInferer" }, "postprocessing": "%train#postprocessing", "handlers": [ { "_target_": "StatsHandler", "iteration_log": false }, { "_target_": "TensorBoardStatsHandler", "log_dir": "@output_dir", "iteration_log": false }, { "_target_": "CheckpointSaver", "save_dir": "@ckpt_dir", "save_dict": { "model": "@network" }, "save_key_metric": true, "key_metric_filename": "model.pt" }, { "_target_": "scripts.TensorBoardImageHandler", "class_names": { "0": "Other", "1": "Inflammatory", "2": "Epithelial", "3": "Spindle-Shaped" }, "log_dir": "@output_dir", "batch_limit": 8, "tag_name": "val" } ], "key_metric": { "val_f1": { "_target_": "ConfusionMatrix", "metric_name": "f1 score", "output_transform": "$monai.handlers.from_engine(['pred', 'label'])" } }, "additional_metrics": { "val_accuracy": { "_target_": "ignite.metrics.Accuracy", "output_transform": "$monai.handlers.from_engine(['pred', 'label'])" } }, "evaluator": { "_target_": "SupervisedEvaluator", "device": "@device", "val_data_loader": "@validate#dataloader", "network": "@network", "inferer": "@validate#inferer", "postprocessing": "@validate#postprocessing", "key_val_metric": "@validate#key_metric", "additional_metrics": "@validate#additional_metrics", "val_handlers": "@validate#handlers", "amp": true } }, "initialize": [ "$import sys", "$sys.path.append(@bundle_root)", "$monai.utils.set_determinism(seed=123)" ], "run": [ "$@train#trainer.run()" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232# Model OverviewA pre-trained model for classifying nuclei cells as the following types - Other - Inflammatory - Epithelial - Spindle-Shaped
This model is trained using [DenseNet121](https://docs.monai.io/en/latest/networks.html#densenet121) over [ConSeP](https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet) dataset.
## DataThe training dataset is from https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet```commandlinewget https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet/consep_dataset.zipunzip -q consep_dataset.zip```<br/>
### PreprocessingAfter [downloading this dataset](https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet/consep_dataset.zip),python script `data_process.py` from `scripts` folder can be used to preprocess and generate the final dataset for training.
```commandlinepython scripts/data_process.py --input /path/to/data/CoNSeP --output /path/to/data/CoNSePNuclei```
After generating the output files, please modify the `dataset_dir` parameter specified in `configs/train.json` and `configs/inference.json` to reflect the output folder which contains new dataset.json.
Class values in dataset are
- 1 = other - 2 = inflammatory - 3 = healthy epithelial - 4 = dysplastic/malignant epithelial - 5 = fibroblast - 6 = muscle - 7 = endothelial
As part of pre-processing, the following steps are executed.
- Crop and Extract each nuclei Image + Label (128x128) based on the centroid given in the dataset. - Combine classes 3 & 4 into the epithelial class and 5,6 & 7 into the spindle-shaped class. - Update the label index for the target nuclie based on the class value - Other cells which are part of the patch are modified to have label idex = 255
Example `dataset.json` in output folder:```json{ "training": [ { "image": "/workspace/data/CoNSePNuclei/Train/Images/train_1_3_0001.png", "label": "/workspace/data/CoNSePNuclei/Train/Labels/train_1_3_0001.png", "nuclei_id": 1, "mask_value": 3, "centroid": [ 64, 64 ] } ], "validation": [ { "image": "/workspace/data/CoNSePNuclei/Test/Images/test_1_3_0001.png", "label": "/workspace/data/CoNSePNuclei/Test/Labels/test_1_3_0001.png", "nuclei_id": 1, "mask_value": 3, "centroid": [ 64, 64 ] } ]}```
## Training configurationThe training was performed with the following:
- GPU: at least 12GB of GPU memory- Actual Model Input: 4 x 128 x 128- AMP: True- Optimizer: Adam- Learning Rate: 1e-4- Loss: torch.nn.CrossEntropyLoss- Dataset Manager: CacheDataset
### Memory Consumption Warning
If you face memory issues with CacheDataset, you can either switch to a regular Dataset class or lower the caching rate `cache_rate` in the configurations within range [0, 1] to minimize the System RAM requirements.
## Input4 channels- 3 RGB channels- 1 signal channel (label mask)
## Output4 channels - 0 = Other - 1 = Inflammatory - 2 = Epithelial - 3 = Spindle-Shaped

## PerformanceThis model achieves the following F1 score on the validation data provided as part of the dataset:
- Train F1 score = 0.926- Validation F1 score = 0.852
<hr/>Confusion Metrics for <b>Validation</b> for individual classes are:
| Metric | Other | Inflammatory | Epithelial | Spindle-Shaped ||-----------|--------|--------------|------------|----------------|| Precision | 0.6909 | 0.7773 | 0.9078 | 0.8478 || Recall | 0.2754 | 0.7831 | 0.9533 | 0.8514 || F1-score | 0.3938 | 0.7802 | 0.9300 | 0.8496 |
<hr/>Confusion Metrics for <b>Training</b> for individual classes are:
| Metric | Other | Inflammatory | Epithelial | Spindle-Shaped ||-----------|--------|--------------|------------|----------------|| Precision | 0.8000 | 0.9076 | 0.9560 | 0.9019 || Recall | 0.6512 | 0.9028 | 0.9690 | 0.8989 || F1-score | 0.7179 | 0.9052 | 0.9625 | 0.9004 |
#### Training Loss and F1A graph showing the training Loss and F1-score over 100 epochs.
 <br> <br>
#### Validation F1A graph showing the validation F1-score over 100 epochs.
 <br>
#### TensorRT speedupThis bundle supports acceleration with TensorRT. The table below displays the speedup ratios observed on an A100 80G GPU. Please note that 32-bit precision models are benchmarked with tf32 weight format.
| method | torch_tf32(ms) | torch_amp(ms) | trt_tf32(ms) | trt_fp16(ms) | speedup amp | speedup tf32 | speedup fp16 | amp vs fp16|| :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: || model computation | 20.47 | 20.57 | 2.49 | 1.48 | 1.00 | 8.22 | 13.83 | 13.90 || end2end | 45 | 49 | 18 | 18 | 0.92 | 2.50 | 2.50 | 2.72 |
Where:- `model computation` means the speedup ratio of model's inference with a random input without preprocessing and postprocessing- `end2end` means run the bundle end-to-end with the TensorRT based model.- `torch_tf32` and `torch_amp` are for the PyTorch models with or without `amp` mode.- `trt_tf32` and `trt_fp16` are for the TensorRT based models converted in corresponding precision.- `speedup amp`, `speedup tf32` and `speedup fp16` are the speedup ratios of corresponding models versus the PyTorch float32 model- `amp vs fp16` is the speedup ratio between the PyTorch amp model and the TensorRT float16 based model.
This result is benchmarked under: - TensorRT: 10.3.0+cuda12.6 - Torch-TensorRT Version: 2.4.0 - CPU Architecture: x86-64 - OS: ubuntu 20.04 - Python version:3.10.12 - CUDA version: 12.6 - GPU models and configuration: A100 80G
## MONAI Bundle CommandsIn addition to the Pythonic APIs, a few command line interfaces (CLI) are provided to interact with the bundle. The CLI supports flexible use cases, such as overriding configs at runtime and predefining arguments in a file.
For more details usage instructions, visit the [MONAI Bundle Configuration Page](https://docs.monai.io/en/latest/config_syntax.html).
#### Execute training:
```python -m monai.bundle run --config_file configs/train.json```
Please note that if the default dataset path is not modified with the actual path in the bundle config files, you can also override it by using `--dataset_dir`:
```python -m monai.bundle run --config_file configs/train.json --dataset_dir <actual dataset path>```
#### Override the `train` config to execute multi-GPU training:
```torchrun --standalone --nnodes=1 --nproc_per_node=2 -m monai.bundle run --config_file "['configs/train.json','configs/multi_gpu_train.json']"```
Please note that the distributed training-related options depend on the actual running environment; thus, users may need to remove `--standalone`, modify `--nnodes`, or do some other necessary changes according to the machine used. For more details, please refer to [pytorch's official tutorial](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html).
#### Override the `train` config to execute evaluation with the trained model:
```python -m monai.bundle run --config_file "['configs/train.json','configs/evaluate.json']"```
#### Override the `train` config and `evaluate` config to execute multi-GPU evaluation:
```torchrun --standalone --nnodes=1 --nproc_per_node=2 -m monai.bundle run --config_file "['configs/train.json','configs/evaluate.json','configs/multi_gpu_evaluate.json']"```
#### Execute inference:
```python -m monai.bundle run --config_file configs/inference.json```
#### Execute inference with the TensorRT model:
```python -m monai.bundle run --config_file "['configs/inference.json', 'configs/inference_trt.json']"```
# References[1] S. Graham, Q. D. Vu, S. E. A. Raza, A. Azam, Y-W. Tsang, J. T. Kwak and N. Rajpoot. "HoVer-Net: Simultaneous Segmentation and Classification of Nuclei in Multi-Tissue Histology Images." Medical Image Analysis, Sept. 2019. [[doi](https://doi.org/10.1016/j.media.2019.101563)]
# LicenseCopyright (c) 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, softwaredistributed 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 andlimitations under the License.123456Third Party Licenses-----------------------------------------------------------------------
/*********************************************************************/i. HoVer-Net: Simultaneous Segmentation and Classification of Nuclei in Multi-Tissue Histology Images https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet/123version https://git-lfs.github.com/spec/v1oid sha256:54066a13f090b94eb43c589c9090f9791810f74903998418c20e8502839d2c83size 28419489123version https://git-lfs.github.com/spec/v1oid sha256:10745ecb9c680c3bc2756da88326403153eee0964551a62da884d5fb21116f5esize 2857313312345678910111213# Copyright (c) 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 .handlers import TensorBoardImageHandlerfrom .writer import ClassificationWriter12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879# Copyright (c) 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 argparseimport globimport jsonimport loggingimport os
from dataset import consep_nuclei_dataset
logger = logging.getLogger(__name__)
def main(): logging.basicConfig( level=logging.INFO, format="[%(asctime)s] [%(process)s] [%(threadName)s] [%(levelname)s] (%(name)s:%(lineno)d) - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", force=True, )
parser = argparse.ArgumentParser() parser.add_argument( "--input", "-i", type=str, default=r"/workspace/data/CoNSeP", help="Input/Downloaded/Extracted dir for CoNSeP Dataset", ) parser.add_argument( "--output", "-o", type=str, default=r"/workspace/data/CoNSePNuclei", help="Output dir to store pre-processed data", ) parser.add_argument("--crop_size", "-s", type=int, default=128, help="Crop size for each Nuclei") parser.add_argument("--limit", "-n", type=int, default=0, help="Non-zero value to limit processing max records")
args = parser.parse_args() dataset_json = {} for f, v in {"Train": "training", "Test": "validation"}.items(): logger.info("---------------------------------------------------------------------------------") if not os.path.exists(os.path.join(args.input, f)): logger.warning(f"Ignore {f} (NOT Exists in Input Folder)") continue
logger.info(f"Processing Images/labels for: {f}") images_path = os.path.join(args.input, f, "Images", "*.png") labels_path = os.path.join(args.input, f, "Labels", "*.mat") images = sorted(glob.glob(images_path)) labels = sorted(glob.glob(labels_path)) ds = [{"image": i, "label": l} for i, l in zip(images, labels)]
output_dir = os.path.join(args.output, f) if args.output else f crop_size = args.crop_size limit = args.limit
ds_new = consep_nuclei_dataset(ds, output_dir, crop_size, limit=limit) logger.info(f"Total Generated/Extended Records: {len(ds)} => {len(ds_new)}")
dataset_json[v] = ds_new
ds_file = os.path.join(args.output, "dataset.json") with open(ds_file, "w") as fp: json.dump(dataset_json, fp, indent=2) logger.info(f"Dataset JSON Generated at: {ds_file}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189# Copyright (c) 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 copyimport jsonimport loggingimport osimport pathlibfrom typing import Dict, List
import numpy as npfrom monai.apps.utils import tqdmfrom monai.utils import optional_import
loadmat, _ = optional_import("scipy.io", name="loadmat")PILImage, _ = optional_import("PIL.Image")
def consep_nuclei_dataset(datalist, output_dir, crop_size, min_area=80, min_distance=20, limit=0) -> List[Dict]: """ Utility to pre-process and create dataset list for Patches per Nuclei for training over ConSeP dataset.
Args: datalist: A list of data dictionary. Each entry should at least contain 'image_key': <image filename>. For example, typical input data can be a list of dictionaries::
[{'image': <image filename>, 'label': <label filename>}]
output_dir: target directory to store the training data after flattening crop_size: Crop Size for each patch min_area: Min Area for each nuclei to be included in dataset min_distance: Min Distance from boundary for each nuclei to be included in dataset limit: limit number of inputs for pre-processing. Defaults to 0 (no limit).
Raises: ValueError: When ``datalist`` is Empty ValueError: When ``scipy.io.loadmat`` is Not available
Returns: A new datalist that contains path to the images/labels after pre-processing.
Example::
datalist = consep_nuclei_dataset( datalist=[{'image': 'img1.png', 'label': 'label1.mat'}], output_dir=output, crop_size=128, limit=1, )
print(datalist[0]["image"], datalist[0]["label"]) """
if not len(datalist): raise ValueError("Input datalist is empty")
if not loadmat: print("Please make sure scipy with loadmat function is correctly installed") raise ValueError("scipy.io.loadmat module/function not found")
dataset_json: List[Dict] = [] for d in tqdm(datalist): logging.debug(f"Processing Image: {d['image']} => Label: {d['label']}")
# Image image = PILImage.open(d["image"]).convert("RGB")
# Label m = loadmat(d["label"]) instances = m["inst_map"]
for nuclei_id, (class_id, (y, x)) in enumerate(zip(m["inst_type"], m["inst_centroid"]), start=1): x, y = (int(x), int(y)) class_id = int(class_id) class_id = 3 if class_id in (3, 4) else 4 if class_id in (5, 6, 7) else class_id # override
if 0 < limit <= len(dataset_json): return dataset_json
item = __prepare_patch( d=d, nuclei_id=nuclei_id, output_dir=output_dir, image=image, instances=instances, instance_idx=nuclei_id, crop_size=crop_size, class_id=class_id, centroid=(x, y), min_area=min_area, min_distance=min_distance, others_idx=255, )
if item: dataset_json.append(item)
return dataset_json
def __prepare_patch( d, nuclei_id, output_dir, image, instances, instance_idx, crop_size, class_id, centroid, min_area, min_distance, others_idx=255,): image_np = np.array(image) image_size = image.size
bbox = __compute_bbox(crop_size, centroid, image_size)
cropped_label_np = instances[bbox[0] : bbox[2], bbox[1] : bbox[3]] cropped_label_np = np.array(cropped_label_np)
this_label = np.where(cropped_label_np == instance_idx, class_id, 0) if np.count_nonzero(this_label) < min_area: return None
x, y = centroid if x < min_distance or y < min_distance or (image_size[0] - x) < min_distance or (image_size[1] - y < min_distance): return None
centroid = centroid[0] - bbox[0], centroid[1] - bbox[1] others = np.where(np.logical_and(cropped_label_np > 0, cropped_label_np != instance_idx), others_idx, 0) cropped_label_np = this_label + others cropped_label = PILImage.fromarray(cropped_label_np.astype(np.uint8), None)
cropped_image_np = image_np[bbox[0] : bbox[2], bbox[1] : bbox[3], :] cropped_image = PILImage.fromarray(cropped_image_np, "RGB")
images_dir = os.path.join(output_dir, "Images") if output_dir else "Images" labels_dir = os.path.join(output_dir, "Labels") if output_dir else "Labels" centroids_dir = os.path.join(output_dir, "Centroids") if output_dir else "Centroids"
os.makedirs(images_dir, exist_ok=True) os.makedirs(labels_dir, exist_ok=True) os.makedirs(centroids_dir, exist_ok=True)
image_id = pathlib.Path(d["image"]).stem file_prefix = f"{image_id}_{class_id}_{str(instance_idx).zfill(4)}" image_file = os.path.join(images_dir, f"{file_prefix}.png") label_file = os.path.join(labels_dir, f"{file_prefix}.png") centroid_file = os.path.join(centroids_dir, f"{file_prefix}.txt")
cropped_image.save(image_file) cropped_label.save(label_file) with open(centroid_file, "w") as fp: json.dump([centroid], fp)
item = copy.deepcopy(d) item["nuclei_id"] = nuclei_id item["mask_value"] = class_id item["image"] = image_file item["label"] = label_file item["centroid"] = centroid return item
def __compute_bbox(patch_size, centroid, size): x, y = centroid m, n = size
x_start = int(max(x - patch_size / 2, 0)) y_start = int(max(y - patch_size / 2, 0)) x_end = x_start + patch_size y_end = y_start + patch_size if x_end > m: x_end = m x_start = m - patch_size if y_end > n: y_end = n y_start = n - patch_size return x_start, y_start, x_end, y_end123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141# Copyright (c) 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 loggingfrom typing import TYPE_CHECKING, Any, Callable, List, Optional
import numpy as npimport torchimport torch.distributedfrom monai.utils import IgniteInfo, min_version, optional_importfrom sklearn.metrics import classification_report
Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events")make_grid, _ = optional_import("torchvision.utils", name="make_grid")Image, _ = optional_import("PIL.Image")ImageDraw, _ = optional_import("PIL.ImageDraw")
if TYPE_CHECKING: from ignite.engine import Engine from torch.utils.tensorboard import SummaryWriterelse: Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") SummaryWriter, _ = optional_import("torch.utils.tensorboard", name="SummaryWriter")
class TensorBoardImageHandler: def __init__( self, class_names, summary_writer: Optional[SummaryWriter] = None, log_dir: str = "./runs", tag_name="val", interval: int = 1, batch_transform: Callable = lambda x: x, output_transform: Callable = lambda x: x, batch_limit=1, device=None, ) -> None: self.class_names = class_names self.writer = SummaryWriter(log_dir=log_dir) if summary_writer is None else summary_writer self.tag_name = tag_name self.interval = interval self.batch_transform = batch_transform self.output_transform = output_transform self.batch_limit = batch_limit self.device = device
self.logger = logging.getLogger(__name__)
if torch.distributed.is_initialized(): self.tag_name = f"{self.tag_name}-r{torch.distributed.get_rank()}" self.class_y: List[Any] = [] self.class_y_pred: List[Any] = []
def attach(self, engine: Engine) -> None: if self.interval == 1: engine.add_event_handler(Events.ITERATION_COMPLETED(every=self.interval), self, "iteration") engine.add_event_handler(Events.EPOCH_COMPLETED(every=self.interval), self, "epoch")
def __call__(self, engine: Engine, action) -> None: epoch = engine.state.epoch batch_data = self.batch_transform(engine.state.batch) output_data = self.output_transform(engine.state.output)
if action == "iteration": for bidx in range(len(batch_data)): y = output_data[bidx]["label"].detach().cpu().numpy() y_pred = output_data[bidx]["pred"].detach().cpu().numpy()
self.class_y.append(np.argmax(y)) self.class_y_pred.append(np.argmax(y_pred)) return
self.write_metrics(epoch) self.write_images(batch_data, output_data, epoch) self.writer.flush()
def write_images(self, batch_data, output_data, epoch): for bidx in range(len(batch_data)): image = batch_data[bidx]["image"].detach().cpu().numpy() y = output_data[bidx]["label"].detach().cpu().numpy() y_pred = output_data[bidx]["pred"].detach().cpu().numpy()
sig_np = image[:3] * 128 + 128 sig_np[0, :, :] = np.where(image[3] > 0, 1, sig_np[0, :, :])
y_c = np.argmax(y) y_pred_c = np.argmax(y_pred)
tag_prefix = f"{self.tag_name} - b{bidx} - " if self.batch_limit != 1 else f"{self.tag_name} - " label_pred_tag = f"{tag_prefix}Image/Signal/Label/Pred:"
y_img = Image.new("RGB", image.shape[-2:]) draw = ImageDraw.Draw(y_img) draw.text((10, 50), self.class_names.get(f"{y_c}", f"{y_c}"))
y_pred_img = Image.new("RGB", image.shape[-2:], "green" if y_c == y_pred_c else "red") draw = ImageDraw.Draw(y_pred_img) draw.text((10, 50), self.class_names.get(f"{y_pred_c}", f"{y_pred_c}"))
img_tensor = make_grid( tensor=[ torch.from_numpy(sig_np), torch.from_numpy(np.stack((np.where(image[3] > 0, 255, 0),) * 3)), torch.from_numpy(np.moveaxis(np.array(y_img), -1, 0)), torch.from_numpy(np.moveaxis(np.array(y_pred_img), -1, 0)), ], nrow=4, normalize=True, pad_value=10, ) self.writer.add_image(tag=label_pred_tag, img_tensor=img_tensor, global_step=epoch)
if self.batch_limit == 1 or bidx == (self.batch_limit - 1): break
def write_metrics(self, epoch): cr = classification_report(self.class_y, self.class_y_pred, output_dict=True, zero_division=0) for k, v in cr.items(): if isinstance(v, dict): ltext = [] cname = self.class_names.get(k, k) for n, m in v.items(): ltext.append(f"{n} => {m:.4f}") self.writer.add_scalar(f"{self.tag_name}_cr_{cname}_{n}", m, epoch)
self.logger.info(f"{self.tag_name} => Epoch[{epoch}] - {cname} - Metrics -- {'; '.join(ltext)}") else: self.logger.info(f"{self.tag_name} => Epoch[{epoch}] Metrics -- {k} => {v:.4f}") self.writer.add_scalar(f"{self.tag_name}_cr_{k}", v, epoch)
self.class_y = [] self.class_y_pred = []123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354# Copyright (c) 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 jsonimport loggingfrom typing import Dict, Mapping, Optional
import numpy as npfrom monai.config import NdarrayOrTensor, PathLikefrom monai.data import ImageWriter
logger = logging.getLogger(__name__)
class ClassificationWriter(ImageWriter): def __init__(self, label_index_map: Optional[Dict[str, str]] = None, **kwargs): super().__init__(**kwargs) self.label_index_map = ( label_index_map if label_index_map else {"0": "Other", "1": "Inflammatory", "2": "Epithelial", "3": "Spindle-Shaped"} )
def set_data_array( self, data_array: NdarrayOrTensor, channel_dim: Optional[int] = 0, squeeze_end_dims: bool = True, contiguous: bool = False, **kwargs, ): self.data_obj: np.ndarray = super().create_backend_obj(data_array)
def set_metadata(self, meta_dict: Optional[Mapping] = None, resample: bool = True, **options): pass
def write(self, filename: PathLike, verbose: bool = False, **kwargs): super().write(filename, verbose=verbose) result = [] for idx, score in enumerate(self.data_obj): name = f"label_{idx}" name = self.label_index_map.get(str(idx)) if self.label_index_map else name if name: result.append({"idx": idx, "label": name, "score": float(score)})
with open(filename, "w") as fp: json.dump(result, fp).gitattributes+1
LICENSEAdded+201
configs/evaluate.jsonAdded+77
configs/inference.jsonAdded+120
configs/inference_trt.jsonAdded+6
configs/logging.confAdded+21
configs/metadata.jsonAdded+108
configs/multi_gpu_evaluate.jsonAdded+36
configs/multi_gpu_train.jsonAdded+44
configs/train.jsonAdded+364
docs/README.mdAdded+232
docs/data_license.txtAdded+6
models/model.ptAdded+3
models/model.tsAdded+3
scripts/__init__.pyAdded+13
scripts/data_process.pyAdded+79
scripts/dataset.pyAdded+189
scripts/handlers.pyAdded+141
scripts/writer.pyAdded+54