PixMClass 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- PixMClass-0.1.0/LICENSE.txt +174 -0
- PixMClass-0.1.0/PKG-INFO +32 -0
- PixMClass-0.1.0/PixMClass.egg-info/PKG-INFO +32 -0
- PixMClass-0.1.0/PixMClass.egg-info/SOURCES.txt +14 -0
- PixMClass-0.1.0/PixMClass.egg-info/dependency_links.txt +1 -0
- PixMClass-0.1.0/PixMClass.egg-info/requires.txt +5 -0
- PixMClass-0.1.0/PixMClass.egg-info/top_level.txt +1 -0
- PixMClass-0.1.0/README.md +8 -0
- PixMClass-0.1.0/pix_mclass/__init__.py +3 -0
- PixMClass-0.1.0/pix_mclass/callbacks.py +68 -0
- PixMClass-0.1.0/pix_mclass/losses.py +55 -0
- PixMClass-0.1.0/pix_mclass/training.py +75 -0
- PixMClass-0.1.0/pix_mclass/unet.py +92 -0
- PixMClass-0.1.0/pix_mclass/utils.py +17 -0
- PixMClass-0.1.0/setup.cfg +4 -0
- PixMClass-0.1.0/setup.py +28 -0
|
@@ -0,0 +1,174 @@
|
|
|
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.
|
PixMClass-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: PixMClass
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Multiclass pixel classification
|
|
5
|
+
Home-page: https://github.com/jeanollion/pix_mclass
|
|
6
|
+
Download-URL: https://github.com/jeanollion/pix_mclass/releases/download/v0.1.0/pix_mclass-0.1.0.tar.gz
|
|
7
|
+
Author: Jean Ollion
|
|
8
|
+
Author-email: jean.ollion@polytechnique.org
|
|
9
|
+
Keywords: Segmentation,Classification,Microscopy,Cell
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Image Processing
|
|
14
|
+
Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Requires-Python: >=3
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE.txt
|
|
19
|
+
Requires-Dist: numpy
|
|
20
|
+
Requires-Dist: scipy
|
|
21
|
+
Requires-Dist: tensorflow>=2.7.1
|
|
22
|
+
Requires-Dist: dataset_iterator>=0.4.0
|
|
23
|
+
Requires-Dist: elasticdeform
|
|
24
|
+
|
|
25
|
+
# Multiclass pixel classifier
|
|
26
|
+
Deep learning segmentation method with very low annotation requirement.
|
|
27
|
+
|
|
28
|
+
Similar to [Ilastik pixel classification](https://www.ilastik.org/documentation/pixelclassification/pixelclassification) procedure, but based on a deep neural network.
|
|
29
|
+
|
|
30
|
+
Described and used in the work [Near-infrared co-illumination of fluorescent proteins reduces photobleaching and phototoxicity](https://doi.org/10.1038/s41587-023-01893-7). Please cite this work when using this method.
|
|
31
|
+
|
|
32
|
+
Docuementation: see this [tutorial](https://github.com/jeanollion/bacmman/wiki/Train-and-use-PixMClass)
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: PixMClass
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Multiclass pixel classification
|
|
5
|
+
Home-page: https://github.com/jeanollion/pix_mclass
|
|
6
|
+
Download-URL: https://github.com/jeanollion/pix_mclass/releases/download/v0.1.0/pix_mclass-0.1.0.tar.gz
|
|
7
|
+
Author: Jean Ollion
|
|
8
|
+
Author-email: jean.ollion@polytechnique.org
|
|
9
|
+
Keywords: Segmentation,Classification,Microscopy,Cell
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Image Processing
|
|
14
|
+
Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Requires-Python: >=3
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE.txt
|
|
19
|
+
Requires-Dist: numpy
|
|
20
|
+
Requires-Dist: scipy
|
|
21
|
+
Requires-Dist: tensorflow>=2.7.1
|
|
22
|
+
Requires-Dist: dataset_iterator>=0.4.0
|
|
23
|
+
Requires-Dist: elasticdeform
|
|
24
|
+
|
|
25
|
+
# Multiclass pixel classifier
|
|
26
|
+
Deep learning segmentation method with very low annotation requirement.
|
|
27
|
+
|
|
28
|
+
Similar to [Ilastik pixel classification](https://www.ilastik.org/documentation/pixelclassification/pixelclassification) procedure, but based on a deep neural network.
|
|
29
|
+
|
|
30
|
+
Described and used in the work [Near-infrared co-illumination of fluorescent proteins reduces photobleaching and phototoxicity](https://doi.org/10.1038/s41587-023-01893-7). Please cite this work when using this method.
|
|
31
|
+
|
|
32
|
+
Docuementation: see this [tutorial](https://github.com/jeanollion/bacmman/wiki/Train-and-use-PixMClass)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
LICENSE.txt
|
|
2
|
+
README.md
|
|
3
|
+
setup.py
|
|
4
|
+
PixMClass.egg-info/PKG-INFO
|
|
5
|
+
PixMClass.egg-info/SOURCES.txt
|
|
6
|
+
PixMClass.egg-info/dependency_links.txt
|
|
7
|
+
PixMClass.egg-info/requires.txt
|
|
8
|
+
PixMClass.egg-info/top_level.txt
|
|
9
|
+
pix_mclass/__init__.py
|
|
10
|
+
pix_mclass/callbacks.py
|
|
11
|
+
pix_mclass/losses.py
|
|
12
|
+
pix_mclass/training.py
|
|
13
|
+
pix_mclass/unet.py
|
|
14
|
+
pix_mclass/utils.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pix_mclass
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Multiclass pixel classifier
|
|
2
|
+
Deep learning segmentation method with very low annotation requirement.
|
|
3
|
+
|
|
4
|
+
Similar to [Ilastik pixel classification](https://www.ilastik.org/documentation/pixelclassification/pixelclassification) procedure, but based on a deep neural network.
|
|
5
|
+
|
|
6
|
+
Described and used in the work [Near-infrared co-illumination of fluorescent proteins reduces photobleaching and phototoxicity](https://doi.org/10.1038/s41587-023-01893-7). Please cite this work when using this method.
|
|
7
|
+
|
|
8
|
+
Docuementation: see this [tutorial](https://github.com/jeanollion/bacmman/wiki/Train-and-use-PixMClass)
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
from math import cos, pi
|
|
2
|
+
from tensorflow.keras.callbacks import Callback
|
|
3
|
+
from tensorflow.keras import backend
|
|
4
|
+
import csv
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
class StopOnLR(Callback):
|
|
8
|
+
def __init__( self, min_lr, **kwargs, ):
|
|
9
|
+
super().__init__()
|
|
10
|
+
self.min_lr = min_lr
|
|
11
|
+
|
|
12
|
+
def on_epoch_end(self, epoch, logs={}):
|
|
13
|
+
lr = backend.get_value(self.model.optimizer.lr)
|
|
14
|
+
if(lr <= self.min_lr):
|
|
15
|
+
self.model.stop_training = True
|
|
16
|
+
|
|
17
|
+
class EpsilonCosineDecayCallback(Callback):
|
|
18
|
+
"""Reduce optimizer epsilon parameter.
|
|
19
|
+
Args:
|
|
20
|
+
factor: factor by which epsilon will be reduced.
|
|
21
|
+
`new_epsilon = epsilon * factor`.
|
|
22
|
+
period: number of epochs after which epsilon will be reduced.
|
|
23
|
+
verbose: int. 0: quiet, 1: update messages.
|
|
24
|
+
min_epsilon: lower bound on the learning rate.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, decay_steps:int, start_epsilon=1, min_epsilon=1e-2, start_step:int=0, verbose=1):
|
|
28
|
+
super(EpsilonCosineDecayCallback, self).__init__()
|
|
29
|
+
self.step_counter = start_step
|
|
30
|
+
self.start_epsilon = start_epsilon
|
|
31
|
+
self.decay_steps=decay_steps
|
|
32
|
+
self.alpha=min_epsilon / start_epsilon
|
|
33
|
+
self.verbose = verbose
|
|
34
|
+
|
|
35
|
+
def on_train_batch_begin(self, batch, logs=None):
|
|
36
|
+
epsilon = self._decayed_epsilon(self.step_counter)
|
|
37
|
+
self.model.optimizer.epsilon = epsilon
|
|
38
|
+
|
|
39
|
+
def on_train_batch_end(self, batch, logs=None):
|
|
40
|
+
self.step_counter +=1
|
|
41
|
+
if logs is not None:
|
|
42
|
+
logs['epsilon'] = self.model.optimizer.epsilon
|
|
43
|
+
|
|
44
|
+
def _decayed_epsilon(self, step):
|
|
45
|
+
step = min(step, self.decay_steps)
|
|
46
|
+
cosine_decay = 0.5 * (1 + cos(pi * step / self.decay_steps))
|
|
47
|
+
decayed = (1 - self.alpha) * cosine_decay + self.alpha
|
|
48
|
+
return self.start_epsilon * decayed
|
|
49
|
+
|
|
50
|
+
class LogsCallback(Callback):
|
|
51
|
+
def __init__(self, filepath, start_epoch=0):
|
|
52
|
+
super().__init__()
|
|
53
|
+
self.filepath = filepath
|
|
54
|
+
self.start_epoch=start_epoch
|
|
55
|
+
|
|
56
|
+
def on_epoch_end(self, epoch, logs=None):
|
|
57
|
+
if logs is not None:
|
|
58
|
+
epoch += self.start_epoch
|
|
59
|
+
losses = list(logs.values())
|
|
60
|
+
losses.insert(0, epoch)
|
|
61
|
+
filepath = self.filepath.format(epoch=epoch + 1, **logs)
|
|
62
|
+
with open(filepath, "a") as file_object:
|
|
63
|
+
writer = csv.writer(file_object, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
|
|
64
|
+
if os.path.getsize(filepath) == 0: # write header only if file is empty
|
|
65
|
+
headers = list(logs.keys())
|
|
66
|
+
headers.insert(0, "epoch")
|
|
67
|
+
writer.writerow(headers)
|
|
68
|
+
writer.writerow(losses)
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import tensorflow as tf
|
|
2
|
+
import tensorflow.keras.backend as K
|
|
3
|
+
import numpy as np
|
|
4
|
+
import dataset_iterator.helpers as dih
|
|
5
|
+
|
|
6
|
+
def get_class_weights(dataset, channel_keyword:str="classes"):
|
|
7
|
+
histo, vmin, bins = dih.get_histogram(dataset, channel_keyword, bins=None, bin_size=1, return_min_and_bin_size=True)
|
|
8
|
+
histo = histo.astype(np.float64)
|
|
9
|
+
if vmin == 0: # remove non-annotated pixels
|
|
10
|
+
histo = histo[1:]
|
|
11
|
+
sum = np.sum(histo)
|
|
12
|
+
#print(f"histo: {histo} sum: {sum}, vmin: {vmin}")
|
|
13
|
+
return sum / histo
|
|
14
|
+
|
|
15
|
+
def weighted_sparse_categorical_crossentropy(weights, dtype='float32', **cce_kwargs):
|
|
16
|
+
weights_cast = np.array(weights).astype(dtype)
|
|
17
|
+
cce = tf.keras.losses.SparseCategoricalCrossentropy(**cce_kwargs)
|
|
18
|
+
wfun = get_category_sample_weights_fun(weights_cast, dtype=dtype)
|
|
19
|
+
def loss_func(true, pred):
|
|
20
|
+
true, wm = tf.split(true, 2, axis=-1)
|
|
21
|
+
weights = wfun(true) * wm[...,0]
|
|
22
|
+
return cce(true, pred, sample_weight=weights)
|
|
23
|
+
return loss_func
|
|
24
|
+
|
|
25
|
+
def get_category_sample_weights_fun(weights_list, axis=-1, sparse=True, dtype='float32'):
|
|
26
|
+
weights_list_cast = np.array(weights_list).astype(dtype)
|
|
27
|
+
class_indices = np.array([i for i in range(len(weights_list_cast))]).astype(dtype)
|
|
28
|
+
def weight_fun(true):
|
|
29
|
+
if sparse:
|
|
30
|
+
class_selectors = K.squeeze(true, axis=axis)
|
|
31
|
+
else:
|
|
32
|
+
class_selectors = K.argmax(true, axis=axis)
|
|
33
|
+
|
|
34
|
+
#considering weights are ordered by class, for each class
|
|
35
|
+
#true(1) if the class index is equal to the weight index
|
|
36
|
+
class_selectors = [K.equal(i, class_selectors) for i in class_indices]
|
|
37
|
+
|
|
38
|
+
#casting boolean to float for calculations
|
|
39
|
+
#each tensor in the list contains 1 where ground true class is equal to its index
|
|
40
|
+
#if you sum all these, you will get a tensor full of ones.
|
|
41
|
+
class_selectors = [tf.cast(x, dtype) for x in class_selectors]
|
|
42
|
+
|
|
43
|
+
#for each of the selections above, multiply their respective weight
|
|
44
|
+
weights = [sel * w for sel, w in zip(class_selectors, weights_list_cast)]
|
|
45
|
+
|
|
46
|
+
#sums all the selections
|
|
47
|
+
#result is a tensor with the respective weight for each element in predictions
|
|
48
|
+
weight_multiplier = weights[0]
|
|
49
|
+
for i in range(1, len(weights)):
|
|
50
|
+
weight_multiplier = weight_multiplier + weights[i]
|
|
51
|
+
|
|
52
|
+
#make sure your original_loss_func only collapses the class axis
|
|
53
|
+
#you need the other axes intact to multiply the weights tensor
|
|
54
|
+
return weight_multiplier
|
|
55
|
+
return weight_fun
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from dataset_iterator import MultiChannelIterator
|
|
3
|
+
from dataset_iterator import extract_tile_random_zoom_function
|
|
4
|
+
from dataset_iterator.image_data_generator import data_generator_to_channel_postprocessing_fun
|
|
5
|
+
from .utils import ensure_multiplicity
|
|
6
|
+
def get_iterator(
|
|
7
|
+
dataset, scaling_data_generator, illumination_data_generator=None,
|
|
8
|
+
input_channel_keywords="raw", class_keyword:str="classes", train_group_keyword:str=None,
|
|
9
|
+
batch_size:int=16, step_number:int=0,
|
|
10
|
+
tiling_parameters:dict = None,
|
|
11
|
+
elasticdeform_parameters=None,
|
|
12
|
+
dtype="float32", shuffle:bool=True ):
|
|
13
|
+
|
|
14
|
+
"""Training Iterator.
|
|
15
|
+
|
|
16
|
+
Parameters
|
|
17
|
+
----------
|
|
18
|
+
dataset : either string or DatasetIO object
|
|
19
|
+
if a string: path to .h5 file containing
|
|
20
|
+
train_group_keyword : str or list of stf
|
|
21
|
+
keyword contained in the path of the training dataset, in order to exclude the evaluation dataset
|
|
22
|
+
scaling_data_generator : ImageDataGenerator or list of ImageDataGenerator (one per channel)
|
|
23
|
+
applied to each channel before elastic deform and tiling, only on channel image and not on classes.
|
|
24
|
+
should only modify intensity and not deform the image as they will not be applied on class image
|
|
25
|
+
illumination_data_generator : ImageDataGenerator or list of ImageDataGenerator (one per channel)
|
|
26
|
+
applied to each channel after elastic deform and tiling, only on channel image and not on classes.
|
|
27
|
+
should only modify intensity and not deform the image as they will not be applied on class image
|
|
28
|
+
step_number : int
|
|
29
|
+
|
|
30
|
+
Returns
|
|
31
|
+
-------
|
|
32
|
+
iterator of tiled images
|
|
33
|
+
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
extract_tiles_fun = None if tiling_parameters is None else extract_tile_random_zoom_function(**tiling_parameters)
|
|
37
|
+
|
|
38
|
+
if isinstance(input_channel_keywords, (list, tuple)):
|
|
39
|
+
channel_keywords = list(input_channel_keywords)
|
|
40
|
+
channel_keywords.append(class_keyword)
|
|
41
|
+
n_inputs = len(input_channel_keywords)
|
|
42
|
+
else:
|
|
43
|
+
channel_keywords = [input_channel_keywords, class_keyword]
|
|
44
|
+
n_inputs = 1
|
|
45
|
+
input_channels = list(range(n_inputs))
|
|
46
|
+
scaling_data_generator = ensure_multiplicity(n_inputs, scaling_data_generator)
|
|
47
|
+
if isinstance(scaling_data_generator, tuple):
|
|
48
|
+
scaling_data_generator = [scaling_data_generator]
|
|
49
|
+
scaling_data_generator.append(None) # classes
|
|
50
|
+
if illumination_data_generator is not None:
|
|
51
|
+
pp_fun = data_generator_to_channel_postprocessing_fun(illumination_data_generator, input_channels)
|
|
52
|
+
else:
|
|
53
|
+
pp_fun = None
|
|
54
|
+
zero = np.zeros(shape=1, dtype=dtype)[0]
|
|
55
|
+
one = np.ones(shape=1, dtype=dtype)[0]
|
|
56
|
+
iterator_params = dict(dataset=dataset,
|
|
57
|
+
channel_keywords=channel_keywords,
|
|
58
|
+
input_channels = input_channels,
|
|
59
|
+
output_channels = [n_inputs],
|
|
60
|
+
mask_channels=[n_inputs],
|
|
61
|
+
group_keyword = train_group_keyword,
|
|
62
|
+
weight_map_functions = [lambda batch: np.where(batch==0, zero, one)], # to avoid unlabeled data be mixed with label 0
|
|
63
|
+
output_postprocessing_functions = [lambda batch : np.where(batch>0, batch-one, zero)], # labels must be in range [0, nlabels-1]
|
|
64
|
+
extract_tile_function = extract_tiles_fun,
|
|
65
|
+
image_data_generators = scaling_data_generator,
|
|
66
|
+
perform_data_augmentation=True,
|
|
67
|
+
elasticdeform_parameters=elasticdeform_parameters,
|
|
68
|
+
channels_postprocessing_function=pp_fun,
|
|
69
|
+
batch_size=batch_size,
|
|
70
|
+
incomplete_last_batch_mode="CONSTANT_SIZE",
|
|
71
|
+
shuffle=shuffle, step_number=step_number,
|
|
72
|
+
dtype=dtype)
|
|
73
|
+
|
|
74
|
+
train_it = MultiChannelIterator(**iterator_params)
|
|
75
|
+
return train_it
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
from tensorflow.keras.layers import Conv2D, Conv3D, Input, MaxPool2D, Conv2DTranspose, Concatenate
|
|
2
|
+
from tensorflow.keras.models import Model
|
|
3
|
+
import keras.backend as K
|
|
4
|
+
import tensorflow as tf
|
|
5
|
+
|
|
6
|
+
ENCODER_SETTINGS = [
|
|
7
|
+
[ # l1 = 128 -> 64
|
|
8
|
+
{"filters":32},
|
|
9
|
+
{"filters":32, "downscale":2, "maxpool":False}
|
|
10
|
+
],
|
|
11
|
+
[ # l2 64 -> 32
|
|
12
|
+
{"filters":32},
|
|
13
|
+
{"filters":32, "downscale":2,"maxpool":False}
|
|
14
|
+
],
|
|
15
|
+
[ # l3: 32->16
|
|
16
|
+
{"filters":64, "kernel_size":5},
|
|
17
|
+
{"filters":64},
|
|
18
|
+
{"filters":64, "downscale":2,"maxpool":False},
|
|
19
|
+
],
|
|
20
|
+
[ # l4: 16 -> 8
|
|
21
|
+
{"filters":128, "kernel_size":5},
|
|
22
|
+
{"filters":128},
|
|
23
|
+
{"filters":256, "downscale":2,"maxpool":False}
|
|
24
|
+
]
|
|
25
|
+
]
|
|
26
|
+
FEATURE_SETTINGS = [
|
|
27
|
+
{"filters":256, "kernel_size":5},
|
|
28
|
+
{"filters":256},
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
DECODER_SETTINGS = [
|
|
32
|
+
{"filters":32},
|
|
33
|
+
{"filters":32},
|
|
34
|
+
{"filters":64},
|
|
35
|
+
{"filters":128}
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
def get_unet(n_classes, n_input_channels=1, encoder_settings = ENCODER_SETTINGS, feature_settings= FEATURE_SETTINGS, decoder_settings=DECODER_SETTINGS, skip_sg=False, skip_omit=None, name = "unet", input_name = "unet_input"):
|
|
39
|
+
assert len(encoder_settings)==len(decoder_settings), "encoder and decoder must have same depth"
|
|
40
|
+
input = Input(shape = (None, None, n_input_channels), name=input_name)
|
|
41
|
+
if skip_sg==True:
|
|
42
|
+
skip_sg = [i for i in range(len(ENCODER_SETTINGS))]
|
|
43
|
+
elif skip_sg==False or skip_sg is None:
|
|
44
|
+
skip_sg = []
|
|
45
|
+
elif isinstance(skip_sg, int):
|
|
46
|
+
skip_sg = [skip_sg]
|
|
47
|
+
assert isinstance(skip_sg, (list, tuple)), "invalid argument: skip_sg should be either bool, None, int or tuple/list of int"
|
|
48
|
+
if skip_omit is None:
|
|
49
|
+
skip_omit = []
|
|
50
|
+
elif isinstance(skip_omit, int):
|
|
51
|
+
skip_omit = [skip_omit]
|
|
52
|
+
assert isinstance(skip_omit, (list, tuple)), "invalid argument: skip_omit should be either None, int or tuple/list of int"
|
|
53
|
+
residuals = []
|
|
54
|
+
downsample_size = []
|
|
55
|
+
for d, parameters in enumerate(encoder_settings):
|
|
56
|
+
down, residual, down_size = downsampling_block(input if d==0 else down, parameters, d, name)
|
|
57
|
+
if d in skip_sg:
|
|
58
|
+
residual = K.stop_gradient(residual)
|
|
59
|
+
residuals.append(residual)
|
|
60
|
+
downsample_size.append(down_size)
|
|
61
|
+
up = downsampling_block(down, feature_settings, len(encoder_settings), name)
|
|
62
|
+
for d in range(len(decoder_settings)-1, -1, -1):
|
|
63
|
+
up=upsampling_block(up, None if d in skip_omit else residuals[d], decoder_settings[d], downsample_size[d], d, name)
|
|
64
|
+
|
|
65
|
+
output = Conv2D(n_classes, kernel_size=3, padding='same', activation="softmax", name=f"{name}/output")(up)
|
|
66
|
+
return Model(input, output, name=name)
|
|
67
|
+
|
|
68
|
+
def downsampling_block(input, parameters, l_idx, name):
|
|
69
|
+
convolutions = [input]
|
|
70
|
+
for i, params in enumerate(parameters):
|
|
71
|
+
downsample = params.get("downscale", 1)
|
|
72
|
+
maxpool = params.get("maxpool", False)
|
|
73
|
+
assert downsample == 1 or i == len(parameters)-1, "downscale > 1 must be last convolution"
|
|
74
|
+
conv = Conv2D(filters=params["filters"], kernel_size=params.get("kernel_size", 3), padding='same', activation=params.get("activation", "relu"), strides = 1 if maxpool else downsample, name=f"{name}/encoder/{l_idx}/conv_{i}")(convolutions[-1])
|
|
75
|
+
convolutions.append(conv)
|
|
76
|
+
if downsample>1 and maxpool:
|
|
77
|
+
mp = MaxPool2D(pool_size = downsample, name=f"{name}/encoder/{l_idx}/mp_{i}")(convolutions[-1])
|
|
78
|
+
convolutions.append(mp)
|
|
79
|
+
downsample = parameters[-1].get("downscale", 1)
|
|
80
|
+
if downsample>1:
|
|
81
|
+
return convolutions[-1], convolutions[-2], downsample
|
|
82
|
+
else:
|
|
83
|
+
return convolutions[-1]
|
|
84
|
+
|
|
85
|
+
def upsampling_block(input, residual, params, stride, l_idx, name):
|
|
86
|
+
up = Conv2DTranspose(params["filters"], kernel_size=params.get("up_kernel_size", 4), strides=stride, padding='same', activation=params.get("activation", "relu"), name=f"{name}/decoder/{l_idx}/upConv")(input)
|
|
87
|
+
if residual is not None:
|
|
88
|
+
concat = Concatenate(axis=-1, name = f"{name}/decoder/{l_idx}/concat")([residual, up])
|
|
89
|
+
else:
|
|
90
|
+
concat = up
|
|
91
|
+
conv = Conv2D(filters=params["filters"], kernel_size=params.get("kernel_size", 3), padding='same', activation=params.get("activation", "relu"), name=f"{name}/decoder/{l_idx}/conv1")(concat)
|
|
92
|
+
return Conv2D(filters=params["filters"] if l_idx==0 else params["filters"]//2, kernel_size=params.get("kernel_size", 3), padding='same', activation=params.get("activation", "relu"), name=f"{name}/decoder/{l_idx}/conv2")(conv)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
def ensure_multiplicity(n, object):
|
|
4
|
+
if object is None:
|
|
5
|
+
return [None] * n
|
|
6
|
+
if not isinstance(object, (list, tuple)):
|
|
7
|
+
object = [object]
|
|
8
|
+
if len(object)>1 and len(object)!=n:
|
|
9
|
+
raise ValueError("length should be either 1 either {}".format(n))
|
|
10
|
+
if n>1 and len(object)==1:
|
|
11
|
+
object = object*n
|
|
12
|
+
elif n==0:
|
|
13
|
+
return []
|
|
14
|
+
return object
|
|
15
|
+
|
|
16
|
+
def is_list(l):
|
|
17
|
+
return isinstance(l, (list, tuple, np.ndarray))
|
PixMClass-0.1.0/setup.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import setuptools
|
|
2
|
+
|
|
3
|
+
with open("README.md", "r") as fh:
|
|
4
|
+
long_description = fh.read()
|
|
5
|
+
|
|
6
|
+
setuptools.setup(
|
|
7
|
+
name="PixMClass",
|
|
8
|
+
version="0.1.0",
|
|
9
|
+
author="Jean Ollion",
|
|
10
|
+
author_email="jean.ollion@polytechnique.org",
|
|
11
|
+
description="Multiclass pixel classification",
|
|
12
|
+
long_description=long_description,
|
|
13
|
+
long_description_content_type="text/markdown",
|
|
14
|
+
url="https://github.com/jeanollion/pix_mclass",
|
|
15
|
+
download_url='https://github.com/jeanollion/pix_mclass/releases/download/v0.1.0/pix_mclass-0.1.0.tar.gz',
|
|
16
|
+
packages=setuptools.find_packages(),
|
|
17
|
+
keywords = ['Segmentation', 'Classification', 'Microscopy', 'Cell'],
|
|
18
|
+
classifiers=[
|
|
19
|
+
'Development Status :: 4 - Beta',
|
|
20
|
+
'Intended Audience :: Science/Research',
|
|
21
|
+
'Topic :: Scientific/Engineering :: Artificial Intelligence',
|
|
22
|
+
'Topic :: Scientific/Engineering :: Image Processing',
|
|
23
|
+
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
|
|
24
|
+
'Programming Language :: Python :: 3',
|
|
25
|
+
],
|
|
26
|
+
python_requires='>=3',
|
|
27
|
+
install_requires=['numpy', 'scipy', 'tensorflow>=2.7.1', 'dataset_iterator>=0.4.0', 'elasticdeform']
|
|
28
|
+
)
|