initialize the model package structure
Browse files- .gitattributes +1 -0
- LICENSE +201 -0
- README.md +183 -0
- configs/evaluate.json +58 -0
- configs/inference.json +130 -0
- configs/logging.conf +21 -0
- configs/metadata.json +79 -0
- configs/multi_gpu_evaluate.json +30 -0
- configs/multi_gpu_train.json +41 -0
- configs/train.json +328 -0
- docs/README.md +176 -0
- docs/data_license.txt +6 -0
- docs/images/dataset.jpeg +0 -0
- docs/images/train_dice.jpeg +0 -0
- docs/images/train_in_out.jpeg +0 -0
- docs/images/train_loss.jpeg +0 -0
- docs/images/val_dice.jpeg +0 -0
- models/model.pt +3 -0
- models/model.ts +3 -0
- scripts/__init__.py +12 -0
- scripts/data_process.py +79 -0
- scripts/dataset.py +189 -0
- scripts/handlers.py +111 -0
.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.
|
README.md
ADDED
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
tags:
|
3 |
+
- monai
|
4 |
+
- medical
|
5 |
+
library_name: monai
|
6 |
+
license: apache-2.0
|
7 |
+
---
|
8 |
+
# Description
|
9 |
+
A pre-trained model for segmenting nuclei cells with user clicks/interactions.
|
10 |
+
|
11 |
+
![nuclick](https://github.com/mostafajahanifar/nuclick_torch/raw/master/docs/11.gif)
|
12 |
+
![nuclick](https://github.com/mostafajahanifar/nuclick_torch/raw/master/docs/33.gif)
|
13 |
+
![nuclick](https://github.com/mostafajahanifar/nuclick_torch/raw/master/docs/22.gif)
|
14 |
+
|
15 |
+
# Model Overview
|
16 |
+
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.
|
17 |
+
|
18 |
+
## Data
|
19 |
+
The training dataset is from https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet
|
20 |
+
```commandline
|
21 |
+
wget https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet/consep_dataset.zip
|
22 |
+
unzip -q consep_dataset.zip
|
23 |
+
```
|
24 |
+
![](images/dataset.jpeg)<br/>
|
25 |
+
|
26 |
+
## Training configuration
|
27 |
+
The training was performed with the following:
|
28 |
+
|
29 |
+
- GPU: at least 12GB of GPU memory
|
30 |
+
- Actual Model Input: 4 x 128 x 128
|
31 |
+
- AMP: True
|
32 |
+
- Optimizer: Adam
|
33 |
+
- Learning Rate: 1e-4
|
34 |
+
- Loss: DiceLoss
|
35 |
+
|
36 |
+
|
37 |
+
### Preprocessing
|
38 |
+
After [downloading this dataset](https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet/consep_dataset.zip),
|
39 |
+
python script `data_process.py` from `scripts` folder can be used to preprocess and generate the final dataset for training.
|
40 |
+
|
41 |
+
```
|
42 |
+
python scripts/data_process.py --input /path/to/data/CoNSeP --output /path/to/data/CoNSePNuclei
|
43 |
+
```
|
44 |
+
|
45 |
+
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.
|
46 |
+
|
47 |
+
Class values in dataset are
|
48 |
+
|
49 |
+
- 1 = other
|
50 |
+
- 2 = inflammatory
|
51 |
+
- 3 = healthy epithelial
|
52 |
+
- 4 = dysplastic/malignant epithelial
|
53 |
+
- 5 = fibroblast
|
54 |
+
- 6 = muscle
|
55 |
+
- 7 = endothelial
|
56 |
+
|
57 |
+
As part of pre-processing, the following steps are executed.
|
58 |
+
|
59 |
+
- Crop and Extract each nuclei Image + Label (128x128) based on the centroid given in the dataset.
|
60 |
+
- Combine classes 3 & 4 into the epithelial class and 5,6 & 7 into the spindle-shaped class.
|
61 |
+
- Update the label index for the target nuclie based on the class value
|
62 |
+
- Other cells which are part of the patch are modified to have label idex = 255
|
63 |
+
|
64 |
+
Example dataset.json
|
65 |
+
```json
|
66 |
+
{
|
67 |
+
"training": [
|
68 |
+
{
|
69 |
+
"image": "/workspace/data/CoNSePNuclei/Train/Images/train_1_3_0001.png",
|
70 |
+
"label": "/workspace/data/CoNSePNuclei/Train/Labels/train_1_3_0001.png",
|
71 |
+
"nuclei_id": 1,
|
72 |
+
"mask_value": 3,
|
73 |
+
"centroid": [
|
74 |
+
64,
|
75 |
+
64
|
76 |
+
]
|
77 |
+
}
|
78 |
+
],
|
79 |
+
"validation": [
|
80 |
+
{
|
81 |
+
"image": "/workspace/data/CoNSePNuclei/Test/Images/test_1_3_0001.png",
|
82 |
+
"label": "/workspace/data/CoNSePNuclei/Test/Labels/test_1_3_0001.png",
|
83 |
+
"nuclei_id": 1,
|
84 |
+
"mask_value": 3,
|
85 |
+
"centroid": [
|
86 |
+
64,
|
87 |
+
64
|
88 |
+
]
|
89 |
+
}
|
90 |
+
]
|
91 |
+
}
|
92 |
+
```
|
93 |
+
|
94 |
+
|
95 |
+
## Input and output formats
|
96 |
+
### Input: 5 channels
|
97 |
+
- 3 RGB channels
|
98 |
+
- +ve signal channel (this nuclei)
|
99 |
+
- -ve signal channel (other nuclei)
|
100 |
+
|
101 |
+
### Output: 2 channels
|
102 |
+
- 0 = Background
|
103 |
+
- 1 = Nuclei
|
104 |
+
|
105 |
+
![](images/train_in_out.jpeg)
|
106 |
+
|
107 |
+
## Scores
|
108 |
+
This model achieves the following Dice score on the validation data provided as part of the dataset:
|
109 |
+
|
110 |
+
- Train Dice score = 0.89
|
111 |
+
- Validation Dice score = 0.85
|
112 |
+
|
113 |
+
|
114 |
+
## Training Performance
|
115 |
+
A graph showing the training Loss and Dice over 50 epochs.
|
116 |
+
|
117 |
+
![](images/train_loss.jpeg) <br>
|
118 |
+
![](images/train_dice.jpeg) <br>
|
119 |
+
|
120 |
+
## Validation Performance
|
121 |
+
A graph showing the validation mean Dice over 50 epochs.
|
122 |
+
|
123 |
+
![](images/val_dice.jpeg) <br>
|
124 |
+
|
125 |
+
|
126 |
+
## commands example
|
127 |
+
Execute training:
|
128 |
+
|
129 |
+
```
|
130 |
+
python -m monai.bundle run training --meta_file configs/metadata.json --config_file configs/train.json --logging_file configs/logging.conf
|
131 |
+
```
|
132 |
+
|
133 |
+
Override the `train` config to execute multi-GPU training:
|
134 |
+
|
135 |
+
```
|
136 |
+
torchrun --standalone --nnodes=1 --nproc_per_node=2 -m monai.bundle run training --meta_file configs/metadata.json --config_file "['configs/train.json','configs/multi_gpu_train.json']" --logging_file configs/logging.conf
|
137 |
+
```
|
138 |
+
|
139 |
+
Please note that the distributed training related options depend on the actual running environment, thus you may need to remove `--standalone`, modify `--nnodes` or do some other necessary changes according to the machine you used.
|
140 |
+
Please refer to [pytorch's official tutorial](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html) for more details.
|
141 |
+
|
142 |
+
Override the `train` config to execute evaluation with the trained model:
|
143 |
+
|
144 |
+
```
|
145 |
+
python -m monai.bundle run evaluating --meta_file configs/metadata.json --config_file "['configs/train.json','configs/evaluate.json']" --logging_file configs/logging.conf
|
146 |
+
```
|
147 |
+
|
148 |
+
Override the `train` config and `evaluate` config to execute multi-GPU evaluation:
|
149 |
+
|
150 |
+
```
|
151 |
+
torchrun --standalone --nnodes=1 --nproc_per_node=2 -m monai.bundle run evaluating --meta_file configs/metadata.json --config_file "['configs/train.json','configs/evaluate.json','configs/multi_gpu_evaluate.json']" --logging_file configs/logging.conf
|
152 |
+
```
|
153 |
+
|
154 |
+
Execute inference:
|
155 |
+
|
156 |
+
```
|
157 |
+
python -m monai.bundle run evaluating --meta_file configs/metadata.json --config_file configs/inference.json --logging_file configs/logging.conf
|
158 |
+
```
|
159 |
+
|
160 |
+
# Disclaimer
|
161 |
+
This is an example, not to be used for diagnostic purposes.
|
162 |
+
|
163 |
+
# References
|
164 |
+
[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.
|
165 |
+
|
166 |
+
[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)]
|
167 |
+
|
168 |
+
[3] NuClick [PyTorch](https://github.com/mostafajahanifar/nuclick_torch) Implementation
|
169 |
+
|
170 |
+
# License
|
171 |
+
Copyright (c) MONAI Consortium
|
172 |
+
|
173 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
174 |
+
you may not use this file except in compliance with the License.
|
175 |
+
You may obtain a copy of the License at
|
176 |
+
|
177 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
178 |
+
|
179 |
+
Unless required by applicable law or agreed to in writing, software
|
180 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
181 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
182 |
+
See the License for the specific language governing permissions and
|
183 |
+
limitations under the License.
|
configs/evaluate.json
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_acc"
|
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 |
+
"evaluating": [
|
53 |
+
"$import sys",
|
54 |
+
"$sys.path.append(@bundle_root)",
|
55 |
+
"$setattr(torch.backends.cudnn, 'benchmark', True)",
|
56 |
+
"$@validate#evaluator.run()"
|
57 |
+
]
|
58 |
+
}
|
configs/inference.json
ADDED
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"imports": [
|
3 |
+
"$import glob",
|
4 |
+
"$import json",
|
5 |
+
"$import pathlib",
|
6 |
+
"$import os"
|
7 |
+
],
|
8 |
+
"bundle_root": "/workspace/data/pathology_nuclick_annotation",
|
9 |
+
"output_dir": "$@bundle_root + '/eval'",
|
10 |
+
"dataset_dir": "/workspace/data/CoNSePNuclei",
|
11 |
+
"images": "$list(sorted(glob.glob(@dataset_dir + '/Test/Images/*.png')))[:1]",
|
12 |
+
"centroids": "$list(sorted(glob.glob(@dataset_dir + '/Test/Centroids/*.txt')))[:1]",
|
13 |
+
"input_data": "$[{'image': i, 'foreground': json.loads(pathlib.Path(c).read_text())} for i,c in zip(@images, @centroids)]",
|
14 |
+
"device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')",
|
15 |
+
"network_def": {
|
16 |
+
"_target_": "BasicUNet",
|
17 |
+
"spatial_dims": 2,
|
18 |
+
"in_channels": 5,
|
19 |
+
"out_channels": 1,
|
20 |
+
"features": [
|
21 |
+
32,
|
22 |
+
64,
|
23 |
+
128,
|
24 |
+
256,
|
25 |
+
512,
|
26 |
+
32
|
27 |
+
]
|
28 |
+
},
|
29 |
+
"network": "$@network_def.to(@device)",
|
30 |
+
"preprocessing": {
|
31 |
+
"_target_": "Compose",
|
32 |
+
"transforms": [
|
33 |
+
{
|
34 |
+
"_target_": "LoadImaged",
|
35 |
+
"keys": "image",
|
36 |
+
"dtype": "uint8"
|
37 |
+
},
|
38 |
+
{
|
39 |
+
"_target_": "EnsureChannelFirstd",
|
40 |
+
"keys": "image"
|
41 |
+
},
|
42 |
+
{
|
43 |
+
"_target_": "ScaleIntensityRanged",
|
44 |
+
"keys": "image",
|
45 |
+
"a_min": 0.0,
|
46 |
+
"a_max": 255.0,
|
47 |
+
"b_min": -1.0,
|
48 |
+
"b_max": 1.0
|
49 |
+
},
|
50 |
+
{
|
51 |
+
"_target_": "AddClickSignalsd",
|
52 |
+
"image": "image",
|
53 |
+
"foreground": "foreground",
|
54 |
+
"gaussian": false
|
55 |
+
},
|
56 |
+
{
|
57 |
+
"_target_": "SqueezeDimd",
|
58 |
+
"keys": "image"
|
59 |
+
}
|
60 |
+
]
|
61 |
+
},
|
62 |
+
"dataset": {
|
63 |
+
"_target_": "Dataset",
|
64 |
+
"data": "@input_data",
|
65 |
+
"transform": "@preprocessing"
|
66 |
+
},
|
67 |
+
"dataloader": {
|
68 |
+
"_target_": "DataLoader",
|
69 |
+
"dataset": "@dataset",
|
70 |
+
"batch_size": 1,
|
71 |
+
"shuffle": false,
|
72 |
+
"num_workers": 4
|
73 |
+
},
|
74 |
+
"inferer": {
|
75 |
+
"_target_": "SimpleInferer"
|
76 |
+
},
|
77 |
+
"postprocessing": {
|
78 |
+
"_target_": "Compose",
|
79 |
+
"transforms": [
|
80 |
+
{
|
81 |
+
"_target_": "Activationsd",
|
82 |
+
"keys": "pred",
|
83 |
+
"sigmoid": true
|
84 |
+
},
|
85 |
+
{
|
86 |
+
"_target_": "AsDiscreted",
|
87 |
+
"keys": "pred",
|
88 |
+
"threshold": 0.5
|
89 |
+
},
|
90 |
+
{
|
91 |
+
"_target_": "KeepLargestConnectedComponentd",
|
92 |
+
"keys": "pred"
|
93 |
+
},
|
94 |
+
{
|
95 |
+
"_target_": "SaveImaged",
|
96 |
+
"keys": "pred",
|
97 |
+
"meta_keys": "pred_meta_dict",
|
98 |
+
"output_dir": "@output_dir",
|
99 |
+
"output_ext": ".png"
|
100 |
+
}
|
101 |
+
]
|
102 |
+
},
|
103 |
+
"handlers": [
|
104 |
+
{
|
105 |
+
"_target_": "CheckpointLoader",
|
106 |
+
"load_path": "$@bundle_root + '/models/model.pt'",
|
107 |
+
"load_dict": {
|
108 |
+
"model": "@network"
|
109 |
+
}
|
110 |
+
},
|
111 |
+
{
|
112 |
+
"_target_": "StatsHandler",
|
113 |
+
"iteration_log": false
|
114 |
+
}
|
115 |
+
],
|
116 |
+
"evaluator": {
|
117 |
+
"_target_": "SupervisedEvaluator",
|
118 |
+
"device": "@device",
|
119 |
+
"val_data_loader": "@dataloader",
|
120 |
+
"network": "@network",
|
121 |
+
"inferer": "@inferer",
|
122 |
+
"postprocessing": "@postprocessing",
|
123 |
+
"val_handlers": "@handlers",
|
124 |
+
"amp": true
|
125 |
+
},
|
126 |
+
"evaluating": [
|
127 |
+
"$setattr(torch.backends.cudnn, 'benchmark', True)",
|
128 |
+
"$@evaluator.run()"
|
129 |
+
]
|
130 |
+
}
|
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,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"schema": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/meta_schema_20220324.json",
|
3 |
+
"version": "0.0.1",
|
4 |
+
"changelog": {
|
5 |
+
"0.0.1": "initialize the model package structure"
|
6 |
+
},
|
7 |
+
"monai_version": "1.0.1",
|
8 |
+
"pytorch_version": "1.13.0",
|
9 |
+
"numpy_version": "1.21.2",
|
10 |
+
"optional_packages_version": {
|
11 |
+
"nibabel": "4.0.1",
|
12 |
+
"pytorch-ignite": "0.4.9"
|
13 |
+
},
|
14 |
+
"task": "Pathology Nuclick segmentation",
|
15 |
+
"description": "A pre-trained model for Nuclei Classification within Haematoxylin & Eosin stained histology images",
|
16 |
+
"authors": "MONAI team",
|
17 |
+
"copyright": "Copyright (c) MONAI Consortium",
|
18 |
+
"data_source": "consep_dataset.zip from https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet",
|
19 |
+
"data_type": "png",
|
20 |
+
"image_classes": "RGB channel data, intensity scaled to [0, 1]",
|
21 |
+
"label_classes": "single channel data",
|
22 |
+
"pred_classes": "1 channel data, with value 1 as nuclei and 0 as background",
|
23 |
+
"eval_metrics": {
|
24 |
+
"mean_dice": 0.85
|
25 |
+
},
|
26 |
+
"intended_use": "This is an example, not to be used for diagnostic purposes",
|
27 |
+
"references": [
|
28 |
+
"Koohbanani, Navid Alemi, et al. \"NuClick: A Deep Learning Framework for Interactive Segmentation of Microscopy Images.\" https://arxiv.org/abs/2005.14511",
|
29 |
+
"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",
|
30 |
+
"NuClick PyTorch Implementation, https://github.com/mostafajahanifar/nuclick_torch"
|
31 |
+
],
|
32 |
+
"network_data_format": {
|
33 |
+
"inputs": {
|
34 |
+
"image": {
|
35 |
+
"type": "png",
|
36 |
+
"format": "RGB",
|
37 |
+
"modality": "regular",
|
38 |
+
"num_channels": 5,
|
39 |
+
"spatial_shape": [
|
40 |
+
128,
|
41 |
+
128
|
42 |
+
],
|
43 |
+
"dtype": "float32",
|
44 |
+
"value_range": [
|
45 |
+
0,
|
46 |
+
1
|
47 |
+
],
|
48 |
+
"is_patch_data": false,
|
49 |
+
"channel_def": {
|
50 |
+
"0": "R",
|
51 |
+
"1": "G",
|
52 |
+
"2": "B",
|
53 |
+
"3": "+ve Signal",
|
54 |
+
"4": "-ve Signal"
|
55 |
+
}
|
56 |
+
}
|
57 |
+
},
|
58 |
+
"outputs": {
|
59 |
+
"pred": {
|
60 |
+
"type": "image",
|
61 |
+
"format": "segmentation",
|
62 |
+
"num_channels": 1,
|
63 |
+
"spatial_shape": [
|
64 |
+
128,
|
65 |
+
128
|
66 |
+
],
|
67 |
+
"dtype": "float32",
|
68 |
+
"value_range": [
|
69 |
+
0,
|
70 |
+
1
|
71 |
+
],
|
72 |
+
"is_patch_data": false,
|
73 |
+
"channel_def": {
|
74 |
+
"0": "Nuclei"
|
75 |
+
}
|
76 |
+
}
|
77 |
+
}
|
78 |
+
}
|
79 |
+
}
|
configs/multi_gpu_evaluate.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"device": "$torch.device(f'cuda:{dist.get_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 |
+
"evaluating": [
|
19 |
+
"$import sys",
|
20 |
+
"$sys.path.append(@bundle_root)",
|
21 |
+
"$import torch.distributed as dist",
|
22 |
+
"$dist.init_process_group(backend='nccl')",
|
23 |
+
"$torch.cuda.set_device(@device)",
|
24 |
+
"$setattr(torch.backends.cudnn, 'benchmark', True)",
|
25 |
+
"$import logging",
|
26 |
+
"$@validate#evaluator.logger.setLevel(logging.WARNING if dist.get_rank() > 0 else logging.INFO)",
|
27 |
+
"$@validate#evaluator.run()",
|
28 |
+
"$dist.destroy_process_group()"
|
29 |
+
]
|
30 |
+
}
|
configs/multi_gpu_train.json
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"device": "$torch.device(f'cuda:{dist.get_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 |
+
"training": [
|
28 |
+
"$import sys",
|
29 |
+
"$sys.path.append(@bundle_root)",
|
30 |
+
"$import torch.distributed as dist",
|
31 |
+
"$dist.init_process_group(backend='nccl')",
|
32 |
+
"$torch.cuda.set_device(@device)",
|
33 |
+
"$monai.utils.set_determinism(seed=123)",
|
34 |
+
"$setattr(torch.backends.cudnn, 'benchmark', True)",
|
35 |
+
"$import logging",
|
36 |
+
"$@train#trainer.logger.setLevel(logging.WARNING if dist.get_rank() > 0 else logging.INFO)",
|
37 |
+
"$@validate#evaluator.logger.setLevel(logging.WARNING if dist.get_rank() > 0 else logging.INFO)",
|
38 |
+
"$@train#trainer.run()",
|
39 |
+
"$dist.destroy_process_group()"
|
40 |
+
]
|
41 |
+
}
|
configs/train.json
ADDED
@@ -0,0 +1,328 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"imports": [
|
3 |
+
"$import glob",
|
4 |
+
"$import ignite",
|
5 |
+
"$import json",
|
6 |
+
"$import pathlib",
|
7 |
+
"$import os"
|
8 |
+
],
|
9 |
+
"bundle_root": "/workspace/data/pathology_nuclick_annotation",
|
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": "$@network.parameters()",
|
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 |
+
},
|
56 |
+
{
|
57 |
+
"_target_": "EnsureChannelFirstd",
|
58 |
+
"keys": [
|
59 |
+
"image",
|
60 |
+
"label"
|
61 |
+
]
|
62 |
+
},
|
63 |
+
{
|
64 |
+
"_target_": "SplitLabeld",
|
65 |
+
"keys": "label",
|
66 |
+
"mask_value": "",
|
67 |
+
"others_value": 255
|
68 |
+
},
|
69 |
+
{
|
70 |
+
"_target_": "RandTorchVisiond",
|
71 |
+
"keys": "image",
|
72 |
+
"name": "ColorJitter",
|
73 |
+
"brightness": 0.251,
|
74 |
+
"contrast": 0.75,
|
75 |
+
"saturation": 0.25,
|
76 |
+
"hue": 0.04,
|
77 |
+
"prob": 0.5
|
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 |
+
},
|
213 |
+
{
|
214 |
+
"_target_": "EnsureChannelFirstd",
|
215 |
+
"keys": [
|
216 |
+
"image",
|
217 |
+
"label"
|
218 |
+
]
|
219 |
+
},
|
220 |
+
{
|
221 |
+
"_target_": "SplitLabeld",
|
222 |
+
"keys": "label",
|
223 |
+
"mask_value": "",
|
224 |
+
"others_value": 255
|
225 |
+
},
|
226 |
+
{
|
227 |
+
"_target_": "ScaleIntensityRanged",
|
228 |
+
"keys": "image",
|
229 |
+
"a_min": 0.0,
|
230 |
+
"a_max": 255.0,
|
231 |
+
"b_min": -1.0,
|
232 |
+
"b_max": 1.0
|
233 |
+
},
|
234 |
+
{
|
235 |
+
"_target_": "AddPointGuidanceSignald",
|
236 |
+
"image": "image",
|
237 |
+
"label": "label",
|
238 |
+
"others": "others",
|
239 |
+
"use_distance": true,
|
240 |
+
"gaussian": false,
|
241 |
+
"drop_rate": 1.0
|
242 |
+
},
|
243 |
+
{
|
244 |
+
"_target_": "SelectItemsd",
|
245 |
+
"keys": [
|
246 |
+
"image",
|
247 |
+
"label"
|
248 |
+
]
|
249 |
+
}
|
250 |
+
]
|
251 |
+
},
|
252 |
+
"dataset": {
|
253 |
+
"_target_": "CacheDataset",
|
254 |
+
"data": "@val_datalist",
|
255 |
+
"transform": "@validate#preprocessing",
|
256 |
+
"cache_rate": 1.0
|
257 |
+
},
|
258 |
+
"dataloader": {
|
259 |
+
"_target_": "DataLoader",
|
260 |
+
"dataset": "@validate#dataset",
|
261 |
+
"batch_size": 64,
|
262 |
+
"shuffle": false,
|
263 |
+
"num_workers": 4
|
264 |
+
},
|
265 |
+
"inferer": {
|
266 |
+
"_target_": "SimpleInferer"
|
267 |
+
},
|
268 |
+
"postprocessing": "%train#postprocessing",
|
269 |
+
"handlers": [
|
270 |
+
{
|
271 |
+
"_target_": "StatsHandler",
|
272 |
+
"iteration_log": false
|
273 |
+
},
|
274 |
+
{
|
275 |
+
"_target_": "TensorBoardStatsHandler",
|
276 |
+
"log_dir": "@output_dir",
|
277 |
+
"iteration_log": false
|
278 |
+
},
|
279 |
+
{
|
280 |
+
"_target_": "CheckpointSaver",
|
281 |
+
"save_dir": "@ckpt_dir",
|
282 |
+
"save_dict": {
|
283 |
+
"model": "@network"
|
284 |
+
},
|
285 |
+
"save_key_metric": true,
|
286 |
+
"key_metric_filename": "model.pt"
|
287 |
+
},
|
288 |
+
{
|
289 |
+
"_target_": "scripts.TensorBoardImageHandler",
|
290 |
+
"log_dir": "@output_dir",
|
291 |
+
"batch_limit": 8,
|
292 |
+
"tag_name": "val"
|
293 |
+
}
|
294 |
+
],
|
295 |
+
"key_metric": {
|
296 |
+
"val_mean_dice": {
|
297 |
+
"_target_": "MeanDice",
|
298 |
+
"include_background": false,
|
299 |
+
"output_transform": "$monai.handlers.from_engine(['pred', 'label'])"
|
300 |
+
}
|
301 |
+
},
|
302 |
+
"additional_metrics": {
|
303 |
+
"val_accuracy": {
|
304 |
+
"_target_": "ignite.metrics.Accuracy",
|
305 |
+
"output_transform": "$monai.handlers.from_engine(['pred', 'label'])"
|
306 |
+
}
|
307 |
+
},
|
308 |
+
"evaluator": {
|
309 |
+
"_target_": "SupervisedEvaluator",
|
310 |
+
"device": "@device",
|
311 |
+
"val_data_loader": "@validate#dataloader",
|
312 |
+
"network": "@network",
|
313 |
+
"inferer": "@validate#inferer",
|
314 |
+
"postprocessing": "@validate#postprocessing",
|
315 |
+
"key_val_metric": "@validate#key_metric",
|
316 |
+
"additional_metrics": "@validate#additional_metrics",
|
317 |
+
"val_handlers": "@validate#handlers",
|
318 |
+
"amp": true
|
319 |
+
}
|
320 |
+
},
|
321 |
+
"training": [
|
322 |
+
"$import sys",
|
323 |
+
"$sys.path.append(@bundle_root)",
|
324 |
+
"$monai.utils.set_determinism(seed=123)",
|
325 |
+
"$setattr(torch.backends.cudnn, 'benchmark', True)",
|
326 |
+
"$@train#trainer.run()"
|
327 |
+
]
|
328 |
+
}
|
docs/README.md
ADDED
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Description
|
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 |
+
# Model Overview
|
9 |
+
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.
|
10 |
+
|
11 |
+
## Data
|
12 |
+
The training dataset is from https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet
|
13 |
+
```commandline
|
14 |
+
wget https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet/consep_dataset.zip
|
15 |
+
unzip -q consep_dataset.zip
|
16 |
+
```
|
17 |
+
![](images/dataset.jpeg)<br/>
|
18 |
+
|
19 |
+
## Training configuration
|
20 |
+
The training was performed with the following:
|
21 |
+
|
22 |
+
- GPU: at least 12GB of GPU memory
|
23 |
+
- Actual Model Input: 4 x 128 x 128
|
24 |
+
- AMP: True
|
25 |
+
- Optimizer: Adam
|
26 |
+
- Learning Rate: 1e-4
|
27 |
+
- Loss: DiceLoss
|
28 |
+
|
29 |
+
|
30 |
+
### Preprocessing
|
31 |
+
After [downloading this dataset](https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet/consep_dataset.zip),
|
32 |
+
python script `data_process.py` from `scripts` folder can be used to preprocess and generate the final dataset for training.
|
33 |
+
|
34 |
+
```
|
35 |
+
python scripts/data_process.py --input /path/to/data/CoNSeP --output /path/to/data/CoNSePNuclei
|
36 |
+
```
|
37 |
+
|
38 |
+
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.
|
39 |
+
|
40 |
+
Class values in dataset are
|
41 |
+
|
42 |
+
- 1 = other
|
43 |
+
- 2 = inflammatory
|
44 |
+
- 3 = healthy epithelial
|
45 |
+
- 4 = dysplastic/malignant epithelial
|
46 |
+
- 5 = fibroblast
|
47 |
+
- 6 = muscle
|
48 |
+
- 7 = endothelial
|
49 |
+
|
50 |
+
As part of pre-processing, the following steps are executed.
|
51 |
+
|
52 |
+
- Crop and Extract each nuclei Image + Label (128x128) based on the centroid given in the dataset.
|
53 |
+
- Combine classes 3 & 4 into the epithelial class and 5,6 & 7 into the spindle-shaped class.
|
54 |
+
- Update the label index for the target nuclie based on the class value
|
55 |
+
- Other cells which are part of the patch are modified to have label idex = 255
|
56 |
+
|
57 |
+
Example dataset.json
|
58 |
+
```json
|
59 |
+
{
|
60 |
+
"training": [
|
61 |
+
{
|
62 |
+
"image": "/workspace/data/CoNSePNuclei/Train/Images/train_1_3_0001.png",
|
63 |
+
"label": "/workspace/data/CoNSePNuclei/Train/Labels/train_1_3_0001.png",
|
64 |
+
"nuclei_id": 1,
|
65 |
+
"mask_value": 3,
|
66 |
+
"centroid": [
|
67 |
+
64,
|
68 |
+
64
|
69 |
+
]
|
70 |
+
}
|
71 |
+
],
|
72 |
+
"validation": [
|
73 |
+
{
|
74 |
+
"image": "/workspace/data/CoNSePNuclei/Test/Images/test_1_3_0001.png",
|
75 |
+
"label": "/workspace/data/CoNSePNuclei/Test/Labels/test_1_3_0001.png",
|
76 |
+
"nuclei_id": 1,
|
77 |
+
"mask_value": 3,
|
78 |
+
"centroid": [
|
79 |
+
64,
|
80 |
+
64
|
81 |
+
]
|
82 |
+
}
|
83 |
+
]
|
84 |
+
}
|
85 |
+
```
|
86 |
+
|
87 |
+
|
88 |
+
## Input and output formats
|
89 |
+
### Input: 5 channels
|
90 |
+
- 3 RGB channels
|
91 |
+
- +ve signal channel (this nuclei)
|
92 |
+
- -ve signal channel (other nuclei)
|
93 |
+
|
94 |
+
### Output: 2 channels
|
95 |
+
- 0 = Background
|
96 |
+
- 1 = Nuclei
|
97 |
+
|
98 |
+
![](images/train_in_out.jpeg)
|
99 |
+
|
100 |
+
## Scores
|
101 |
+
This model achieves the following Dice score on the validation data provided as part of the dataset:
|
102 |
+
|
103 |
+
- Train Dice score = 0.89
|
104 |
+
- Validation Dice score = 0.85
|
105 |
+
|
106 |
+
|
107 |
+
## Training Performance
|
108 |
+
A graph showing the training Loss and Dice over 50 epochs.
|
109 |
+
|
110 |
+
![](images/train_loss.jpeg) <br>
|
111 |
+
![](images/train_dice.jpeg) <br>
|
112 |
+
|
113 |
+
## Validation Performance
|
114 |
+
A graph showing the validation mean Dice over 50 epochs.
|
115 |
+
|
116 |
+
![](images/val_dice.jpeg) <br>
|
117 |
+
|
118 |
+
|
119 |
+
## commands example
|
120 |
+
Execute training:
|
121 |
+
|
122 |
+
```
|
123 |
+
python -m monai.bundle run training --meta_file configs/metadata.json --config_file configs/train.json --logging_file configs/logging.conf
|
124 |
+
```
|
125 |
+
|
126 |
+
Override the `train` config to execute multi-GPU training:
|
127 |
+
|
128 |
+
```
|
129 |
+
torchrun --standalone --nnodes=1 --nproc_per_node=2 -m monai.bundle run training --meta_file configs/metadata.json --config_file "['configs/train.json','configs/multi_gpu_train.json']" --logging_file configs/logging.conf
|
130 |
+
```
|
131 |
+
|
132 |
+
Please note that the distributed training related options depend on the actual running environment, thus you may need to remove `--standalone`, modify `--nnodes` or do some other necessary changes according to the machine you used.
|
133 |
+
Please refer to [pytorch's official tutorial](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html) for more details.
|
134 |
+
|
135 |
+
Override the `train` config to execute evaluation with the trained model:
|
136 |
+
|
137 |
+
```
|
138 |
+
python -m monai.bundle run evaluating --meta_file configs/metadata.json --config_file "['configs/train.json','configs/evaluate.json']" --logging_file configs/logging.conf
|
139 |
+
```
|
140 |
+
|
141 |
+
Override the `train` config and `evaluate` config to execute multi-GPU evaluation:
|
142 |
+
|
143 |
+
```
|
144 |
+
torchrun --standalone --nnodes=1 --nproc_per_node=2 -m monai.bundle run evaluating --meta_file configs/metadata.json --config_file "['configs/train.json','configs/evaluate.json','configs/multi_gpu_evaluate.json']" --logging_file configs/logging.conf
|
145 |
+
```
|
146 |
+
|
147 |
+
Execute inference:
|
148 |
+
|
149 |
+
```
|
150 |
+
python -m monai.bundle run evaluating --meta_file configs/metadata.json --config_file configs/inference.json --logging_file configs/logging.conf
|
151 |
+
```
|
152 |
+
|
153 |
+
# Disclaimer
|
154 |
+
This is an example, not to be used for diagnostic purposes.
|
155 |
+
|
156 |
+
# References
|
157 |
+
[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.
|
158 |
+
|
159 |
+
[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)]
|
160 |
+
|
161 |
+
[3] NuClick [PyTorch](https://github.com/mostafajahanifar/nuclick_torch) Implementation
|
162 |
+
|
163 |
+
# License
|
164 |
+
Copyright (c) MONAI Consortium
|
165 |
+
|
166 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
167 |
+
you may not use this file except in compliance with the License.
|
168 |
+
You may obtain a copy of the License at
|
169 |
+
|
170 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
171 |
+
|
172 |
+
Unless required by applicable law or agreed to in writing, software
|
173 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
174 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
175 |
+
See the License for the specific language governing permissions and
|
176 |
+
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/
|
docs/images/dataset.jpeg
ADDED
docs/images/train_dice.jpeg
ADDED
docs/images/train_in_out.jpeg
ADDED
docs/images/train_loss.jpeg
ADDED
docs/images/val_dice.jpeg
ADDED
models/model.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9886629a19d2f3ef2d607d156f1c9409d32d193a7b831d19df35cf4cf303aebe
|
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,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.config import IgniteInfo
|
19 |
+
from monai.utils import min_version, optional_import
|
20 |
+
|
21 |
+
Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events")
|
22 |
+
make_grid, _ = optional_import("torchvision.utils", name="make_grid")
|
23 |
+
Image, _ = optional_import("PIL.Image")
|
24 |
+
ImageDraw, _ = optional_import("PIL.ImageDraw")
|
25 |
+
|
26 |
+
if TYPE_CHECKING:
|
27 |
+
from ignite.engine import Engine
|
28 |
+
from torch.utils.tensorboard import SummaryWriter
|
29 |
+
else:
|
30 |
+
Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine")
|
31 |
+
SummaryWriter, _ = optional_import("torch.utils.tensorboard", name="SummaryWriter")
|
32 |
+
|
33 |
+
|
34 |
+
class TensorBoardImageHandler:
|
35 |
+
def __init__(
|
36 |
+
self,
|
37 |
+
summary_writer: Optional[SummaryWriter] = None,
|
38 |
+
log_dir: str = "./runs",
|
39 |
+
tag_name="val",
|
40 |
+
interval: int = 1,
|
41 |
+
batch_transform: Callable = lambda x: x,
|
42 |
+
output_transform: Callable = lambda x: x,
|
43 |
+
batch_limit=1,
|
44 |
+
device=None,
|
45 |
+
) -> None:
|
46 |
+
self.writer = SummaryWriter(log_dir=log_dir) if summary_writer is None else summary_writer
|
47 |
+
self.tag_name = tag_name
|
48 |
+
self.interval = interval
|
49 |
+
self.batch_transform = batch_transform
|
50 |
+
self.output_transform = output_transform
|
51 |
+
self.batch_limit = batch_limit
|
52 |
+
self.device = device
|
53 |
+
|
54 |
+
self.logger = logging.getLogger(__name__)
|
55 |
+
|
56 |
+
if torch.distributed.is_initialized():
|
57 |
+
self.tag_name = f"{self.tag_name}-r{torch.distributed.get_rank()}"
|
58 |
+
|
59 |
+
def attach(self, engine: Engine) -> None:
|
60 |
+
engine.add_event_handler(Events.EPOCH_COMPLETED(every=self.interval), self, "epoch")
|
61 |
+
|
62 |
+
def __call__(self, engine: Engine, action) -> None:
|
63 |
+
epoch = engine.state.epoch
|
64 |
+
batch_data = self.batch_transform(engine.state.batch)
|
65 |
+
output_data = self.output_transform(engine.state.output)
|
66 |
+
|
67 |
+
self.write_images(batch_data, output_data, epoch)
|
68 |
+
|
69 |
+
def write_images(self, batch_data, output_data, epoch):
|
70 |
+
for bidx in range(len(batch_data)):
|
71 |
+
image = batch_data[bidx]["image"].detach().cpu().numpy()
|
72 |
+
y = output_data[bidx]["label"].detach().cpu().numpy()
|
73 |
+
|
74 |
+
tag_prefix = f"{self.tag_name} - b{bidx} - " if self.batch_limit != 1 else ""
|
75 |
+
img_np = image[:3]
|
76 |
+
img_np[0, :, :] = np.where(y[0] > 0, 1, img_np[0, :, :])
|
77 |
+
img_tensor = make_grid(torch.from_numpy(img_np), normalize=True)
|
78 |
+
self.writer.add_image(tag=f"{tag_prefix}Image", img_tensor=img_tensor, global_step=epoch)
|
79 |
+
|
80 |
+
y_pred = output_data[bidx]["pred"].detach().cpu().numpy()
|
81 |
+
|
82 |
+
cl = np.count_nonzero(y)
|
83 |
+
cp = np.count_nonzero(y_pred)
|
84 |
+
self.logger.info(
|
85 |
+
"{} => {} - Image: {};"
|
86 |
+
" Label: {} (nz: {});"
|
87 |
+
" Pred: {} (nz: {});"
|
88 |
+
" Diff: {:.2f}%;"
|
89 |
+
" Sig: (pos-nz: {}, neg-nz: {})".format(
|
90 |
+
self.tag_name,
|
91 |
+
bidx,
|
92 |
+
image.shape,
|
93 |
+
y.shape,
|
94 |
+
cl,
|
95 |
+
y_pred.shape,
|
96 |
+
cp,
|
97 |
+
100 * (cp - cl) / (cl + 1),
|
98 |
+
np.count_nonzero(image[3]),
|
99 |
+
np.count_nonzero(image[4]),
|
100 |
+
)
|
101 |
+
)
|
102 |
+
|
103 |
+
tag_prefix = f"{self.tag_name} - b{bidx} - " if self.batch_limit != 1 else f"{self.tag_name} - "
|
104 |
+
label_pred = [y, y_pred, image[3][None] > 0, image[4][None] > 0]
|
105 |
+
label_pred_tag = f"{tag_prefix}Label vs Pred vs Pos vs Neg"
|
106 |
+
|
107 |
+
img_tensor = make_grid(tensor=torch.from_numpy(np.array(label_pred)), nrow=4, normalize=True, pad_value=10)
|
108 |
+
self.writer.add_image(tag=label_pred_tag, img_tensor=img_tensor, global_step=epoch)
|
109 |
+
|
110 |
+
if self.batch_limit == 1 or bidx == (self.batch_limit - 1):
|
111 |
+
break
|