Ole-Christian Galbo Engstrøm
commited on
Commit
·
42935f4
1
Parent(s):
50d9fe1
Adding files and setting up Git LFS for images
Browse files
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
*.png 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 2025 Ole-Christian Galbo Engstrøm
|
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
CHANGED
@@ -1,3 +1,70 @@
|
|
1 |
---
|
2 |
license: apache-2.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
---
|
2 |
license: apache-2.0
|
3 |
+
tags:
|
4 |
+
- computer-vision
|
5 |
+
- image-segmentation
|
6 |
+
- pytorch
|
7 |
+
- unet
|
8 |
+
- medical-imaging
|
9 |
+
- semantic-segmentation
|
10 |
+
library_name: pytorch
|
11 |
+
pipeline_tag: image-segmentation
|
12 |
---
|
13 |
+
|
14 |
+
# U-Net
|
15 |
+
This repository contains an implementation of U-Net [[1]](#references). [unet.py](./unet.py) implements the class UNet. The implementation has been tested with PyTorch 2.7.1 and CUDA 12.6.
|
16 |
+

|
17 |
+
|
18 |
+
You can also load the U-Net from PyTorch Hub.
|
19 |
+
```python
|
20 |
+
import torch
|
21 |
+
|
22 |
+
# These are the default parameters. They are written out for clarity. Currently no pretrained weights are available.
|
23 |
+
model = torch.hub.load('sm00thix/unet', 'unet', pretrained=False, in_channels=3, out_channels=1, pad=True, bilinear=True, normalization=None)
|
24 |
+
# or
|
25 |
+
# model = torch.hub.load('sm00thix/unet', 'unet_bn', **kwargs) # Convenience function equivalent to torch.hub.load('sm00thix/unet', 'unet', normalization='bn', **kwargs)
|
26 |
+
# or
|
27 |
+
# model = torch.hub.load('sm00thix/unet', 'unet_ln', **kwargs) # Convenience function equivalent to torch.hub.load('sm00thix/unet', 'unet', normalization='ln', **kwargs)
|
28 |
+
# or
|
29 |
+
# model = torch.hub.load('sm00thix/unet', 'unet_medical', **kwargs) # Convenience function equivalent to torch.hub.load('sm00thix/unet', 'unet', in_channels=1, out_channels=1, **kwargs)
|
30 |
+
# or
|
31 |
+
# model = torch.hub.load('sm00thix/unet', 'unet_transconv', **kwargs) # Convenience function equivalent to torch.hub.load('sm00thix/unet', 'unet', bilinear=False, **kwargs)
|
32 |
+
```
|
33 |
+
|
34 |
+
## Options
|
35 |
+
The UNet class provides the following options for customization.
|
36 |
+
|
37 |
+
1. Number of input and output channels
|
38 |
+
`in_channels` is the number of channels in the input image.
|
39 |
+
`out_channels` is the number of channels in the output image.
|
40 |
+
2. Upsampling
|
41 |
+
1. `bilinear = False`: Transposed convolution with a 2x2 kernel applied with stride 2. This is followed by a ReLU.
|
42 |
+
2. `bilinear = True`: Factor 2 bilinear upsampling followed by convolution with a 1x1 kernel applied with stride 1.
|
43 |
+
3. Padding
|
44 |
+
1. `pad = True`: The input size is retained in the output by zero-padding convolutions and, if necessary, the results of the upsampling operations.
|
45 |
+
2. `pad = False`: The output is smaller than the input as in the original implementation. In this case, every 3x3 convolution layer reduces the height and width by 2 pixels each. Consequently, the right side of the U-Net has a smaller spatial size than the left size. Therefore, before concatenating, the central slice of the left tensor is cropped along the spatial dimensions to match those of the right tensor.
|
46 |
+
4. Normalization following the ReLU which follows each convolution and transposed convolution.
|
47 |
+
1. `normalization = None`: Applies no normalization.
|
48 |
+
2. `normalization = "bn"`: Applies batch normalization [[2]](#references).
|
49 |
+
3. `normalization = "ln"`: Applies layer normalization [[3]](#references). A permutation of dimensions is performed before the layer to ensure normalization is applied over the channel dimension. Afterward, the dimensions are permuted back to their original order.
|
50 |
+
|
51 |
+
In particular, setting bilinear = False, pad = False, and normalization = None will yield the U-Net as originally designed. Generally, however, bilinear = True is recommended to avoid checkerboard artifacts.
|
52 |
+
|
53 |
+
As in the original implementation, all weights are initialized by sampling from a Kaiming He Normal Distribution [[4]](#references), and all biases are initialized to zero. If Batch Normalization or Layer Normalization is used, the weights of those layers are initialized to one and their biases to zero.
|
54 |
+
|
55 |
+
If you use this U-Net implementation, please cite Engstrøm et al. [[5]](#references) who developed this implementation as part of their work on chemical map geenration of fat content in images of pork bellies.
|
56 |
+
|
57 |
+
## Citation
|
58 |
+
If you use the code shared in this repository, please cite this work: https://arxiv.org/abs/2504.14131. The U-Net implementation in this repository was used to generate pixel-wise fat predictions in an image of a pork belly.
|
59 |
+

|
60 |
+
|
61 |
+
## References
|
62 |
+
|
63 |
+
1. [O. Ronneberger, P. Fischer, and Thomas Brox (2015). U-Net: Convolutional Networks for Biomedical Image Segmentation. *MICCAI 2015*.](https://arxiv.org/abs/1505.04597)
|
64 |
+
2. [S. Ioffe and C. Szegedy (2015). Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift. *ICML 2015*.](https://arxiv.org/abs/1502.03167)
|
65 |
+
3. [J. L. Ba and J. R. Kiros and G. E. Hinton (2016). Layer Normalization.](https://arxiv.org/abs/1607.06450)
|
66 |
+
4. [K. He and X. Zhang and S. Ren and J. Sun (2015). Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification.](https://openaccess.thecvf.com/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html)
|
67 |
+
5. [O.-C. G. Engstrøm and M. Albano-Gaglio and E. S. Dreier and Y. Bouzembrak and M. Font-i-Furnols and P. Mishra and K. S. Pedersen (2025). Transforming Hyperspectral Images Into Chemical Maps: A Novel End-to-End Deep Learning Approach.](https://arxiv.org/abs/2504.14131)
|
68 |
+
|
69 |
+
## Funding
|
70 |
+
This work has been carried out as part of an industrial Ph. D. project receiving funding from [FOSS Analytical A/S](https://www.fossanalytics.com/) and [The Innovation Fund Denmark](https://innovationsfonden.dk/en). Grant number 1044-00108B.
|
unet.py
ADDED
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Contains an implementation of the U-Net architecture.
|
3 |
+
U-Net paper by Ronneberger et al. (2015): https://arxiv.org/abs/1505.04597
|
4 |
+
|
5 |
+
This implementation is based on the original U-Net architecture, with options for
|
6 |
+
normalization (batch normalization or layer normalization), bilinear upsampling,
|
7 |
+
and padding in the convolution layers.
|
8 |
+
|
9 |
+
Author: Ole-Christian Galbo Engstrøm
|
10 |
+
E-mail: [email protected]
|
11 |
+
"""
|
12 |
+
|
13 |
+
from typing import Iterable
|
14 |
+
|
15 |
+
import torch
|
16 |
+
from torch import nn
|
17 |
+
from torch.nn import functional as F
|
18 |
+
|
19 |
+
|
20 |
+
def conv3x3(in_channels: int, out_channels: int, bias: bool, pad: bool) -> nn.Conv2d:
|
21 |
+
"""
|
22 |
+
Applies a convolution with a 3x3 kernel.
|
23 |
+
"""
|
24 |
+
if pad:
|
25 |
+
padding = 1
|
26 |
+
else:
|
27 |
+
padding = "valid"
|
28 |
+
layer = nn.Conv2d(
|
29 |
+
in_channels,
|
30 |
+
out_channels,
|
31 |
+
kernel_size=3,
|
32 |
+
padding=padding,
|
33 |
+
bias=bias,
|
34 |
+
)
|
35 |
+
return layer
|
36 |
+
|
37 |
+
|
38 |
+
def conv_block(
|
39 |
+
in_channels: int,
|
40 |
+
out_channels: int,
|
41 |
+
non_linearity: nn.Module,
|
42 |
+
normalization: None | str,
|
43 |
+
bias: bool,
|
44 |
+
pad: bool,
|
45 |
+
) -> nn.Sequential:
|
46 |
+
"""
|
47 |
+
A block of two convolutional layers, each followed by a non-linearity
|
48 |
+
and optionally a normalization layer.
|
49 |
+
|
50 |
+
In the U-Net architecture illustration in the U-Net paper,
|
51 |
+
this corresponds to two blue arrows.
|
52 |
+
"""
|
53 |
+
layers = []
|
54 |
+
for _ in range(2):
|
55 |
+
layers.append(
|
56 |
+
conv3x3(
|
57 |
+
in_channels=in_channels, out_channels=out_channels, bias=bias, pad=pad
|
58 |
+
)
|
59 |
+
)
|
60 |
+
layers.append(non_linearity)
|
61 |
+
layers.append(
|
62 |
+
get_norm_layer(normalization=normalization, in_channels=out_channels)
|
63 |
+
)
|
64 |
+
in_channels = out_channels
|
65 |
+
return nn.Sequential(*layers)
|
66 |
+
|
67 |
+
|
68 |
+
def batch_norm(in_channels: int) -> nn.Sequential:
|
69 |
+
"""
|
70 |
+
Apply Batch Normalization over the channel dimension.
|
71 |
+
Batch Normalization paper by Ioffe and Szegedy (2015): https://arxiv.org/abs/1502.03167
|
72 |
+
"""
|
73 |
+
return nn.BatchNorm2d(in_channels, momentum=0.01)
|
74 |
+
|
75 |
+
|
76 |
+
class Permute(nn.Module):
|
77 |
+
"""
|
78 |
+
Permute the dimensions of a tensor.
|
79 |
+
"""
|
80 |
+
|
81 |
+
def __init__(self, dims: Iterable[int]):
|
82 |
+
super().__init__()
|
83 |
+
self.dims = dims
|
84 |
+
|
85 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
86 |
+
return x.permute(self.dims)
|
87 |
+
|
88 |
+
def __repr__(self):
|
89 |
+
return f'{self.__class__.__name__}({", ".join(map(str, self.dims))})'
|
90 |
+
|
91 |
+
|
92 |
+
def layer_norm(in_channels: int) -> nn.Sequential:
|
93 |
+
"""
|
94 |
+
Apply Layer Normalization over the channel dimension.
|
95 |
+
Layer Normalization paper by Ba et al. (2016): https://arxiv.org/abs/1607.06450
|
96 |
+
"""
|
97 |
+
layers = [
|
98 |
+
# (B, C, H, W) -> (B, H, W, C)
|
99 |
+
Permute((0, 2, 3, 1)),
|
100 |
+
# LayerNorm expects the last dimension to be the feature dimension
|
101 |
+
# (we want the normalized shape to be (C,))
|
102 |
+
nn.LayerNorm(in_channels),
|
103 |
+
# (B, H, W, C) -> (B, C, H, W)
|
104 |
+
Permute((0, 3, 1, 2)),
|
105 |
+
]
|
106 |
+
return nn.Sequential(*layers)
|
107 |
+
|
108 |
+
|
109 |
+
def get_norm_layer(normalization: None | str, in_channels: int) -> nn.Module:
|
110 |
+
"""
|
111 |
+
Get the normalization layer based on the specified type.
|
112 |
+
Either 'bn' for batch normalization, 'ln' for layer normalization,
|
113 |
+
or None for no normalization layer.
|
114 |
+
"""
|
115 |
+
if normalization == "bn":
|
116 |
+
return batch_norm(in_channels)
|
117 |
+
if normalization == "ln":
|
118 |
+
return layer_norm(in_channels)
|
119 |
+
return nn.Identity()
|
120 |
+
|
121 |
+
|
122 |
+
def copy_and_crop(large: torch.Tensor, small: torch.Tensor) -> torch.Tensor:
|
123 |
+
"""
|
124 |
+
Implementation of a copy-and-crop block in the U-Net architecture.
|
125 |
+
Copy the large image and crop it to the size of the small image.
|
126 |
+
The large image is cropped in the middle, and then the two images are
|
127 |
+
concatenated along the channel dimension.
|
128 |
+
|
129 |
+
In the U-Net architecture illustration in the U-Net paper,
|
130 |
+
this corresponds to a gray arrow.
|
131 |
+
"""
|
132 |
+
large_height, large_width = large.shape[-2:]
|
133 |
+
small_height, small_width = small.shape[-2:]
|
134 |
+
start_x = (large_height - small_height) // 2
|
135 |
+
start_y = (large_width - small_width) // 2
|
136 |
+
cropped_large = large[
|
137 |
+
..., start_x : start_x + small_height, start_y : start_y + small_width
|
138 |
+
]
|
139 |
+
return torch.cat([cropped_large, small], dim=-3)
|
140 |
+
|
141 |
+
|
142 |
+
class ContractionBlock(nn.Module):
|
143 |
+
"""
|
144 |
+
Implementation of a contraction block in the U-Net architecture.
|
145 |
+
This block consists of a max pooling layer followed by a convolution block.
|
146 |
+
|
147 |
+
In the U-Net architecture illustration in the U-Net paper, this corresponds to
|
148 |
+
one red arrow followed by the subsequent two blue arrows.
|
149 |
+
"""
|
150 |
+
|
151 |
+
def __init__(
|
152 |
+
self,
|
153 |
+
in_channels: int,
|
154 |
+
out_channels: int,
|
155 |
+
non_linearity: nn.Module,
|
156 |
+
nonormalization: None | str,
|
157 |
+
bias: bool,
|
158 |
+
pad: bool,
|
159 |
+
):
|
160 |
+
super().__init__()
|
161 |
+
self.max_pool = self._max_pool()
|
162 |
+
self.conv_block = conv_block(
|
163 |
+
in_channels=in_channels,
|
164 |
+
out_channels=out_channels,
|
165 |
+
non_linearity=non_linearity,
|
166 |
+
normalization=nonormalization,
|
167 |
+
bias=bias,
|
168 |
+
pad=pad,
|
169 |
+
)
|
170 |
+
|
171 |
+
def _max_pool(self) -> nn.MaxPool2d:
|
172 |
+
layer = nn.MaxPool2d(kernel_size=2, stride=2)
|
173 |
+
return layer
|
174 |
+
|
175 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
176 |
+
x = self.max_pool(x)
|
177 |
+
x = self.conv_block(x)
|
178 |
+
return x
|
179 |
+
|
180 |
+
|
181 |
+
class Upsample(nn.Module):
|
182 |
+
"""
|
183 |
+
Implementation of an upsampling block in the U-Net architecture.
|
184 |
+
This block consists of either a transposed convolution or bilinear upsampling,
|
185 |
+
followed by a convolution block.
|
186 |
+
|
187 |
+
In the U-Net architecture illustration in the U-Net paper, this corresponds to
|
188 |
+
one green arrow.
|
189 |
+
"""
|
190 |
+
|
191 |
+
def __init__(
|
192 |
+
self,
|
193 |
+
in_channels: int,
|
194 |
+
out_channels: int,
|
195 |
+
non_linearity,
|
196 |
+
normalization: None | str,
|
197 |
+
bias: bool,
|
198 |
+
bilinear: bool,
|
199 |
+
):
|
200 |
+
super().__init__()
|
201 |
+
self.in_channels = in_channels
|
202 |
+
self.out_channels = out_channels
|
203 |
+
self.non_linearity = non_linearity
|
204 |
+
self.normalization = normalization
|
205 |
+
self.bias = bias
|
206 |
+
self.bilinear = bilinear
|
207 |
+
self.up = self._upsample(in_channels, out_channels)
|
208 |
+
|
209 |
+
def _upsample(self, in_channels: int, out_channels: int) -> nn.Sequential:
|
210 |
+
if self.bilinear:
|
211 |
+
up = self._up_bilinear(in_channels, out_channels)
|
212 |
+
else:
|
213 |
+
up = self._up_trans_conv2x2(in_channels, out_channels)
|
214 |
+
return up
|
215 |
+
|
216 |
+
def _up_trans_conv2x2(self, in_channels: int, out_channels: int) -> nn.Sequential:
|
217 |
+
layers = [
|
218 |
+
nn.ConvTranspose2d(
|
219 |
+
in_channels, out_channels, kernel_size=2, stride=2, bias=self.bias
|
220 |
+
),
|
221 |
+
self.non_linearity,
|
222 |
+
]
|
223 |
+
layers.append(get_norm_layer(self.normalization, out_channels))
|
224 |
+
return nn.Sequential(*layers)
|
225 |
+
|
226 |
+
def _up_bilinear(self, in_channels: int, out_channels: int) -> nn.Sequential:
|
227 |
+
layers = [
|
228 |
+
nn.Upsample(mode="bilinear", scale_factor=2, align_corners=True),
|
229 |
+
nn.Conv2d(
|
230 |
+
in_channels=in_channels, out_channels=out_channels, kernel_size=1
|
231 |
+
),
|
232 |
+
self.non_linearity,
|
233 |
+
]
|
234 |
+
layers.append(get_norm_layer(self.normalization, out_channels))
|
235 |
+
return nn.Sequential(*layers)
|
236 |
+
|
237 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
238 |
+
return self.up(x)
|
239 |
+
|
240 |
+
|
241 |
+
class ExpansionBlock(nn.Module):
|
242 |
+
"""
|
243 |
+
Implementation of an expansion block in the U-Net architecture.
|
244 |
+
This block consists of an upsampling block followed by a copy-and-crop block and
|
245 |
+
a convolution block.
|
246 |
+
|
247 |
+
In the U-Net architecture illustration in the U-Net paper, this corresponds to
|
248 |
+
one green arrow followed by a gray arrow and then two blue arrows.
|
249 |
+
"""
|
250 |
+
|
251 |
+
def __init__(
|
252 |
+
self,
|
253 |
+
in_channels: int,
|
254 |
+
out_channels: int,
|
255 |
+
non_linearity: nn.Module,
|
256 |
+
normalization: None | str,
|
257 |
+
bias: bool,
|
258 |
+
bilinear: bool,
|
259 |
+
pad: bool,
|
260 |
+
):
|
261 |
+
super().__init__()
|
262 |
+
self.pad = pad
|
263 |
+
self.upsample = Upsample(
|
264 |
+
in_channels=in_channels,
|
265 |
+
out_channels=out_channels,
|
266 |
+
non_linearity=non_linearity,
|
267 |
+
normalization=normalization,
|
268 |
+
bias=bias,
|
269 |
+
bilinear=bilinear,
|
270 |
+
)
|
271 |
+
self.conv_block = self.conv_block = conv_block(
|
272 |
+
in_channels=in_channels,
|
273 |
+
out_channels=out_channels,
|
274 |
+
non_linearity=non_linearity,
|
275 |
+
normalization=normalization,
|
276 |
+
bias=bias,
|
277 |
+
pad=pad,
|
278 |
+
)
|
279 |
+
|
280 |
+
def forward(self, large: torch.Tensor, small: torch.Tensor) -> torch.Tensor:
|
281 |
+
x = self.upsample(small)
|
282 |
+
if self.pad:
|
283 |
+
diff_h = large.shape[-2] - x.shape[-2]
|
284 |
+
diff_w = large.shape[-1] - x.shape[-1]
|
285 |
+
pad_left = diff_w // 2
|
286 |
+
pad_right = diff_w - pad_left
|
287 |
+
pad_top = diff_h // 2
|
288 |
+
pad_bottom = diff_h - pad_top
|
289 |
+
x = F.pad(
|
290 |
+
x,
|
291 |
+
(pad_left, pad_right, pad_top, pad_bottom),
|
292 |
+
mode="constant",
|
293 |
+
value=0.0,
|
294 |
+
)
|
295 |
+
x = copy_and_crop(large, x)
|
296 |
+
x = self.conv_block(x)
|
297 |
+
return x
|
298 |
+
|
299 |
+
|
300 |
+
class UNet(nn.Module):
|
301 |
+
"""
|
302 |
+
in_channels : int\\
|
303 |
+
Number of input channels.
|
304 |
+
|
305 |
+
out_channels : int\\
|
306 |
+
Number of output channels
|
307 |
+
|
308 |
+
pad : bool, default=True\\
|
309 |
+
If True use padding in the convolution layers, preserving the input size.
|
310 |
+
If False, the output size will be reduced compared to the input size.
|
311 |
+
|
312 |
+
bilinear : bool, default=True\\
|
313 |
+
If True use bilinear upsampling.
|
314 |
+
If False use transposed convolution.
|
315 |
+
|
316 |
+
normalization: None | str, default=None\\
|
317 |
+
If None use no normalization.
|
318 |
+
If 'bn' use batch normalization.
|
319 |
+
If 'ln' use layer normalization.
|
320 |
+
"""
|
321 |
+
|
322 |
+
def __init__(
|
323 |
+
self,
|
324 |
+
in_channels: int,
|
325 |
+
out_channels: int,
|
326 |
+
pad: bool = True,
|
327 |
+
bilinear: bool = True,
|
328 |
+
normalization: None | str = None,
|
329 |
+
):
|
330 |
+
super().__init__()
|
331 |
+
self.in_channels = in_channels
|
332 |
+
self.out_channels = out_channels
|
333 |
+
self.pad = pad
|
334 |
+
self.bilinear = bilinear
|
335 |
+
self.normalization = normalization
|
336 |
+
if self.normalization not in [None, "bn", "ln"]:
|
337 |
+
raise ValueError(
|
338 |
+
"Normalization must be None, 'bn' for batch normalization,"
|
339 |
+
"or 'ln' for layer normalization"
|
340 |
+
)
|
341 |
+
# Whether to use bias in the convolution layers
|
342 |
+
# If normalization is used, bias is already included in the normalization layer
|
343 |
+
self.bias_conv = normalization is None
|
344 |
+
self.non_linearity = nn.ReLU(inplace=True)
|
345 |
+
self.intermediate_channels = [64 * 2**i for i in range(5)]
|
346 |
+
self.first_convs = conv_block(
|
347 |
+
in_channels=in_channels,
|
348 |
+
out_channels=self.intermediate_channels[0],
|
349 |
+
non_linearity=self.non_linearity,
|
350 |
+
normalization=self.normalization,
|
351 |
+
bias=self.bias_conv,
|
352 |
+
pad=self.pad,
|
353 |
+
)
|
354 |
+
self.last_conv = nn.Conv2d(
|
355 |
+
self.intermediate_channels[0], out_channels, kernel_size=1
|
356 |
+
)
|
357 |
+
|
358 |
+
self.contraction1 = self._get_contraction_block(
|
359 |
+
in_channels=self.intermediate_channels[0],
|
360 |
+
out_channels=self.intermediate_channels[1],
|
361 |
+
)
|
362 |
+
self.contraction2 = self._get_contraction_block(
|
363 |
+
in_channels=self.intermediate_channels[1],
|
364 |
+
out_channels=self.intermediate_channels[2],
|
365 |
+
)
|
366 |
+
self.contraction3 = self._get_contraction_block(
|
367 |
+
in_channels=self.intermediate_channels[2],
|
368 |
+
out_channels=self.intermediate_channels[3],
|
369 |
+
)
|
370 |
+
self.contraction4 = self._get_contraction_block(
|
371 |
+
in_channels=self.intermediate_channels[3],
|
372 |
+
out_channels=self.intermediate_channels[4],
|
373 |
+
)
|
374 |
+
self.expansion4 = self._get_expansion_block(
|
375 |
+
in_channels=self.intermediate_channels[4],
|
376 |
+
out_channels=self.intermediate_channels[3],
|
377 |
+
)
|
378 |
+
self.expansion3 = self._get_expansion_block(
|
379 |
+
in_channels=self.intermediate_channels[3],
|
380 |
+
out_channels=self.intermediate_channels[2],
|
381 |
+
)
|
382 |
+
self.expansion2 = self._get_expansion_block(
|
383 |
+
in_channels=self.intermediate_channels[2],
|
384 |
+
out_channels=self.intermediate_channels[1],
|
385 |
+
)
|
386 |
+
self.expansion1 = self._get_expansion_block(
|
387 |
+
in_channels=self.intermediate_channels[1],
|
388 |
+
out_channels=self.intermediate_channels[0],
|
389 |
+
)
|
390 |
+
|
391 |
+
# Init weights
|
392 |
+
for m in self.modules():
|
393 |
+
if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d)):
|
394 |
+
nn.init.kaiming_normal_(m.weight)
|
395 |
+
if m.bias is not None:
|
396 |
+
nn.init.constant_(m.bias, 0)
|
397 |
+
elif isinstance(m, (nn.BatchNorm2d, nn.LayerNorm)):
|
398 |
+
nn.init.constant_(m.weight, 1)
|
399 |
+
nn.init.constant_(m.bias, 0)
|
400 |
+
|
401 |
+
def _get_contraction_block(
|
402 |
+
self, in_channels: int, out_channels: int
|
403 |
+
) -> ContractionBlock:
|
404 |
+
return ContractionBlock(
|
405 |
+
in_channels=in_channels,
|
406 |
+
out_channels=out_channels,
|
407 |
+
non_linearity=self.non_linearity,
|
408 |
+
nonormalization=self.normalization,
|
409 |
+
bias=self.bias_conv,
|
410 |
+
pad=self.pad,
|
411 |
+
)
|
412 |
+
|
413 |
+
def _get_expansion_block(
|
414 |
+
self, in_channels: int, out_channels: int
|
415 |
+
) -> ExpansionBlock:
|
416 |
+
return ExpansionBlock(
|
417 |
+
in_channels=in_channels,
|
418 |
+
out_channels=out_channels,
|
419 |
+
non_linearity=self.non_linearity,
|
420 |
+
normalization=self.normalization,
|
421 |
+
bias=self.bias_conv,
|
422 |
+
bilinear=self.bilinear,
|
423 |
+
pad=self.pad,
|
424 |
+
)
|
425 |
+
|
426 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
427 |
+
x1 = self.first_convs(x)
|
428 |
+
x2 = self.contraction1(x1)
|
429 |
+
x3 = self.contraction2(x2)
|
430 |
+
x4 = self.contraction3(x3)
|
431 |
+
x5 = self.contraction4(x4)
|
432 |
+
x = self.expansion4(x4, x5)
|
433 |
+
x = self.expansion3(x3, x)
|
434 |
+
x = self.expansion2(x2, x)
|
435 |
+
x = self.expansion1(x1, x)
|
436 |
+
x = self.last_conv(x)
|
437 |
+
return x
|