initialize the model package structure
Browse files- .gitattributes +1 -0
- LICENSE +201 -0
- README.md +200 -0
- configs/evaluate.json +60 -0
- configs/inference.json +116 -0
- configs/logging.conf +21 -0
- configs/metadata.json +81 -0
- configs/multi_gpu_evaluate.json +32 -0
- configs/multi_gpu_train.json +41 -0
- configs/train.json +350 -0
- docs/README.md +193 -0
- docs/data_license.txt +6 -0
- docs/images/dataset.jpeg +0 -0
- docs/images/train_f1.jpeg +0 -0
- docs/images/train_loss.jpeg +0 -0
- docs/images/val_f1.jpeg +0 -0
- docs/images/val_in_out.jpeg +0 -0
- models/model.pt +3 -0
- models/model.ts +3 -0
- scripts/__init__.py +13 -0
- scripts/data_process.py +79 -0
- scripts/dataset.py +189 -0
- scripts/handlers.py +142 -0
- scripts/writer.py +54 -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,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 classifying nuclei cells as the following types.
|
10 |
+
- Other
|
11 |
+
- Inflammatory
|
12 |
+
- Epithelial
|
13 |
+
- Spindle-Shaped
|
14 |
+
|
15 |
+
# Model Overview
|
16 |
+
This model is trained using [DenseNet121](https://docs.monai.io/en/latest/networks.html#densenet121) over [ConSeP](https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet) dataset.
|
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: torch.nn.CrossEntropyLoss
|
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 |
+
```commandline
|
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` in output folder:
|
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: 4 channels
|
97 |
+
- 3 RGB channels
|
98 |
+
- 1 signal channel (label mask)
|
99 |
+
|
100 |
+
### Output: 4 channels
|
101 |
+
- 0 = Other
|
102 |
+
- 1 = Inflammatory
|
103 |
+
- 2 = Epithelial
|
104 |
+
- 3 = Spindle-Shaped
|
105 |
+
|
106 |
+
![](images/val_in_out.jpeg)
|
107 |
+
|
108 |
+
## Scores
|
109 |
+
This model achieves the following F1 score on the validation data provided as part of the dataset:
|
110 |
+
|
111 |
+
- Train F1 score = 0.96
|
112 |
+
- Validation F1 score = 0.85
|
113 |
+
|
114 |
+
<hr/>
|
115 |
+
Confusion Metrics for <b>Validation</b> for individual classes are (at epoch 50):
|
116 |
+
|
117 |
+
| Metric | Other | Inflammatory | Epithelial | Spindle-Shaped |
|
118 |
+
|-----------|--------|--------------|------------|----------------|
|
119 |
+
| Precision | 0.5846 | 0.7143 | 0.9158 | 0.8399 |
|
120 |
+
| Recall | 0.2550 | 0.8441 | 0.9193 | 0.8106 |
|
121 |
+
| F1-score | 0.3551 | 0.7738 | 0.9175 | 0.8250 |
|
122 |
+
|
123 |
+
|
124 |
+
<hr/>
|
125 |
+
Confusion Metrics for <b>Training</b> for individual classes are (at epoch 50):
|
126 |
+
|
127 |
+
| Metric | Other | Inflammatory | Epithelial | Spindle-Shaped |
|
128 |
+
|-----------|--------|--------------|------------|----------------|
|
129 |
+
| Precision | 0.9059 | 0.9569 | 0.9754 | 0.9494 |
|
130 |
+
| Recall | 0.8370 | 0.9547 | 0.9790 | 0.9502 |
|
131 |
+
| F1-score | 0.8701 | 0.9558 | 0.9772 | 0.9498 |
|
132 |
+
|
133 |
+
|
134 |
+
|
135 |
+
## Training Performance
|
136 |
+
A graph showing the training Loss and F1-score over 50 epochs.
|
137 |
+
|
138 |
+
![](images/train_loss.jpeg) <br>
|
139 |
+
![](images/train_f1.jpeg) <br>
|
140 |
+
|
141 |
+
## Validation Performance
|
142 |
+
A graph showing the validation F1-score over 50 epochs.
|
143 |
+
|
144 |
+
![](images/val_f1.jpeg) <br>
|
145 |
+
|
146 |
+
|
147 |
+
## commands example
|
148 |
+
Execute training:
|
149 |
+
|
150 |
+
```
|
151 |
+
python -m monai.bundle run training --meta_file configs/metadata.json --config_file configs/train.json --logging_file configs/logging.conf
|
152 |
+
```
|
153 |
+
|
154 |
+
Override the `train` config to execute multi-GPU training:
|
155 |
+
|
156 |
+
```
|
157 |
+
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
|
158 |
+
```
|
159 |
+
|
160 |
+
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.
|
161 |
+
Please refer to [pytorch's official tutorial](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html) for more details.
|
162 |
+
|
163 |
+
Override the `train` config to execute evaluation with the trained model:
|
164 |
+
|
165 |
+
```
|
166 |
+
python -m monai.bundle run evaluating --meta_file configs/metadata.json --config_file "['configs/train.json','configs/evaluate.json']" --logging_file configs/logging.conf
|
167 |
+
```
|
168 |
+
|
169 |
+
Override the `train` config and `evaluate` config to execute multi-GPU evaluation:
|
170 |
+
|
171 |
+
```
|
172 |
+
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
|
173 |
+
```
|
174 |
+
|
175 |
+
Execute inference:
|
176 |
+
|
177 |
+
```
|
178 |
+
python -m monai.bundle run evaluating --meta_file configs/metadata.json --config_file configs/inference.json --logging_file configs/logging.conf
|
179 |
+
```
|
180 |
+
|
181 |
+
# Disclaimer
|
182 |
+
This is an example, not to be used for diagnostic purposes.
|
183 |
+
|
184 |
+
# References
|
185 |
+
[1] S. Graham, Q. D. Vu, S. E. A. Raza, A. Azam, Y-W. Tsang, J. T. Kwak and N. Rajpoot. "HoVer-Net: Simultaneous Segmentation and Classification of Nuclei in Multi-Tissue Histology Images." Medical Image Analysis, Sept. 2019. [[doi](https://doi.org/10.1016/j.media.2019.101563)]
|
186 |
+
|
187 |
+
# License
|
188 |
+
Copyright (c) MONAI Consortium
|
189 |
+
|
190 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
191 |
+
you may not use this file except in compliance with the License.
|
192 |
+
You may obtain a copy of the License at
|
193 |
+
|
194 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
195 |
+
|
196 |
+
Unless required by applicable law or agreed to in writing, software
|
197 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
198 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
199 |
+
See the License for the specific language governing permissions and
|
200 |
+
limitations under the License.
|
configs/evaluate.json
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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": ".json"
|
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 |
+
"$import scripts",
|
57 |
+
"$monai.data.register_writer('json', scripts.ClassificationWriter)",
|
58 |
+
"$@validate#evaluator.run()"
|
59 |
+
]
|
60 |
+
}
|
configs/inference.json
ADDED
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"imports": [
|
3 |
+
"$import glob",
|
4 |
+
"$import json",
|
5 |
+
"$import pathlib",
|
6 |
+
"$import os"
|
7 |
+
],
|
8 |
+
"bundle_root": "/workspace/data/pathology_nuclei_classification",
|
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 |
+
"labels": "$list(sorted(glob.glob(@dataset_dir + '/Test/Labels/*.png')))[:1]",
|
13 |
+
"input_data": "$[{'image': i, 'label': l} for i,l in zip(@images, @labels)]",
|
14 |
+
"device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')",
|
15 |
+
"network_def": {
|
16 |
+
"_target_": "DenseNet121",
|
17 |
+
"spatial_dims": 2,
|
18 |
+
"in_channels": 4,
|
19 |
+
"out_channels": 4
|
20 |
+
},
|
21 |
+
"network": "$@network_def.to(@device)",
|
22 |
+
"preprocessing": {
|
23 |
+
"_target_": "Compose",
|
24 |
+
"transforms": [
|
25 |
+
{
|
26 |
+
"_target_": "LoadImaged",
|
27 |
+
"keys": [
|
28 |
+
"image",
|
29 |
+
"label"
|
30 |
+
],
|
31 |
+
"dtype": "uint8"
|
32 |
+
},
|
33 |
+
{
|
34 |
+
"_target_": "EnsureChannelFirstd",
|
35 |
+
"keys": [
|
36 |
+
"image",
|
37 |
+
"label"
|
38 |
+
]
|
39 |
+
},
|
40 |
+
{
|
41 |
+
"_target_": "ScaleIntensityRanged",
|
42 |
+
"keys": "image",
|
43 |
+
"a_min": 0.0,
|
44 |
+
"a_max": 255.0,
|
45 |
+
"b_min": -1.0,
|
46 |
+
"b_max": 1.0
|
47 |
+
},
|
48 |
+
{
|
49 |
+
"_target_": "AddLabelAsGuidanced",
|
50 |
+
"keys": "image",
|
51 |
+
"source": "label"
|
52 |
+
}
|
53 |
+
]
|
54 |
+
},
|
55 |
+
"dataset": {
|
56 |
+
"_target_": "Dataset",
|
57 |
+
"data": "@input_data",
|
58 |
+
"transform": "@preprocessing"
|
59 |
+
},
|
60 |
+
"dataloader": {
|
61 |
+
"_target_": "DataLoader",
|
62 |
+
"dataset": "@dataset",
|
63 |
+
"batch_size": 1,
|
64 |
+
"shuffle": false,
|
65 |
+
"num_workers": 4
|
66 |
+
},
|
67 |
+
"inferer": {
|
68 |
+
"_target_": "SimpleInferer"
|
69 |
+
},
|
70 |
+
"postprocessing": {
|
71 |
+
"_target_": "Compose",
|
72 |
+
"transforms": [
|
73 |
+
{
|
74 |
+
"_target_": "Activationsd",
|
75 |
+
"keys": "pred",
|
76 |
+
"softmax": true
|
77 |
+
},
|
78 |
+
{
|
79 |
+
"_target_": "SaveImaged",
|
80 |
+
"keys": "pred",
|
81 |
+
"meta_keys": "pred_meta_dict",
|
82 |
+
"output_dir": "@output_dir",
|
83 |
+
"output_ext": ".json"
|
84 |
+
}
|
85 |
+
]
|
86 |
+
},
|
87 |
+
"handlers": [
|
88 |
+
{
|
89 |
+
"_target_": "CheckpointLoader",
|
90 |
+
"load_path": "$@bundle_root + '/models/model.pt'",
|
91 |
+
"load_dict": {
|
92 |
+
"model": "@network"
|
93 |
+
}
|
94 |
+
},
|
95 |
+
{
|
96 |
+
"_target_": "StatsHandler",
|
97 |
+
"iteration_log": false
|
98 |
+
}
|
99 |
+
],
|
100 |
+
"evaluator": {
|
101 |
+
"_target_": "SupervisedEvaluator",
|
102 |
+
"device": "@device",
|
103 |
+
"val_data_loader": "@dataloader",
|
104 |
+
"network": "@network",
|
105 |
+
"inferer": "@inferer",
|
106 |
+
"postprocessing": "@postprocessing",
|
107 |
+
"val_handlers": "@handlers",
|
108 |
+
"amp": true
|
109 |
+
},
|
110 |
+
"evaluating": [
|
111 |
+
"$setattr(torch.backends.cudnn, 'benchmark', True)",
|
112 |
+
"$import scripts",
|
113 |
+
"$monai.data.register_writer('json', scripts.ClassificationWriter)",
|
114 |
+
"[email protected]()"
|
115 |
+
]
|
116 |
+
}
|
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,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 Nuclei Classification",
|
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": "4 channels OneHot data, channel 0 is Other, channel 1 is Inflammatory, channel 2 is Epithelial, channel 3 is Spindle-Shaped",
|
23 |
+
"eval_metrics": {
|
24 |
+
"f1_score": 0.85
|
25 |
+
},
|
26 |
+
"intended_use": "This is an example, not to be used for diagnostic purposes",
|
27 |
+
"references": [
|
28 |
+
"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"
|
29 |
+
],
|
30 |
+
"network_data_format": {
|
31 |
+
"inputs": {
|
32 |
+
"image": {
|
33 |
+
"type": "magnitude",
|
34 |
+
"format": "RGB",
|
35 |
+
"modality": "regular",
|
36 |
+
"num_channels": 4,
|
37 |
+
"spatial_shape": [
|
38 |
+
128,
|
39 |
+
128
|
40 |
+
],
|
41 |
+
"dtype": "float32",
|
42 |
+
"value_range": [
|
43 |
+
0,
|
44 |
+
1
|
45 |
+
],
|
46 |
+
"is_patch_data": false,
|
47 |
+
"channel_def": {
|
48 |
+
"0": "R",
|
49 |
+
"1": "G",
|
50 |
+
"2": "B",
|
51 |
+
"3": "Mask"
|
52 |
+
}
|
53 |
+
}
|
54 |
+
},
|
55 |
+
"outputs": {
|
56 |
+
"pred": {
|
57 |
+
"type": "probabilities",
|
58 |
+
"format": "classes",
|
59 |
+
"num_channels": 4,
|
60 |
+
"spatial_shape": [
|
61 |
+
1,
|
62 |
+
4
|
63 |
+
],
|
64 |
+
"dtype": "float32",
|
65 |
+
"value_range": [
|
66 |
+
0,
|
67 |
+
1,
|
68 |
+
2,
|
69 |
+
3
|
70 |
+
],
|
71 |
+
"is_patch_data": false,
|
72 |
+
"channel_def": {
|
73 |
+
"0": "Other",
|
74 |
+
"1": "Inflammatory",
|
75 |
+
"2": "Epithelial",
|
76 |
+
"3": "Spindle-Shaped"
|
77 |
+
}
|
78 |
+
}
|
79 |
+
}
|
80 |
+
}
|
81 |
+
}
|
configs/multi_gpu_evaluate.json
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"$import scripts",
|
28 |
+
"$monai.data.register_writer('json', scripts.ClassificationWriter)",
|
29 |
+
"$@validate#evaluator.run()",
|
30 |
+
"$dist.destroy_process_group()"
|
31 |
+
]
|
32 |
+
}
|
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,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_nuclei_classification",
|
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_": "DenseNet121",
|
20 |
+
"spatial_dims": 2,
|
21 |
+
"in_channels": 4,
|
22 |
+
"out_channels": 4
|
23 |
+
},
|
24 |
+
"network": "$@network_def.to(@device)",
|
25 |
+
"loss": {
|
26 |
+
"_target_": "torch.nn.CrossEntropyLoss"
|
27 |
+
},
|
28 |
+
"optimizer": {
|
29 |
+
"_target_": "torch.optim.Adam",
|
30 |
+
"params": "[email protected]()",
|
31 |
+
"lr": 0.0001
|
32 |
+
},
|
33 |
+
"max_epochs": 5,
|
34 |
+
"train": {
|
35 |
+
"preprocessing": {
|
36 |
+
"_target_": "Compose",
|
37 |
+
"transforms": [
|
38 |
+
{
|
39 |
+
"_target_": "LoadImaged",
|
40 |
+
"keys": [
|
41 |
+
"image",
|
42 |
+
"label"
|
43 |
+
],
|
44 |
+
"dtype": "uint8"
|
45 |
+
},
|
46 |
+
{
|
47 |
+
"_target_": "EnsureChannelFirstd",
|
48 |
+
"keys": [
|
49 |
+
"image",
|
50 |
+
"label"
|
51 |
+
]
|
52 |
+
},
|
53 |
+
{
|
54 |
+
"_target_": "SplitLabeld",
|
55 |
+
"keys": "label",
|
56 |
+
"mask_value": "",
|
57 |
+
"others_value": 255,
|
58 |
+
"to_binary_mask": false
|
59 |
+
},
|
60 |
+
{
|
61 |
+
"_target_": "RandTorchVisiond",
|
62 |
+
"keys": "image",
|
63 |
+
"name": "ColorJitter",
|
64 |
+
"brightness": 0.25,
|
65 |
+
"contrast": 0.75,
|
66 |
+
"saturation": 0.25,
|
67 |
+
"hue": 0.04,
|
68 |
+
"prob": 0.5
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"_target_": "RandFlipd",
|
72 |
+
"keys": [
|
73 |
+
"image",
|
74 |
+
"label",
|
75 |
+
"others"
|
76 |
+
],
|
77 |
+
"prob": 0.5
|
78 |
+
},
|
79 |
+
{
|
80 |
+
"_target_": "RandRotate90d",
|
81 |
+
"keys": [
|
82 |
+
"image",
|
83 |
+
"label",
|
84 |
+
"others"
|
85 |
+
],
|
86 |
+
"prob": 0.5
|
87 |
+
},
|
88 |
+
{
|
89 |
+
"_target_": "ScaleIntensityRanged",
|
90 |
+
"keys": "image",
|
91 |
+
"a_min": 0.0,
|
92 |
+
"a_max": 255.0,
|
93 |
+
"b_min": -1.0,
|
94 |
+
"b_max": 1.0
|
95 |
+
},
|
96 |
+
{
|
97 |
+
"_target_": "AddLabelAsGuidanced",
|
98 |
+
"keys": "image",
|
99 |
+
"source": "label"
|
100 |
+
},
|
101 |
+
{
|
102 |
+
"_target_": "SetLabelClassd",
|
103 |
+
"keys": "label",
|
104 |
+
"offset": -1
|
105 |
+
},
|
106 |
+
{
|
107 |
+
"_target_": "SelectItemsd",
|
108 |
+
"keys": [
|
109 |
+
"image",
|
110 |
+
"label"
|
111 |
+
]
|
112 |
+
}
|
113 |
+
]
|
114 |
+
},
|
115 |
+
"dataset": {
|
116 |
+
"_target_": "CacheDataset",
|
117 |
+
"data": "@train_datalist",
|
118 |
+
"transform": "@train#preprocessing",
|
119 |
+
"cache_rate": 1.0,
|
120 |
+
"num_workers": 4
|
121 |
+
},
|
122 |
+
"dataloader": {
|
123 |
+
"_target_": "DataLoader",
|
124 |
+
"dataset": "@train#dataset",
|
125 |
+
"batch_size": 64,
|
126 |
+
"shuffle": true,
|
127 |
+
"num_workers": 4
|
128 |
+
},
|
129 |
+
"inferer": {
|
130 |
+
"_target_": "SimpleInferer"
|
131 |
+
},
|
132 |
+
"postprocessing": {
|
133 |
+
"_target_": "Compose",
|
134 |
+
"transforms": [
|
135 |
+
{
|
136 |
+
"_target_": "Activationsd",
|
137 |
+
"keys": "pred",
|
138 |
+
"softmax": true
|
139 |
+
},
|
140 |
+
{
|
141 |
+
"_target_": "AsDiscreted",
|
142 |
+
"keys": [
|
143 |
+
"pred",
|
144 |
+
"label"
|
145 |
+
],
|
146 |
+
"argmax": [
|
147 |
+
true,
|
148 |
+
false
|
149 |
+
],
|
150 |
+
"to_onehot": 4
|
151 |
+
},
|
152 |
+
{
|
153 |
+
"_target_": "ToTensord",
|
154 |
+
"keys": [
|
155 |
+
"pred",
|
156 |
+
"label"
|
157 |
+
],
|
158 |
+
"device": "@device"
|
159 |
+
}
|
160 |
+
]
|
161 |
+
},
|
162 |
+
"handlers": [
|
163 |
+
{
|
164 |
+
"_target_": "ValidationHandler",
|
165 |
+
"validator": "@validate#evaluator",
|
166 |
+
"epoch_level": true,
|
167 |
+
"interval": "@val_interval"
|
168 |
+
},
|
169 |
+
{
|
170 |
+
"_target_": "StatsHandler",
|
171 |
+
"tag_name": "train_loss",
|
172 |
+
"output_transform": "$monai.handlers.from_engine(['loss'], first=True)"
|
173 |
+
},
|
174 |
+
{
|
175 |
+
"_target_": "TensorBoardStatsHandler",
|
176 |
+
"log_dir": "@output_dir",
|
177 |
+
"tag_name": "train_loss",
|
178 |
+
"output_transform": "$monai.handlers.from_engine(['loss'], first=True)"
|
179 |
+
},
|
180 |
+
{
|
181 |
+
"_target_": "scripts.TensorBoardImageHandler",
|
182 |
+
"class_names": {
|
183 |
+
"0": "Other",
|
184 |
+
"1": "Inflammatory",
|
185 |
+
"2": "Epithelial",
|
186 |
+
"3": "Spindle-Shaped"
|
187 |
+
},
|
188 |
+
"log_dir": "@output_dir",
|
189 |
+
"batch_limit": 4,
|
190 |
+
"tag_name": "train"
|
191 |
+
}
|
192 |
+
],
|
193 |
+
"key_metric": {
|
194 |
+
"train_f1": {
|
195 |
+
"_target_": "ConfusionMatrix",
|
196 |
+
"metric_name": "f1 score",
|
197 |
+
"output_transform": "$monai.handlers.from_engine(['pred', 'label'])"
|
198 |
+
}
|
199 |
+
},
|
200 |
+
"trainer": {
|
201 |
+
"_target_": "SupervisedTrainer",
|
202 |
+
"max_epochs": "@max_epochs",
|
203 |
+
"device": "@device",
|
204 |
+
"train_data_loader": "@train#dataloader",
|
205 |
+
"network": "@network",
|
206 |
+
"loss_function": "@loss",
|
207 |
+
"optimizer": "@optimizer",
|
208 |
+
"inferer": "@train#inferer",
|
209 |
+
"postprocessing": "@train#postprocessing",
|
210 |
+
"key_train_metric": "@train#key_metric",
|
211 |
+
"train_handlers": "@train#handlers",
|
212 |
+
"amp": true
|
213 |
+
}
|
214 |
+
},
|
215 |
+
"validate": {
|
216 |
+
"preprocessing": {
|
217 |
+
"_target_": "Compose",
|
218 |
+
"transforms": [
|
219 |
+
{
|
220 |
+
"_target_": "LoadImaged",
|
221 |
+
"keys": [
|
222 |
+
"image",
|
223 |
+
"label"
|
224 |
+
],
|
225 |
+
"dtype": "uint8"
|
226 |
+
},
|
227 |
+
{
|
228 |
+
"_target_": "EnsureChannelFirstd",
|
229 |
+
"keys": [
|
230 |
+
"image",
|
231 |
+
"label"
|
232 |
+
]
|
233 |
+
},
|
234 |
+
{
|
235 |
+
"_target_": "SplitLabeld",
|
236 |
+
"keys": "label",
|
237 |
+
"mask_value": "",
|
238 |
+
"others_value": 255,
|
239 |
+
"to_binary_mask": false
|
240 |
+
},
|
241 |
+
{
|
242 |
+
"_target_": "ScaleIntensityRanged",
|
243 |
+
"keys": "image",
|
244 |
+
"a_min": 0.0,
|
245 |
+
"a_max": 255.0,
|
246 |
+
"b_min": -1.0,
|
247 |
+
"b_max": 1.0
|
248 |
+
},
|
249 |
+
{
|
250 |
+
"_target_": "AddLabelAsGuidanced",
|
251 |
+
"keys": "image",
|
252 |
+
"source": "label"
|
253 |
+
},
|
254 |
+
{
|
255 |
+
"_target_": "SetLabelClassd",
|
256 |
+
"keys": "label",
|
257 |
+
"offset": -1
|
258 |
+
},
|
259 |
+
{
|
260 |
+
"_target_": "SelectItemsd",
|
261 |
+
"keys": [
|
262 |
+
"image",
|
263 |
+
"label"
|
264 |
+
]
|
265 |
+
}
|
266 |
+
]
|
267 |
+
},
|
268 |
+
"dataset": {
|
269 |
+
"_target_": "CacheDataset",
|
270 |
+
"data": "@val_datalist",
|
271 |
+
"transform": "@validate#preprocessing",
|
272 |
+
"cache_rate": 1.0
|
273 |
+
},
|
274 |
+
"dataloader": {
|
275 |
+
"_target_": "DataLoader",
|
276 |
+
"dataset": "@validate#dataset",
|
277 |
+
"batch_size": 64,
|
278 |
+
"shuffle": false,
|
279 |
+
"num_workers": 4
|
280 |
+
},
|
281 |
+
"inferer": {
|
282 |
+
"_target_": "SimpleInferer"
|
283 |
+
},
|
284 |
+
"postprocessing": "%train#postprocessing",
|
285 |
+
"handlers": [
|
286 |
+
{
|
287 |
+
"_target_": "StatsHandler",
|
288 |
+
"iteration_log": false
|
289 |
+
},
|
290 |
+
{
|
291 |
+
"_target_": "TensorBoardStatsHandler",
|
292 |
+
"log_dir": "@output_dir",
|
293 |
+
"iteration_log": false
|
294 |
+
},
|
295 |
+
{
|
296 |
+
"_target_": "CheckpointSaver",
|
297 |
+
"save_dir": "@ckpt_dir",
|
298 |
+
"save_dict": {
|
299 |
+
"model": "@network"
|
300 |
+
},
|
301 |
+
"save_key_metric": true,
|
302 |
+
"key_metric_filename": "model.pt"
|
303 |
+
},
|
304 |
+
{
|
305 |
+
"_target_": "scripts.TensorBoardImageHandler",
|
306 |
+
"class_names": {
|
307 |
+
"0": "Other",
|
308 |
+
"1": "Inflammatory",
|
309 |
+
"2": "Epithelial",
|
310 |
+
"3": "Spindle-Shaped"
|
311 |
+
},
|
312 |
+
"log_dir": "@output_dir",
|
313 |
+
"batch_limit": 8,
|
314 |
+
"tag_name": "val"
|
315 |
+
}
|
316 |
+
],
|
317 |
+
"key_metric": {
|
318 |
+
"val_f1": {
|
319 |
+
"_target_": "ConfusionMatrix",
|
320 |
+
"metric_name": "f1 score",
|
321 |
+
"output_transform": "$monai.handlers.from_engine(['pred', 'label'])"
|
322 |
+
}
|
323 |
+
},
|
324 |
+
"additional_metrics": {
|
325 |
+
"val_accuracy": {
|
326 |
+
"_target_": "ignite.metrics.Accuracy",
|
327 |
+
"output_transform": "$monai.handlers.from_engine(['pred', 'label'])"
|
328 |
+
}
|
329 |
+
},
|
330 |
+
"evaluator": {
|
331 |
+
"_target_": "SupervisedEvaluator",
|
332 |
+
"device": "@device",
|
333 |
+
"val_data_loader": "@validate#dataloader",
|
334 |
+
"network": "@network",
|
335 |
+
"inferer": "@validate#inferer",
|
336 |
+
"postprocessing": "@validate#postprocessing",
|
337 |
+
"key_val_metric": "@validate#key_metric",
|
338 |
+
"additional_metrics": "@validate#additional_metrics",
|
339 |
+
"val_handlers": "@validate#handlers",
|
340 |
+
"amp": true
|
341 |
+
}
|
342 |
+
},
|
343 |
+
"training": [
|
344 |
+
"$import sys",
|
345 |
+
"$sys.path.append(@bundle_root)",
|
346 |
+
"$monai.utils.set_determinism(seed=123)",
|
347 |
+
"$setattr(torch.backends.cudnn, 'benchmark', True)",
|
348 |
+
"$@train#trainer.run()"
|
349 |
+
]
|
350 |
+
}
|
docs/README.md
ADDED
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Description
|
2 |
+
A pre-trained model for classifying nuclei cells as the following types.
|
3 |
+
- Other
|
4 |
+
- Inflammatory
|
5 |
+
- Epithelial
|
6 |
+
- Spindle-Shaped
|
7 |
+
|
8 |
+
# Model Overview
|
9 |
+
This model is trained using [DenseNet121](https://docs.monai.io/en/latest/networks.html#densenet121) over [ConSeP](https://warwick.ac.uk/fac/cross_fac/tia/data/hovernet) dataset.
|
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: torch.nn.CrossEntropyLoss
|
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 |
+
```commandline
|
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` in output folder:
|
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: 4 channels
|
90 |
+
- 3 RGB channels
|
91 |
+
- 1 signal channel (label mask)
|
92 |
+
|
93 |
+
### Output: 4 channels
|
94 |
+
- 0 = Other
|
95 |
+
- 1 = Inflammatory
|
96 |
+
- 2 = Epithelial
|
97 |
+
- 3 = Spindle-Shaped
|
98 |
+
|
99 |
+
![](images/val_in_out.jpeg)
|
100 |
+
|
101 |
+
## Scores
|
102 |
+
This model achieves the following F1 score on the validation data provided as part of the dataset:
|
103 |
+
|
104 |
+
- Train F1 score = 0.96
|
105 |
+
- Validation F1 score = 0.85
|
106 |
+
|
107 |
+
<hr/>
|
108 |
+
Confusion Metrics for <b>Validation</b> for individual classes are (at epoch 50):
|
109 |
+
|
110 |
+
| Metric | Other | Inflammatory | Epithelial | Spindle-Shaped |
|
111 |
+
|-----------|--------|--------------|------------|----------------|
|
112 |
+
| Precision | 0.5846 | 0.7143 | 0.9158 | 0.8399 |
|
113 |
+
| Recall | 0.2550 | 0.8441 | 0.9193 | 0.8106 |
|
114 |
+
| F1-score | 0.3551 | 0.7738 | 0.9175 | 0.8250 |
|
115 |
+
|
116 |
+
|
117 |
+
<hr/>
|
118 |
+
Confusion Metrics for <b>Training</b> for individual classes are (at epoch 50):
|
119 |
+
|
120 |
+
| Metric | Other | Inflammatory | Epithelial | Spindle-Shaped |
|
121 |
+
|-----------|--------|--------------|------------|----------------|
|
122 |
+
| Precision | 0.9059 | 0.9569 | 0.9754 | 0.9494 |
|
123 |
+
| Recall | 0.8370 | 0.9547 | 0.9790 | 0.9502 |
|
124 |
+
| F1-score | 0.8701 | 0.9558 | 0.9772 | 0.9498 |
|
125 |
+
|
126 |
+
|
127 |
+
|
128 |
+
## Training Performance
|
129 |
+
A graph showing the training Loss and F1-score over 50 epochs.
|
130 |
+
|
131 |
+
![](images/train_loss.jpeg) <br>
|
132 |
+
![](images/train_f1.jpeg) <br>
|
133 |
+
|
134 |
+
## Validation Performance
|
135 |
+
A graph showing the validation F1-score over 50 epochs.
|
136 |
+
|
137 |
+
![](images/val_f1.jpeg) <br>
|
138 |
+
|
139 |
+
|
140 |
+
## commands example
|
141 |
+
Execute training:
|
142 |
+
|
143 |
+
```
|
144 |
+
python -m monai.bundle run training --meta_file configs/metadata.json --config_file configs/train.json --logging_file configs/logging.conf
|
145 |
+
```
|
146 |
+
|
147 |
+
Override the `train` config to execute multi-GPU training:
|
148 |
+
|
149 |
+
```
|
150 |
+
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
|
151 |
+
```
|
152 |
+
|
153 |
+
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.
|
154 |
+
Please refer to [pytorch's official tutorial](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html) for more details.
|
155 |
+
|
156 |
+
Override the `train` config to execute evaluation with the trained model:
|
157 |
+
|
158 |
+
```
|
159 |
+
python -m monai.bundle run evaluating --meta_file configs/metadata.json --config_file "['configs/train.json','configs/evaluate.json']" --logging_file configs/logging.conf
|
160 |
+
```
|
161 |
+
|
162 |
+
Override the `train` config and `evaluate` config to execute multi-GPU evaluation:
|
163 |
+
|
164 |
+
```
|
165 |
+
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
|
166 |
+
```
|
167 |
+
|
168 |
+
Execute inference:
|
169 |
+
|
170 |
+
```
|
171 |
+
python -m monai.bundle run evaluating --meta_file configs/metadata.json --config_file configs/inference.json --logging_file configs/logging.conf
|
172 |
+
```
|
173 |
+
|
174 |
+
# Disclaimer
|
175 |
+
This is an example, not to be used for diagnostic purposes.
|
176 |
+
|
177 |
+
# References
|
178 |
+
[1] S. Graham, Q. D. Vu, S. E. A. Raza, A. Azam, Y-W. Tsang, J. T. Kwak and N. Rajpoot. "HoVer-Net: Simultaneous Segmentation and Classification of Nuclei in Multi-Tissue Histology Images." Medical Image Analysis, Sept. 2019. [[doi](https://doi.org/10.1016/j.media.2019.101563)]
|
179 |
+
|
180 |
+
# License
|
181 |
+
Copyright (c) MONAI Consortium
|
182 |
+
|
183 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
184 |
+
you may not use this file except in compliance with the License.
|
185 |
+
You may obtain a copy of the License at
|
186 |
+
|
187 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
188 |
+
|
189 |
+
Unless required by applicable law or agreed to in writing, software
|
190 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
191 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
192 |
+
See the License for the specific language governing permissions and
|
193 |
+
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_f1.jpeg
ADDED
docs/images/train_loss.jpeg
ADDED
docs/images/val_f1.jpeg
ADDED
docs/images/val_in_out.jpeg
ADDED
models/model.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f254ae6b0318e1375d48c1e9d6056d236d4a1a32957afc4aeafba0e047c46b2b
|
3 |
+
size 28419489
|
models/model.ts
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a3d6a7da0c74a470cb2e9cbd72c5783ec0f2c7ed120cc6dfada30338b73637dd
|
3 |
+
size 28575181
|
scripts/__init__.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
13 |
+
from .writer import ClassificationWriter
|
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,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, Any, Callable, List, 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 |
+
from sklearn.metrics import classification_report
|
21 |
+
|
22 |
+
Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events")
|
23 |
+
make_grid, _ = optional_import("torchvision.utils", name="make_grid")
|
24 |
+
Image, _ = optional_import("PIL.Image")
|
25 |
+
ImageDraw, _ = optional_import("PIL.ImageDraw")
|
26 |
+
|
27 |
+
if TYPE_CHECKING:
|
28 |
+
from ignite.engine import Engine
|
29 |
+
from torch.utils.tensorboard import SummaryWriter
|
30 |
+
else:
|
31 |
+
Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine")
|
32 |
+
SummaryWriter, _ = optional_import("torch.utils.tensorboard", name="SummaryWriter")
|
33 |
+
|
34 |
+
|
35 |
+
class TensorBoardImageHandler:
|
36 |
+
def __init__(
|
37 |
+
self,
|
38 |
+
class_names,
|
39 |
+
summary_writer: Optional[SummaryWriter] = None,
|
40 |
+
log_dir: str = "./runs",
|
41 |
+
tag_name="val",
|
42 |
+
interval: int = 1,
|
43 |
+
batch_transform: Callable = lambda x: x,
|
44 |
+
output_transform: Callable = lambda x: x,
|
45 |
+
batch_limit=1,
|
46 |
+
device=None,
|
47 |
+
) -> None:
|
48 |
+
self.class_names = class_names
|
49 |
+
self.writer = SummaryWriter(log_dir=log_dir) if summary_writer is None else summary_writer
|
50 |
+
self.tag_name = tag_name
|
51 |
+
self.interval = interval
|
52 |
+
self.batch_transform = batch_transform
|
53 |
+
self.output_transform = output_transform
|
54 |
+
self.batch_limit = batch_limit
|
55 |
+
self.device = device
|
56 |
+
|
57 |
+
self.logger = logging.getLogger(__name__)
|
58 |
+
|
59 |
+
if torch.distributed.is_initialized():
|
60 |
+
self.tag_name = f"{self.tag_name}-r{torch.distributed.get_rank()}"
|
61 |
+
self.class_y: List[Any] = []
|
62 |
+
self.class_y_pred: List[Any] = []
|
63 |
+
|
64 |
+
def attach(self, engine: Engine) -> None:
|
65 |
+
if self.interval == 1:
|
66 |
+
engine.add_event_handler(Events.ITERATION_COMPLETED(every=self.interval), self, "iteration")
|
67 |
+
engine.add_event_handler(Events.EPOCH_COMPLETED(every=self.interval), self, "epoch")
|
68 |
+
|
69 |
+
def __call__(self, engine: Engine, action) -> None:
|
70 |
+
epoch = engine.state.epoch
|
71 |
+
batch_data = self.batch_transform(engine.state.batch)
|
72 |
+
output_data = self.output_transform(engine.state.output)
|
73 |
+
|
74 |
+
if action == "iteration":
|
75 |
+
for bidx in range(len(batch_data)):
|
76 |
+
y = output_data[bidx]["label"].detach().cpu().numpy()
|
77 |
+
y_pred = output_data[bidx]["pred"].detach().cpu().numpy()
|
78 |
+
|
79 |
+
self.class_y.append(np.argmax(y))
|
80 |
+
self.class_y_pred.append(np.argmax(y_pred))
|
81 |
+
return
|
82 |
+
|
83 |
+
self.write_metrics(epoch)
|
84 |
+
self.write_images(batch_data, output_data, epoch)
|
85 |
+
self.writer.flush()
|
86 |
+
|
87 |
+
def write_images(self, batch_data, output_data, epoch):
|
88 |
+
for bidx in range(len(batch_data)):
|
89 |
+
image = batch_data[bidx]["image"].detach().cpu().numpy()
|
90 |
+
y = output_data[bidx]["label"].detach().cpu().numpy()
|
91 |
+
y_pred = output_data[bidx]["pred"].detach().cpu().numpy()
|
92 |
+
|
93 |
+
sig_np = image[:3] * 128 + 128
|
94 |
+
sig_np[0, :, :] = np.where(image[3] > 0, 1, sig_np[0, :, :])
|
95 |
+
|
96 |
+
y_c = np.argmax(y)
|
97 |
+
y_pred_c = np.argmax(y_pred)
|
98 |
+
|
99 |
+
tag_prefix = f"{self.tag_name} - b{bidx} - " if self.batch_limit != 1 else f"{self.tag_name} - "
|
100 |
+
label_pred_tag = f"{tag_prefix}Image/Signal/Label/Pred:"
|
101 |
+
|
102 |
+
y_img = Image.new("RGB", image.shape[-2:])
|
103 |
+
draw = ImageDraw.Draw(y_img)
|
104 |
+
draw.text((10, 50), self.class_names.get(f"{y_c}", f"{y_c}"))
|
105 |
+
|
106 |
+
y_pred_img = Image.new("RGB", image.shape[-2:], "green" if y_c == y_pred_c else "red")
|
107 |
+
draw = ImageDraw.Draw(y_pred_img)
|
108 |
+
draw.text((10, 50), self.class_names.get(f"{y_pred_c}", f"{y_pred_c}"))
|
109 |
+
|
110 |
+
img_tensor = make_grid(
|
111 |
+
tensor=[
|
112 |
+
torch.from_numpy(sig_np),
|
113 |
+
torch.from_numpy(np.stack((np.where(image[3] > 0, 255, 0),) * 3)),
|
114 |
+
torch.from_numpy(np.moveaxis(np.array(y_img), -1, 0)),
|
115 |
+
torch.from_numpy(np.moveaxis(np.array(y_pred_img), -1, 0)),
|
116 |
+
],
|
117 |
+
nrow=4,
|
118 |
+
normalize=True,
|
119 |
+
pad_value=10,
|
120 |
+
)
|
121 |
+
self.writer.add_image(tag=label_pred_tag, img_tensor=img_tensor, global_step=epoch)
|
122 |
+
|
123 |
+
if self.batch_limit == 1 or bidx == (self.batch_limit - 1):
|
124 |
+
break
|
125 |
+
|
126 |
+
def write_metrics(self, epoch):
|
127 |
+
cr = classification_report(self.class_y, self.class_y_pred, output_dict=True, zero_division=0)
|
128 |
+
for k, v in cr.items():
|
129 |
+
if isinstance(v, dict):
|
130 |
+
ltext = []
|
131 |
+
cname = self.class_names.get(k, k)
|
132 |
+
for n, m in v.items():
|
133 |
+
ltext.append(f"{n} => {m:.4f}")
|
134 |
+
self.writer.add_scalar(f"{self.tag_name}_cr_{cname}_{n}", m, epoch)
|
135 |
+
|
136 |
+
self.logger.info(f"{self.tag_name} => Epoch[{epoch}] - {cname} - Metrics -- {'; '.join(ltext)}")
|
137 |
+
else:
|
138 |
+
self.logger.info(f"{self.tag_name} => Epoch[{epoch}] Metrics -- {k} => {v:.4f}")
|
139 |
+
self.writer.add_scalar(f"{self.tag_name}_cr_{k}", v, epoch)
|
140 |
+
|
141 |
+
self.class_y = []
|
142 |
+
self.class_y_pred = []
|
scripts/writer.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 json
|
12 |
+
import logging
|
13 |
+
from typing import Dict, Mapping, Optional
|
14 |
+
|
15 |
+
import numpy as np
|
16 |
+
from monai.config import NdarrayOrTensor, PathLike
|
17 |
+
from monai.data import ImageWriter
|
18 |
+
|
19 |
+
logger = logging.getLogger(__name__)
|
20 |
+
|
21 |
+
|
22 |
+
class ClassificationWriter(ImageWriter):
|
23 |
+
def __init__(self, label_index_map: Optional[Dict[str, str]] = None, **kwargs):
|
24 |
+
super().__init__(**kwargs)
|
25 |
+
self.label_index_map = (
|
26 |
+
label_index_map
|
27 |
+
if label_index_map
|
28 |
+
else {"0": "Other", "1": "Inflammatory", "2": "Epithelial", "3": "Spindle-Shaped"}
|
29 |
+
)
|
30 |
+
|
31 |
+
def set_data_array(
|
32 |
+
self,
|
33 |
+
data_array: NdarrayOrTensor,
|
34 |
+
channel_dim: Optional[int] = 0,
|
35 |
+
squeeze_end_dims: bool = True,
|
36 |
+
contiguous: bool = False,
|
37 |
+
**kwargs,
|
38 |
+
):
|
39 |
+
self.data_obj: np.ndarray = super().create_backend_obj(data_array)
|
40 |
+
|
41 |
+
def set_metadata(self, meta_dict: Optional[Mapping] = None, resample: bool = True, **options):
|
42 |
+
pass
|
43 |
+
|
44 |
+
def write(self, filename: PathLike, verbose: bool = False, **kwargs):
|
45 |
+
super().write(filename, verbose=verbose)
|
46 |
+
result = []
|
47 |
+
for idx, score in enumerate(self.data_obj):
|
48 |
+
name = f"label_{idx}"
|
49 |
+
name = self.label_index_map.get(str(idx)) if self.label_index_map else name
|
50 |
+
if name:
|
51 |
+
result.append({"idx": idx, "label": name, "score": float(score)})
|
52 |
+
|
53 |
+
with open(filename, "w") as fp:
|
54 |
+
json.dump(result, fp)
|