project-monai commited on
Commit
e88dbff
·
verified ·
1 Parent(s): b244beb

Upload pathology_nuclick_annotation version 0.2.2

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ models/model.ts filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
configs/evaluate.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "validate#dataset#cache_rate": 0,
3
+ "validate#postprocessing": {
4
+ "_target_": "Compose",
5
+ "transforms": [
6
+ {
7
+ "_target_": "Activationsd",
8
+ "keys": "pred",
9
+ "sigmoid": true
10
+ },
11
+ {
12
+ "_target_": "AsDiscreted",
13
+ "keys": "pred",
14
+ "threshold": 0.5
15
+ },
16
+ {
17
+ "_target_": "SaveImaged",
18
+ "_disabled_": true,
19
+ "keys": "pred",
20
+ "meta_keys": "pred_meta_dict",
21
+ "output_dir": "@output_dir",
22
+ "output_ext": ".png"
23
+ }
24
+ ]
25
+ },
26
+ "validate#handlers": [
27
+ {
28
+ "_target_": "CheckpointLoader",
29
+ "load_path": "$@ckpt_dir + '/model.pt'",
30
+ "load_dict": {
31
+ "model": "@network"
32
+ }
33
+ },
34
+ {
35
+ "_target_": "StatsHandler",
36
+ "iteration_log": false
37
+ },
38
+ {
39
+ "_target_": "MetricsSaver",
40
+ "save_dir": "@output_dir",
41
+ "metrics": [
42
+ "val_mean_dice",
43
+ "val_accuracy"
44
+ ],
45
+ "metric_details": [
46
+ "val_mean_dice"
47
+ ],
48
+ "batch_transform": "$monai.handlers.from_engine(['image_meta_dict'])",
49
+ "summary_ops": "*"
50
+ }
51
+ ],
52
+ "run": [
53
+ "$@validate#evaluator.run()"
54
+ ]
55
+ }
configs/inference.json ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "imports": [
3
+ "$import glob",
4
+ "$import numpy",
5
+ "$import json",
6
+ "$import pathlib",
7
+ "$import os"
8
+ ],
9
+ "bundle_root": ".",
10
+ "image_key": "image",
11
+ "output_dir": "$@bundle_root + '/eval'",
12
+ "output_ext": ".png",
13
+ "output_dtype": "$numpy.float32",
14
+ "output_postfix": "trans",
15
+ "separate_folder": true,
16
+ "load_pretrain": true,
17
+ "dataset_dir": "/workspace/data/CoNSePNuclei",
18
+ "images": "$list(sorted(glob.glob(@dataset_dir + '/Test/Images/*.png')))[:1]",
19
+ "centroids": "$list(sorted(glob.glob(@dataset_dir + '/Test/Centroids/*.txt')))[:1]",
20
+ "input_data": "$[{'image': i, 'foreground': json.loads(pathlib.Path(c).read_text())} for i,c in zip(@images, @centroids)]",
21
+ "device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')",
22
+ "network_def": {
23
+ "_target_": "BasicUNet",
24
+ "spatial_dims": 2,
25
+ "in_channels": 5,
26
+ "out_channels": 1,
27
+ "features": [
28
+ 32,
29
+ 64,
30
+ 128,
31
+ 256,
32
+ 512,
33
+ 32
34
+ ]
35
+ },
36
+ "network": "$@network_def.to(@device)",
37
+ "preprocessing": {
38
+ "_target_": "Compose",
39
+ "transforms": [
40
+ {
41
+ "_target_": "LoadImaged",
42
+ "keys": "@image_key",
43
+ "dtype": "uint8",
44
+ "image_only": false
45
+ },
46
+ {
47
+ "_target_": "EnsureChannelFirstd",
48
+ "keys": "@image_key"
49
+ },
50
+ {
51
+ "_target_": "ScaleIntensityRanged",
52
+ "keys": "@image_key",
53
+ "a_min": 0.0,
54
+ "a_max": 255.0,
55
+ "b_min": -1.0,
56
+ "b_max": 1.0
57
+ },
58
+ {
59
+ "_target_": "AddClickSignalsd",
60
+ "image": "@image_key",
61
+ "foreground": "foreground",
62
+ "gaussian": false
63
+ },
64
+ {
65
+ "_target_": "SqueezeDimd",
66
+ "keys": "@image_key"
67
+ }
68
+ ]
69
+ },
70
+ "dataset": {
71
+ "_target_": "Dataset",
72
+ "data": "@input_data",
73
+ "transform": "@preprocessing"
74
+ },
75
+ "dataloader": {
76
+ "_target_": "DataLoader",
77
+ "dataset": "@dataset",
78
+ "batch_size": 1,
79
+ "shuffle": false,
80
+ "num_workers": 4
81
+ },
82
+ "inferer": {
83
+ "_target_": "SimpleInferer"
84
+ },
85
+ "postprocessing": {
86
+ "_target_": "Compose",
87
+ "transforms": [
88
+ {
89
+ "_target_": "Activationsd",
90
+ "keys": "pred",
91
+ "sigmoid": true
92
+ },
93
+ {
94
+ "_target_": "AsDiscreted",
95
+ "keys": "pred",
96
+ "threshold": 0.5
97
+ },
98
+ {
99
+ "_target_": "KeepLargestConnectedComponentd",
100
+ "keys": "pred"
101
+ },
102
+ {
103
+ "_target_": "SaveImaged",
104
+ "keys": "pred",
105
+ "meta_keys": "pred_meta_dict",
106
+ "output_dir": "@output_dir",
107
+ "output_ext": "@output_ext",
108
+ "output_dtype": "@output_dtype",
109
+ "output_postfix": "@output_postfix",
110
+ "separate_folder": "@separate_folder"
111
+ }
112
+ ]
113
+ },
114
+ "handlers": [
115
+ {
116
+ "_target_": "StatsHandler",
117
+ "iteration_log": false
118
+ }
119
+ ],
120
+ "evaluator": {
121
+ "_target_": "SupervisedEvaluator",
122
+ "device": "@device",
123
+ "val_data_loader": "@dataloader",
124
+ "network": "@network",
125
+ "inferer": "@inferer",
126
+ "postprocessing": "@postprocessing",
127
+ "val_handlers": "@handlers",
128
+ "amp": true
129
+ },
130
+ "checkpointloader": {
131
+ "_target_": "CheckpointLoader",
132
+ "load_path": "$@bundle_root + '/models/model.pt'",
133
+ "load_dict": {
134
+ "model": "@network"
135
+ }
136
+ },
137
+ "initialize": [
138
+ "$import sys",
139
+ "$sys.path.append(@bundle_root)",
140
+ "$monai.utils.set_determinism(seed=123)",
141
+ "$@checkpointloader(@evaluator) if @load_pretrain else None"
142
+ ],
143
+ "run": [
144
145
+ ]
146
+ }
configs/inference_trt.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "imports": [
3
+ "$import glob",
4
+ "$import json",
5
+ "$import pathlib",
6
+ "$import os",
7
+ "$import torch_tensorrt"
8
+ ],
9
+ "network_def": "$torch.jit.load(@bundle_root + '/models/model_trt.ts')",
10
+ "evaluator#amp": false,
11
+ "initialize": [
12
+ "$import sys",
13
+ "$sys.path.append(@bundle_root)",
14
+ "$monai.utils.set_determinism(seed=123)"
15
+ ]
16
+ }
configs/logging.conf ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [loggers]
2
+ keys=root
3
+
4
+ [handlers]
5
+ keys=consoleHandler
6
+
7
+ [formatters]
8
+ keys=fullFormatter
9
+
10
+ [logger_root]
11
+ level=INFO
12
+ handlers=consoleHandler
13
+
14
+ [handler_consoleHandler]
15
+ class=StreamHandler
16
+ level=INFO
17
+ formatter=fullFormatter
18
+ args=(sys.stdout,)
19
+
20
+ [formatter_fullFormatter]
21
+ format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
configs/metadata.json ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/meta_schema_20240725.json",
3
+ "version": "0.2.2",
4
+ "changelog": {
5
+ "0.2.2": "update to huggingface hosting",
6
+ "0.2.1": "update issue for IgniteInfo",
7
+ "0.2.0": "use monai 1.4 and update large files",
8
+ "0.1.9": "update to use monai 1.3.1",
9
+ "0.1.8": "add load_pretrain flag for infer",
10
+ "0.1.7": "add checkpoint loader for infer",
11
+ "0.1.6": "set image_only to False",
12
+ "0.1.5": "add support for TensorRT conversion and inference",
13
+ "0.1.4": "fix the wrong GPU index issue of multi-node",
14
+ "0.1.3": "remove error dollar symbol in readme",
15
+ "0.1.2": "add RAM usage with CachDataset",
16
+ "0.1.1": "deterministic retrain benchmark and add link",
17
+ "0.1.0": "fix mgpu finalize issue",
18
+ "0.0.9": "Update README Formatting",
19
+ "0.0.8": "enable deterministic training",
20
+ "0.0.7": "Update with figure links",
21
+ "0.0.6": "adapt to BundleWorkflow interface",
22
+ "0.0.5": "add name tag",
23
+ "0.0.4": "Fix evaluation",
24
+ "0.0.3": "Update to use MONAI 1.1.0",
25
+ "0.0.2": "Update The Torch Vision Transform",
26
+ "0.0.1": "initialize the model package structure"
27
+ },
28
+ "monai_version": "1.4.0",
29
+ "pytorch_version": "2.4.0",
30
+ "numpy_version": "1.24.4",
31
+ "required_packages_version": {
32
+ "nibabel": "5.2.1",
33
+ "pytorch-ignite": "0.4.11",
34
+ "torchvision": "0.19.0",
35
+ "scipy": "1.13.1",
36
+ "scikit-image": "0.23.2",
37
+ "tensorboard": "2.17.0"
38
+ },
39
+ "supported_apps": {},
40
+ "name": "Pathology nuclick annotation",
41
+ "task": "Pathology Nuclick annotation",
42
+ "description": "A pre-trained model for segmenting nuclei cells with user clicks/interactions",
43
+ "authors": "MONAI team",
44
+ "copyright": "Copyright (c) MONAI Consortium",
45
+ "data_source": "consep_dataset.zip from https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet",
46
+ "data_type": "png",
47
+ "image_classes": "RGB channel data, intensity scaled to [0, 1]",
48
+ "label_classes": "single channel data",
49
+ "pred_classes": "1 channel data, with value 1 as nuclei and 0 as background",
50
+ "eval_metrics": {
51
+ "mean_dice": 0.85
52
+ },
53
+ "intended_use": "This is an example, not to be used for diagnostic purposes",
54
+ "references": [
55
+ "Koohbanani, Navid Alemi, et al. \"NuClick: A Deep Learning Framework for Interactive Segmentation of Microscopy Images.\" https://arxiv.org/abs/2005.14511",
56
+ "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",
57
+ "NuClick PyTorch Implementation, https://github.com/mostafajahanifar/nuclick_torch"
58
+ ],
59
+ "network_data_format": {
60
+ "inputs": {
61
+ "image": {
62
+ "type": "png",
63
+ "format": "RGB",
64
+ "modality": "regular",
65
+ "num_channels": 5,
66
+ "spatial_shape": [
67
+ 128,
68
+ 128
69
+ ],
70
+ "dtype": "float32",
71
+ "value_range": [
72
+ 0,
73
+ 1
74
+ ],
75
+ "is_patch_data": false,
76
+ "channel_def": {
77
+ "0": "R",
78
+ "1": "G",
79
+ "2": "B",
80
+ "3": "+ve Signal",
81
+ "4": "-ve Signal"
82
+ }
83
+ }
84
+ },
85
+ "outputs": {
86
+ "pred": {
87
+ "type": "image",
88
+ "format": "segmentation",
89
+ "num_channels": 1,
90
+ "spatial_shape": [
91
+ 128,
92
+ 128
93
+ ],
94
+ "dtype": "float32",
95
+ "value_range": [
96
+ 0,
97
+ 1
98
+ ],
99
+ "is_patch_data": false,
100
+ "channel_def": {
101
+ "0": "Nuclei"
102
+ }
103
+ }
104
+ }
105
+ }
106
+ }
configs/multi_gpu_evaluate.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "device": "$torch.device('cuda:' + os.environ['LOCAL_RANK'])",
3
+ "network": {
4
+ "_target_": "torch.nn.parallel.DistributedDataParallel",
5
+ "module": "$@network_def.to(@device)",
6
+ "device_ids": [
7
+ "@device"
8
+ ]
9
+ },
10
+ "validate#sampler": {
11
+ "_target_": "DistributedSampler",
12
+ "dataset": "@validate#dataset",
13
+ "even_divisible": false,
14
+ "shuffle": false
15
+ },
16
+ "validate#dataloader#sampler": "@validate#sampler",
17
+ "validate#handlers#1#_disabled_": "$dist.get_rank() > 0",
18
+ "initialize": [
19
+ "$import sys",
20
+ "$sys.path.append(@bundle_root)",
21
+ "$import torch.distributed as dist",
22
+ "$dist.is_initialized() or dist.init_process_group(backend='nccl')",
23
+ "$torch.cuda.set_device(@device)",
24
+ "$monai.utils.set_determinism(seed=123)",
25
+ "$import logging",
26
+ "$@validate#evaluator.logger.setLevel(logging.WARNING if dist.get_rank() > 0 else logging.INFO)"
27
+ ],
28
+ "run": [
29
+ "$@validate#evaluator.run()"
30
+ ],
31
+ "finalize": [
32
+ "$dist.is_initialized() and dist.destroy_process_group()"
33
+ ]
34
+ }
configs/multi_gpu_train.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "device": "$torch.device('cuda:' + os.environ['LOCAL_RANK'])",
3
+ "network": {
4
+ "_target_": "torch.nn.parallel.DistributedDataParallel",
5
+ "module": "$@network_def.to(@device)",
6
+ "device_ids": [
7
+ "@device"
8
+ ]
9
+ },
10
+ "train#sampler": {
11
+ "_target_": "DistributedSampler",
12
+ "dataset": "@train#dataset",
13
+ "even_divisible": true,
14
+ "shuffle": true
15
+ },
16
+ "train#dataloader#sampler": "@train#sampler",
17
+ "train#dataloader#shuffle": false,
18
+ "train#trainer#train_handlers": "$@train#handlers[: -2 if dist.get_rank() > 0 else None]",
19
+ "validate#sampler": {
20
+ "_target_": "DistributedSampler",
21
+ "dataset": "@validate#dataset",
22
+ "even_divisible": false,
23
+ "shuffle": false
24
+ },
25
+ "validate#dataloader#sampler": "@validate#sampler",
26
+ "validate#evaluator#val_handlers": "$None if dist.get_rank() > 0 else @validate#handlers",
27
+ "initialize": [
28
+ "$import sys",
29
+ "$sys.path.append(@bundle_root)",
30
+ "$import torch.distributed as dist",
31
+ "$dist.is_initialized() or dist.init_process_group(backend='nccl')",
32
+ "$torch.cuda.set_device(@device)",
33
+ "$monai.utils.set_determinism(seed=123)",
34
+ "$import logging",
35
+ "$@train#trainer.logger.setLevel(logging.WARNING if dist.get_rank() > 0 else logging.INFO)",
36
+ "$@validate#evaluator.logger.setLevel(logging.WARNING if dist.get_rank() > 0 else logging.INFO)"
37
+ ],
38
+ "run": [
39
+ "$@train#trainer.run()"
40
+ ],
41
+ "finalize": [
42
+ "$dist.is_initialized() and dist.destroy_process_group()"
43
+ ]
44
+ }
configs/train.json ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "imports": [
3
+ "$import glob",
4
+ "$import ignite",
5
+ "$import json",
6
+ "$import pathlib",
7
+ "$import os"
8
+ ],
9
+ "bundle_root": ".",
10
+ "ckpt_dir": "$@bundle_root + '/models'",
11
+ "output_dir": "$@bundle_root + '/eval'",
12
+ "dataset_dir": "/workspace/data/CoNSePNuclei",
13
+ "dataset_json": "$@dataset_dir + '/dataset.json'",
14
+ "train_datalist": "$json.loads(pathlib.Path(@dataset_json).read_text())['training']",
15
+ "val_datalist": "$json.loads(pathlib.Path(@dataset_json).read_text())['validation']",
16
+ "val_interval": 1,
17
+ "device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')",
18
+ "network_def": {
19
+ "_target_": "BasicUNet",
20
+ "spatial_dims": 2,
21
+ "in_channels": 5,
22
+ "out_channels": 1,
23
+ "features": [
24
+ 32,
25
+ 64,
26
+ 128,
27
+ 256,
28
+ 512,
29
+ 32
30
+ ]
31
+ },
32
+ "network": "$@network_def.to(@device)",
33
+ "loss": {
34
+ "_target_": "DiceLoss",
35
+ "sigmoid": true,
36
+ "squared_pred": true
37
+ },
38
+ "optimizer": {
39
+ "_target_": "torch.optim.Adam",
40
+ "params": "[email protected]()",
41
+ "lr": 0.0001
42
+ },
43
+ "max_epochs": 50,
44
+ "train": {
45
+ "preprocessing": {
46
+ "_target_": "Compose",
47
+ "transforms": [
48
+ {
49
+ "_target_": "LoadImaged",
50
+ "keys": [
51
+ "image",
52
+ "label"
53
+ ],
54
+ "dtype": "uint8",
55
+ "image_only": false
56
+ },
57
+ {
58
+ "_target_": "EnsureChannelFirstd",
59
+ "keys": [
60
+ "image",
61
+ "label"
62
+ ]
63
+ },
64
+ {
65
+ "_target_": "SplitLabeld",
66
+ "keys": "label",
67
+ "mask_value": "",
68
+ "others_value": 255
69
+ },
70
+ {
71
+ "_target_": "RandTorchVisiond",
72
+ "keys": "image",
73
+ "name": "ColorJitter",
74
+ "brightness": 0.251,
75
+ "contrast": 0.75,
76
+ "saturation": 0.25,
77
+ "hue": 0.04
78
+ },
79
+ {
80
+ "_target_": "RandFlipd",
81
+ "keys": [
82
+ "image",
83
+ "label",
84
+ "others"
85
+ ],
86
+ "prob": 0.5
87
+ },
88
+ {
89
+ "_target_": "RandRotate90d",
90
+ "keys": [
91
+ "image",
92
+ "label",
93
+ "others"
94
+ ],
95
+ "prob": 0.5
96
+ },
97
+ {
98
+ "_target_": "ScaleIntensityRanged",
99
+ "keys": "image",
100
+ "a_min": 0.0,
101
+ "a_max": 255.0,
102
+ "b_min": -1.0,
103
+ "b_max": 1.0
104
+ },
105
+ {
106
+ "_target_": "AddPointGuidanceSignald",
107
+ "image": "image",
108
+ "label": "label",
109
+ "others": "others",
110
+ "use_distance": true,
111
+ "gaussian": false
112
+ },
113
+ {
114
+ "_target_": "SelectItemsd",
115
+ "keys": [
116
+ "image",
117
+ "label"
118
+ ]
119
+ }
120
+ ]
121
+ },
122
+ "dataset": {
123
+ "_target_": "CacheDataset",
124
+ "data": "@train_datalist",
125
+ "transform": "@train#preprocessing",
126
+ "cache_rate": 1.0,
127
+ "num_workers": 4
128
+ },
129
+ "dataloader": {
130
+ "_target_": "DataLoader",
131
+ "dataset": "@train#dataset",
132
+ "batch_size": 64,
133
+ "shuffle": true,
134
+ "num_workers": 4
135
+ },
136
+ "inferer": {
137
+ "_target_": "SimpleInferer"
138
+ },
139
+ "postprocessing": {
140
+ "_target_": "Compose",
141
+ "transforms": [
142
+ {
143
+ "_target_": "Activationsd",
144
+ "keys": "pred",
145
+ "sigmoid": true
146
+ },
147
+ {
148
+ "_target_": "AsDiscreted",
149
+ "keys": "pred",
150
+ "threshold": 0.5
151
+ }
152
+ ]
153
+ },
154
+ "handlers": [
155
+ {
156
+ "_target_": "ValidationHandler",
157
+ "validator": "@validate#evaluator",
158
+ "epoch_level": true,
159
+ "interval": "@val_interval"
160
+ },
161
+ {
162
+ "_target_": "StatsHandler",
163
+ "tag_name": "train_loss",
164
+ "output_transform": "$monai.handlers.from_engine(['loss'], first=True)"
165
+ },
166
+ {
167
+ "_target_": "TensorBoardStatsHandler",
168
+ "log_dir": "@output_dir",
169
+ "tag_name": "train_loss",
170
+ "output_transform": "$monai.handlers.from_engine(['loss'], first=True)"
171
+ },
172
+ {
173
+ "_target_": "scripts.TensorBoardImageHandler",
174
+ "log_dir": "@output_dir",
175
+ "batch_limit": 4,
176
+ "tag_name": "train"
177
+ }
178
+ ],
179
+ "key_metric": {
180
+ "train_dice": {
181
+ "_target_": "monai.handlers.MeanDice",
182
+ "output_transform": "$monai.handlers.from_engine(['pred', 'label'])",
183
+ "include_background": false
184
+ }
185
+ },
186
+ "trainer": {
187
+ "_target_": "SupervisedTrainer",
188
+ "max_epochs": "@max_epochs",
189
+ "device": "@device",
190
+ "train_data_loader": "@train#dataloader",
191
+ "network": "@network",
192
+ "loss_function": "@loss",
193
+ "optimizer": "@optimizer",
194
+ "inferer": "@train#inferer",
195
+ "postprocessing": "@train#postprocessing",
196
+ "key_train_metric": "@train#key_metric",
197
+ "train_handlers": "@train#handlers",
198
+ "amp": true
199
+ }
200
+ },
201
+ "validate": {
202
+ "preprocessing": {
203
+ "_target_": "Compose",
204
+ "transforms": [
205
+ {
206
+ "_target_": "LoadImaged",
207
+ "keys": [
208
+ "image",
209
+ "label"
210
+ ],
211
+ "dtype": "uint8",
212
+ "image_only": false
213
+ },
214
+ {
215
+ "_target_": "EnsureChannelFirstd",
216
+ "keys": [
217
+ "image",
218
+ "label"
219
+ ]
220
+ },
221
+ {
222
+ "_target_": "SplitLabeld",
223
+ "keys": "label",
224
+ "mask_value": "",
225
+ "others_value": 255
226
+ },
227
+ {
228
+ "_target_": "ScaleIntensityRanged",
229
+ "keys": "image",
230
+ "a_min": 0.0,
231
+ "a_max": 255.0,
232
+ "b_min": -1.0,
233
+ "b_max": 1.0
234
+ },
235
+ {
236
+ "_target_": "AddPointGuidanceSignald",
237
+ "image": "image",
238
+ "label": "label",
239
+ "others": "others",
240
+ "use_distance": true,
241
+ "gaussian": false,
242
+ "drop_rate": 1.0
243
+ },
244
+ {
245
+ "_target_": "SelectItemsd",
246
+ "keys": [
247
+ "image",
248
+ "label",
249
+ "image_meta_dict"
250
+ ]
251
+ }
252
+ ]
253
+ },
254
+ "dataset": {
255
+ "_target_": "CacheDataset",
256
+ "data": "@val_datalist",
257
+ "transform": "@validate#preprocessing",
258
+ "cache_rate": 1.0
259
+ },
260
+ "dataloader": {
261
+ "_target_": "DataLoader",
262
+ "dataset": "@validate#dataset",
263
+ "batch_size": 64,
264
+ "shuffle": false,
265
+ "num_workers": 4
266
+ },
267
+ "inferer": {
268
+ "_target_": "SimpleInferer"
269
+ },
270
+ "postprocessing": "%train#postprocessing",
271
+ "handlers": [
272
+ {
273
+ "_target_": "StatsHandler",
274
+ "iteration_log": false
275
+ },
276
+ {
277
+ "_target_": "TensorBoardStatsHandler",
278
+ "log_dir": "@output_dir",
279
+ "iteration_log": false
280
+ },
281
+ {
282
+ "_target_": "CheckpointSaver",
283
+ "save_dir": "@ckpt_dir",
284
+ "save_dict": {
285
+ "model": "@network"
286
+ },
287
+ "save_key_metric": true,
288
+ "key_metric_filename": "model.pt"
289
+ },
290
+ {
291
+ "_target_": "scripts.TensorBoardImageHandler",
292
+ "log_dir": "@output_dir",
293
+ "batch_limit": 8,
294
+ "tag_name": "val"
295
+ }
296
+ ],
297
+ "key_metric": {
298
+ "val_mean_dice": {
299
+ "_target_": "MeanDice",
300
+ "include_background": false,
301
+ "output_transform": "$monai.handlers.from_engine(['pred', 'label'])"
302
+ }
303
+ },
304
+ "additional_metrics": {
305
+ "val_accuracy": {
306
+ "_target_": "ignite.metrics.Accuracy",
307
+ "output_transform": "$monai.handlers.from_engine(['pred', 'label'])"
308
+ }
309
+ },
310
+ "evaluator": {
311
+ "_target_": "SupervisedEvaluator",
312
+ "device": "@device",
313
+ "val_data_loader": "@validate#dataloader",
314
+ "network": "@network",
315
+ "inferer": "@validate#inferer",
316
+ "postprocessing": "@validate#postprocessing",
317
+ "key_val_metric": "@validate#key_metric",
318
+ "additional_metrics": "@validate#additional_metrics",
319
+ "val_handlers": "@validate#handlers",
320
+ "amp": true
321
+ }
322
+ },
323
+ "initialize": [
324
+ "$import sys",
325
+ "$sys.path.append(@bundle_root)",
326
+ "$monai.utils.set_determinism(seed=123)"
327
+ ],
328
+ "run": [
329
+ "$@train#trainer.run()"
330
+ ]
331
+ }
docs/README.md ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model Overview
2
+ A pre-trained model for segmenting nuclei cells with user clicks/interactions.
3
+
4
+ ![nuclick](https://github.com/mostafajahanifar/nuclick_torch/raw/master/docs/11.gif)
5
+ ![nuclick](https://github.com/mostafajahanifar/nuclick_torch/raw/master/docs/33.gif)
6
+ ![nuclick](https://github.com/mostafajahanifar/nuclick_torch/raw/master/docs/22.gif)
7
+
8
+ This model is trained using [BasicUNet](https://docs.monai.io/en/latest/networks.html#basicunet) over [ConSeP](https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet) dataset.
9
+
10
+ ## Data
11
+ The training dataset is from https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet
12
+ ```commandline
13
+ wget https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet/consep_dataset.zip
14
+ unzip -q consep_dataset.zip
15
+ ```
16
+ ![](https://developer.download.nvidia.com/assets/Clara/Images/monai_pathology_nuclick_annotation_dataset.jpeg)<br/>
17
+
18
+ ### Preprocessing
19
+ After [downloading this dataset](https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet/consep_dataset.zip),
20
+ python script `data_process.py` from `scripts` folder can be used to preprocess and generate the final dataset for training.
21
+
22
+ ```
23
+ python scripts/data_process.py --input /path/to/data/CoNSeP --output /path/to/data/CoNSePNuclei
24
+ ```
25
+
26
+ 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.
27
+
28
+ Class values in dataset are
29
+
30
+ - 1 = other
31
+ - 2 = inflammatory
32
+ - 3 = healthy epithelial
33
+ - 4 = dysplastic/malignant epithelial
34
+ - 5 = fibroblast
35
+ - 6 = muscle
36
+ - 7 = endothelial
37
+
38
+ As part of pre-processing, the following steps are executed.
39
+
40
+ - Crop and Extract each nuclei Image + Label (128x128) based on the centroid given in the dataset.
41
+ - Combine classes 3 & 4 into the epithelial class and 5,6 & 7 into the spindle-shaped class.
42
+ - Update the label index for the target nuclei based on the class value
43
+ - Other cells which are part of the patch are modified to have label idx = 255
44
+
45
+ Example dataset.json
46
+ ```json
47
+ {
48
+ "training": [
49
+ {
50
+ "image": "/workspace/data/CoNSePNuclei/Train/Images/train_1_3_0001.png",
51
+ "label": "/workspace/data/CoNSePNuclei/Train/Labels/train_1_3_0001.png",
52
+ "nuclei_id": 1,
53
+ "mask_value": 3,
54
+ "centroid": [
55
+ 64,
56
+ 64
57
+ ]
58
+ }
59
+ ],
60
+ "validation": [
61
+ {
62
+ "image": "/workspace/data/CoNSePNuclei/Test/Images/test_1_3_0001.png",
63
+ "label": "/workspace/data/CoNSePNuclei/Test/Labels/test_1_3_0001.png",
64
+ "nuclei_id": 1,
65
+ "mask_value": 3,
66
+ "centroid": [
67
+ 64,
68
+ 64
69
+ ]
70
+ }
71
+ ]
72
+ }
73
+ ```
74
+
75
+ ## Training Configuration
76
+ The training was performed with the following:
77
+
78
+ - GPU: at least 12GB of GPU memory
79
+ - Actual Model Input: 5 x 128 x 128
80
+ - AMP: True
81
+ - Optimizer: Adam
82
+ - Learning Rate: 1e-4
83
+ - Loss: DiceLoss
84
+
85
+ ### Memory Consumption
86
+
87
+ - Dataset Manager: CacheDataset
88
+ - Data Size: 13,136 PNG images
89
+ - Cache Rate: 1.0
90
+ - Single GPU - System RAM Usage: 4.7G
91
+
92
+ ### Memory Consumption Warning
93
+
94
+ 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.
95
+
96
+ ## Input
97
+ 5 channels
98
+ - 3 RGB channels
99
+ - +ve signal channel (this nuclei)
100
+ - -ve signal channel (other nuclei)
101
+
102
+ ## Output
103
+ 2 channels
104
+ - 0 = Background
105
+ - 1 = Nuclei
106
+
107
+ ![](https://developer.download.nvidia.com/assets/Clara/Images/monai_pathology_nuclick_annotation_train_in_out.jpeg)
108
+
109
+
110
+ ## Performance
111
+ This model achieves the following Dice score on the validation data provided as part of the dataset:
112
+
113
+ - Train Dice score = 0.89
114
+ - Validation Dice score = 0.85
115
+
116
+
117
+ #### Training Loss and Dice
118
+ A graph showing the training Loss and Dice over 50 epochs.
119
+
120
+ ![](https://developer.download.nvidia.com/assets/Clara/Images/monai_pathology_nuclick_annotation_train_loss_v2.png) <br>
121
+ ![](https://developer.download.nvidia.com/assets/Clara/Images/monai_pathology_nuclick_annotation_train_dice_v2.png) <br>
122
+
123
+ #### Validation Dice
124
+ A graph showing the validation mean Dice over 50 epochs.
125
+
126
+ ![](https://developer.download.nvidia.com/assets/Clara/Images/monai_pathology_nuclick_annotation_val_dice_v2.png) <br>
127
+
128
+ #### TensorRT speedup
129
+ This bundle supports acceleration with TensorRT. The table below displays the speedup ratios observed on an A100 80G GPU.
130
+
131
+ | method | torch_fp32(ms) | torch_amp(ms) | trt_fp32(ms) | trt_fp16(ms) | speedup amp | speedup fp32 | speedup fp16 | amp vs fp16|
132
+ | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
133
+ | model computation | 3.27 | 4.31 | 2.12 | 1.73 | 0.76 | 1.54 | 1.89 | 2.49 |
134
+ | end2end | 705.32 | 752.64 | 290.45 | 347.07 | 0.94 | 2.43 | 2.03 | 2.17 |
135
+
136
+ Where:
137
+ - `model computation` means the speedup ratio of model's inference with a random input without preprocessing and postprocessing
138
+ - `end2end` means run the bundle end-to-end with the TensorRT based model.
139
+ - `torch_fp32` and `torch_amp` are for the PyTorch models with or without `amp` mode.
140
+ - `trt_fp32` and `trt_fp16` are for the TensorRT based models converted in corresponding precision.
141
+ - `speedup amp`, `speedup fp32` and `speedup fp16` are the speedup ratios of corresponding models versus the PyTorch float32 model
142
+ - `amp vs fp16` is the speedup ratio between the PyTorch amp model and the TensorRT float16 based model.
143
+
144
+ This result is benchmarked under:
145
+ - TensorRT: 8.6.1+cuda12.0
146
+ - Torch-TensorRT Version: 1.4.0
147
+ - CPU Architecture: x86-64
148
+ - OS: ubuntu 20.04
149
+ - Python version:3.8.10
150
+ - CUDA version: 12.1
151
+ - GPU models and configuration: A100 80G
152
+
153
+ ## MONAI Bundle Commands
154
+ In 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.
155
+
156
+ For more details usage instructions, visit the [MONAI Bundle Configuration Page](https://docs.monai.io/en/latest/config_syntax.html).
157
+
158
+ #### Execute training:
159
+
160
+ ```
161
+ python -m monai.bundle run --config_file configs/train.json
162
+ ```
163
+
164
+ 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`:
165
+
166
+ ```
167
+ python -m monai.bundle run --config_file configs/train.json --dataset_dir <actual dataset path>
168
+ ```
169
+
170
+ #### Override the `train` config to execute multi-GPU training:
171
+
172
+ ```
173
+ torchrun --standalone --nnodes=1 --nproc_per_node=2 -m monai.bundle run --config_file "['configs/train.json','configs/multi_gpu_train.json']"
174
+ ```
175
+
176
+ 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).
177
+
178
+ #### Override the `train` config to execute evaluation with the trained model:
179
+
180
+ ```
181
+ python -m monai.bundle run --config_file "['configs/train.json','configs/evaluate.json']"
182
+ ```
183
+
184
+ #### Override the `train` config and `evaluate` config to execute multi-GPU evaluation:
185
+
186
+ ```
187
+ 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']"
188
+ ```
189
+
190
+ #### Execute inference:
191
+
192
+ ```
193
+ python -m monai.bundle run --config_file configs/inference.json
194
+ ```
195
+
196
+ #### Export checkpoint to TensorRT based models with fp32 or fp16 precision:
197
+
198
+ ```
199
+ python -m monai.bundle trt_export --net_id network_def --filepath models/model_trt.ts --ckpt_file models/model.pt --meta_file configs/metadata.json --config_file configs/inference.json --precision <fp32/fp16> --use_trace "True"
200
+ ```
201
+
202
+ #### Execute inference with the TensorRT model:
203
+
204
+ ```
205
+ python -m monai.bundle run --config_file "['configs/inference.json', 'configs/inference_trt.json']"
206
+ ```
207
+
208
+ # References
209
+ [1] Koohbanani, Navid Alemi, et al. "NuClick: a deep learning framework for interactive segmentation of microscopic images." Medical Image Analysis 65 (2020): 101771. https://arxiv.org/abs/2005.14511.
210
+
211
+ [2] 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)]
212
+
213
+ [3] NuClick [PyTorch](https://github.com/mostafajahanifar/nuclick_torch) Implementation
214
+
215
+ # License
216
+ Copyright (c) MONAI Consortium
217
+
218
+ Licensed under the Apache License, Version 2.0 (the "License");
219
+ you may not use this file except in compliance with the License.
220
+ You may obtain a copy of the License at
221
+
222
+ http://www.apache.org/licenses/LICENSE-2.0
223
+
224
+ Unless required by applicable law or agreed to in writing, software
225
+ distributed under the License is distributed on an "AS IS" BASIS,
226
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
227
+ See the License for the specific language governing permissions and
228
+ limitations under the License.
docs/data_license.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Third Party Licenses
2
+ -----------------------------------------------------------------------
3
+
4
+ /*********************************************************************/
5
+ i. HoVer-Net: Simultaneous Segmentation and Classification of Nuclei in Multi-Tissue Histology Images
6
+ https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet/
models/model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e40ca4d2a5e8649d9faef3aa9a0ec6fa201526d0262a4bc63431a151b178a8ae
3
+ size 31162823
models/model.ts ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b519966e4571708b3cc0ca78b1178e58e26558227f988b5be3618a438ed0864
3
+ size 31274615
scripts/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from .handlers import TensorBoardImageHandler
scripts/data_process.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+ import argparse
12
+ import glob
13
+ import json
14
+ import logging
15
+ import os
16
+
17
+ from dataset import consep_nuclei_dataset
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ def main():
23
+ logging.basicConfig(
24
+ level=logging.INFO,
25
+ format="[%(asctime)s] [%(process)s] [%(threadName)s] [%(levelname)s] (%(name)s:%(lineno)d) - %(message)s",
26
+ datefmt="%Y-%m-%d %H:%M:%S",
27
+ force=True,
28
+ )
29
+
30
+ parser = argparse.ArgumentParser()
31
+ parser.add_argument(
32
+ "--input",
33
+ "-i",
34
+ type=str,
35
+ default=r"/workspace/data/CoNSeP",
36
+ help="Input/Downloaded/Extracted dir for CoNSeP Dataset",
37
+ )
38
+ parser.add_argument(
39
+ "--output",
40
+ "-o",
41
+ type=str,
42
+ default=r"/workspace/data/CoNSePNuclei",
43
+ help="Output dir to store pre-processed data",
44
+ )
45
+ parser.add_argument("--crop_size", "-s", type=int, default=128, help="Crop size for each Nuclei")
46
+ parser.add_argument("--limit", "-n", type=int, default=0, help="Non-zero value to limit processing max records")
47
+
48
+ args = parser.parse_args()
49
+ dataset_json = {}
50
+ for f, v in {"Train": "training", "Test": "validation"}.items():
51
+ logger.info("---------------------------------------------------------------------------------")
52
+ if not os.path.exists(os.path.join(args.input, f)):
53
+ logger.warning(f"Ignore {f} (NOT Exists in Input Folder)")
54
+ continue
55
+
56
+ logger.info(f"Processing Images/labels for: {f}")
57
+ images_path = os.path.join(args.input, f, "Images", "*.png")
58
+ labels_path = os.path.join(args.input, f, "Labels", "*.mat")
59
+ images = sorted(glob.glob(images_path))
60
+ labels = sorted(glob.glob(labels_path))
61
+ ds = [{"image": i, "label": l} for i, l in zip(images, labels)]
62
+
63
+ output_dir = os.path.join(args.output, f) if args.output else f
64
+ crop_size = args.crop_size
65
+ limit = args.limit
66
+
67
+ ds_new = consep_nuclei_dataset(ds, output_dir, crop_size, limit=limit)
68
+ logger.info(f"Total Generated/Extended Records: {len(ds)} => {len(ds_new)}")
69
+
70
+ dataset_json[v] = ds_new
71
+
72
+ ds_file = os.path.join(args.output, "dataset.json")
73
+ with open(ds_file, "w") as fp:
74
+ json.dump(dataset_json, fp, indent=2)
75
+ logger.info(f"Dataset JSON Generated at: {ds_file}")
76
+
77
+
78
+ if __name__ == "__main__":
79
+ main()
scripts/dataset.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ import copy
13
+ import json
14
+ import logging
15
+ import os
16
+ import pathlib
17
+ from typing import Dict, List
18
+
19
+ import numpy as np
20
+ from monai.apps.utils import tqdm
21
+ from monai.utils import optional_import
22
+
23
+ loadmat, _ = optional_import("scipy.io", name="loadmat")
24
+ PILImage, _ = optional_import("PIL.Image")
25
+
26
+
27
+ def consep_nuclei_dataset(datalist, output_dir, crop_size, min_area=80, min_distance=20, limit=0) -> List[Dict]:
28
+ """
29
+ Utility to pre-process and create dataset list for Patches per Nuclei for training over ConSeP dataset.
30
+
31
+ Args:
32
+ datalist: A list of data dictionary. Each entry should at least contain 'image_key': <image filename>.
33
+ For example, typical input data can be a list of dictionaries::
34
+
35
+ [{'image': <image filename>, 'label': <label filename>}]
36
+
37
+ output_dir: target directory to store the training data after flattening
38
+ crop_size: Crop Size for each patch
39
+ min_area: Min Area for each nuclei to be included in dataset
40
+ min_distance: Min Distance from boundary for each nuclei to be included in dataset
41
+ limit: limit number of inputs for pre-processing. Defaults to 0 (no limit).
42
+
43
+ Raises:
44
+ ValueError: When ``datalist`` is Empty
45
+ ValueError: When ``scipy.io.loadmat`` is Not available
46
+
47
+ Returns:
48
+ A new datalist that contains path to the images/labels after pre-processing.
49
+
50
+ Example::
51
+
52
+ datalist = consep_nuclei_dataset(
53
+ datalist=[{'image': 'img1.png', 'label': 'label1.mat'}],
54
+ output_dir=output,
55
+ crop_size=128,
56
+ limit=1,
57
+ )
58
+
59
+ print(datalist[0]["image"], datalist[0]["label"])
60
+ """
61
+
62
+ if not len(datalist):
63
+ raise ValueError("Input datalist is empty")
64
+
65
+ if not loadmat:
66
+ print("Please make sure scipy with loadmat function is correctly installed")
67
+ raise ValueError("scipy.io.loadmat module/function not found")
68
+
69
+ dataset_json: List[Dict] = []
70
+ for d in tqdm(datalist):
71
+ logging.debug(f"Processing Image: {d['image']} => Label: {d['label']}")
72
+
73
+ # Image
74
+ image = PILImage.open(d["image"]).convert("RGB")
75
+
76
+ # Label
77
+ m = loadmat(d["label"])
78
+ instances = m["inst_map"]
79
+
80
+ for nuclei_id, (class_id, (y, x)) in enumerate(zip(m["inst_type"], m["inst_centroid"]), start=1):
81
+ x, y = (int(x), int(y))
82
+ class_id = int(class_id)
83
+ class_id = 3 if class_id in (3, 4) else 4 if class_id in (5, 6, 7) else class_id # override
84
+
85
+ if 0 < limit <= len(dataset_json):
86
+ return dataset_json
87
+
88
+ item = __prepare_patch(
89
+ d=d,
90
+ nuclei_id=nuclei_id,
91
+ output_dir=output_dir,
92
+ image=image,
93
+ instances=instances,
94
+ instance_idx=nuclei_id,
95
+ crop_size=crop_size,
96
+ class_id=class_id,
97
+ centroid=(x, y),
98
+ min_area=min_area,
99
+ min_distance=min_distance,
100
+ others_idx=255,
101
+ )
102
+
103
+ if item:
104
+ dataset_json.append(item)
105
+
106
+ return dataset_json
107
+
108
+
109
+ def __prepare_patch(
110
+ d,
111
+ nuclei_id,
112
+ output_dir,
113
+ image,
114
+ instances,
115
+ instance_idx,
116
+ crop_size,
117
+ class_id,
118
+ centroid,
119
+ min_area,
120
+ min_distance,
121
+ others_idx=255,
122
+ ):
123
+ image_np = np.array(image)
124
+ image_size = image.size
125
+
126
+ bbox = __compute_bbox(crop_size, centroid, image_size)
127
+
128
+ cropped_label_np = instances[bbox[0] : bbox[2], bbox[1] : bbox[3]]
129
+ cropped_label_np = np.array(cropped_label_np)
130
+
131
+ this_label = np.where(cropped_label_np == instance_idx, class_id, 0)
132
+ if np.count_nonzero(this_label) < min_area:
133
+ return None
134
+
135
+ x, y = centroid
136
+ if x < min_distance or y < min_distance or (image_size[0] - x) < min_distance or (image_size[1] - y < min_distance):
137
+ return None
138
+
139
+ centroid = centroid[0] - bbox[0], centroid[1] - bbox[1]
140
+ others = np.where(np.logical_and(cropped_label_np > 0, cropped_label_np != instance_idx), others_idx, 0)
141
+ cropped_label_np = this_label + others
142
+ cropped_label = PILImage.fromarray(cropped_label_np.astype(np.uint8), None)
143
+
144
+ cropped_image_np = image_np[bbox[0] : bbox[2], bbox[1] : bbox[3], :]
145
+ cropped_image = PILImage.fromarray(cropped_image_np, "RGB")
146
+
147
+ images_dir = os.path.join(output_dir, "Images") if output_dir else "Images"
148
+ labels_dir = os.path.join(output_dir, "Labels") if output_dir else "Labels"
149
+ centroids_dir = os.path.join(output_dir, "Centroids") if output_dir else "Centroids"
150
+
151
+ os.makedirs(images_dir, exist_ok=True)
152
+ os.makedirs(labels_dir, exist_ok=True)
153
+ os.makedirs(centroids_dir, exist_ok=True)
154
+
155
+ image_id = pathlib.Path(d["image"]).stem
156
+ file_prefix = f"{image_id}_{class_id}_{str(instance_idx).zfill(4)}"
157
+ image_file = os.path.join(images_dir, f"{file_prefix}.png")
158
+ label_file = os.path.join(labels_dir, f"{file_prefix}.png")
159
+ centroid_file = os.path.join(centroids_dir, f"{file_prefix}.txt")
160
+
161
+ cropped_image.save(image_file)
162
+ cropped_label.save(label_file)
163
+ with open(centroid_file, "w") as fp:
164
+ json.dump([centroid], fp)
165
+
166
+ item = copy.deepcopy(d)
167
+ item["nuclei_id"] = nuclei_id
168
+ item["mask_value"] = class_id
169
+ item["image"] = image_file
170
+ item["label"] = label_file
171
+ item["centroid"] = centroid
172
+ return item
173
+
174
+
175
+ def __compute_bbox(patch_size, centroid, size):
176
+ x, y = centroid
177
+ m, n = size
178
+
179
+ x_start = int(max(x - patch_size / 2, 0))
180
+ y_start = int(max(y - patch_size / 2, 0))
181
+ x_end = x_start + patch_size
182
+ y_end = y_start + patch_size
183
+ if x_end > m:
184
+ x_end = m
185
+ x_start = m - patch_size
186
+ if y_end > n:
187
+ y_end = n
188
+ y_start = n - patch_size
189
+ return x_start, y_start, x_end, y_end
scripts/handlers.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ import logging
13
+ from typing import TYPE_CHECKING, Callable, Optional
14
+
15
+ import numpy as np
16
+ import torch
17
+ import torch.distributed
18
+ from monai.utils import IgniteInfo, min_version, optional_import
19
+
20
+ Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events")
21
+ make_grid, _ = optional_import("torchvision.utils", name="make_grid")
22
+ Image, _ = optional_import("PIL.Image")
23
+ ImageDraw, _ = optional_import("PIL.ImageDraw")
24
+
25
+ if TYPE_CHECKING:
26
+ from ignite.engine import Engine
27
+ from torch.utils.tensorboard import SummaryWriter
28
+ else:
29
+ Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine")
30
+ SummaryWriter, _ = optional_import("torch.utils.tensorboard", name="SummaryWriter")
31
+
32
+
33
+ class TensorBoardImageHandler:
34
+ def __init__(
35
+ self,
36
+ summary_writer: Optional[SummaryWriter] = None,
37
+ log_dir: str = "./runs",
38
+ tag_name="val",
39
+ interval: int = 1,
40
+ batch_transform: Callable = lambda x: x,
41
+ output_transform: Callable = lambda x: x,
42
+ batch_limit=1,
43
+ device=None,
44
+ ) -> None:
45
+ self.writer = SummaryWriter(log_dir=log_dir) if summary_writer is None else summary_writer
46
+ self.tag_name = tag_name
47
+ self.interval = interval
48
+ self.batch_transform = batch_transform
49
+ self.output_transform = output_transform
50
+ self.batch_limit = batch_limit
51
+ self.device = device
52
+
53
+ self.logger = logging.getLogger(__name__)
54
+
55
+ if torch.distributed.is_initialized():
56
+ self.tag_name = f"{self.tag_name}-r{torch.distributed.get_rank()}"
57
+
58
+ def attach(self, engine: Engine) -> None:
59
+ engine.add_event_handler(Events.EPOCH_COMPLETED(every=self.interval), self, "epoch")
60
+
61
+ def __call__(self, engine: Engine, action) -> None:
62
+ epoch = engine.state.epoch
63
+ batch_data = self.batch_transform(engine.state.batch)
64
+ output_data = self.output_transform(engine.state.output)
65
+
66
+ self.write_images(batch_data, output_data, epoch)
67
+
68
+ def write_images(self, batch_data, output_data, epoch):
69
+ for bidx in range(len(batch_data)):
70
+ image = batch_data[bidx]["image"].detach().cpu().numpy()
71
+ y = output_data[bidx]["label"].detach().cpu().numpy()
72
+
73
+ tag_prefix = f"{self.tag_name} - b{bidx} - " if self.batch_limit != 1 else ""
74
+ img_np = image[:3]
75
+ img_np[0, :, :] = np.where(y[0] > 0, 1, img_np[0, :, :])
76
+ img_tensor = make_grid(torch.from_numpy(img_np), normalize=True)
77
+ self.writer.add_image(tag=f"{tag_prefix}Image", img_tensor=img_tensor, global_step=epoch)
78
+
79
+ y_pred = output_data[bidx]["pred"].detach().cpu().numpy()
80
+
81
+ cl = np.count_nonzero(y)
82
+ cp = np.count_nonzero(y_pred)
83
+ self.logger.info(
84
+ "{} => {} - Image: {};"
85
+ " Label: {} (nz: {});"
86
+ " Pred: {} (nz: {});"
87
+ " Diff: {:.2f}%;"
88
+ " Sig: (pos-nz: {}, neg-nz: {})".format(
89
+ self.tag_name,
90
+ bidx,
91
+ image.shape,
92
+ y.shape,
93
+ cl,
94
+ y_pred.shape,
95
+ cp,
96
+ 100 * (cp - cl) / (cl + 1),
97
+ np.count_nonzero(image[3]),
98
+ np.count_nonzero(image[4]),
99
+ )
100
+ )
101
+
102
+ tag_prefix = f"{self.tag_name} - b{bidx} - " if self.batch_limit != 1 else f"{self.tag_name} - "
103
+ label_pred = [y, y_pred, image[3][None] > 0, image[4][None] > 0]
104
+ label_pred_tag = f"{tag_prefix}Label vs Pred vs Pos vs Neg"
105
+
106
+ img_tensor = make_grid(tensor=torch.from_numpy(np.array(label_pred)), nrow=4, normalize=True, pad_value=10)
107
+ self.writer.add_image(tag=label_pred_tag, img_tensor=img_tensor, global_step=epoch)
108
+
109
+ if self.batch_limit == 1 or bidx == (self.batch_limit - 1):
110
+ break