Corentin Meyer
commited on
Commit
·
3840afc
1
Parent(s):
a00d8e9
Working towards Keras 3 Model
Browse files- .python-version +1 -0
- README.md +4 -2
- main.py +6 -0
- myoquant-sdh-train.ipynb +0 -0
- pyproject.toml +20 -0
- random_brightness.py +0 -345
- sdh_embedding_umap.ipynb +98 -90
- uv.lock +0 -0
.python-version
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
3.12
|
README.md
CHANGED
@@ -35,6 +35,8 @@ model-index:
|
|
35 |
name: Test Accuracy # Optional. Example: Test WER
|
36 |
---
|
37 |
|
|
|
|
|
38 |
## Model description
|
39 |
|
40 |
<p align="center">
|
@@ -141,7 +143,7 @@ Test data results:
|
|
141 |
With Tensorflow 2.10 and over:
|
142 |
|
143 |
```python
|
144 |
-
model_sdh = keras.models.load_model("model.
|
145 |
```
|
146 |
|
147 |
With Tensorflow <2.10:
|
@@ -151,7 +153,7 @@ Then the model can easily be imported in Tensorflow/Keras using:
|
|
151 |
```python
|
152 |
from .random_brightness import *
|
153 |
model_sdh = keras.models.load_model(
|
154 |
-
"model.
|
155 |
)
|
156 |
```
|
157 |
|
|
|
35 |
name: Test Accuracy # Optional. Example: Test WER
|
36 |
---
|
37 |
|
38 |
+
# TODO: UPDATE WITH LATEST INFO
|
39 |
+
|
40 |
## Model description
|
41 |
|
42 |
<p align="center">
|
|
|
143 |
With Tensorflow 2.10 and over:
|
144 |
|
145 |
```python
|
146 |
+
model_sdh = keras.models.load_model("model.keras")
|
147 |
```
|
148 |
|
149 |
With Tensorflow <2.10:
|
|
|
153 |
```python
|
154 |
from .random_brightness import *
|
155 |
model_sdh = keras.models.load_model(
|
156 |
+
"model.keras", custom_objects={"RandomBrightness": RandomBrightness}
|
157 |
)
|
158 |
```
|
159 |
|
main.py
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
def main():
|
2 |
+
print("Hello from myoquant-sdh-model!")
|
3 |
+
|
4 |
+
|
5 |
+
if __name__ == "__main__":
|
6 |
+
main()
|
myoquant-sdh-train.ipynb
CHANGED
The diff for this file is too large to render.
See raw diff
|
|
pyproject.toml
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[project]
|
2 |
+
name = "myoquant-sdh-model"
|
3 |
+
version = "0.1.0"
|
4 |
+
description = "Add your description here"
|
5 |
+
readme = "README.md"
|
6 |
+
requires-python = ">=3.12"
|
7 |
+
dependencies = [
|
8 |
+
"datasets>=3.6.0",
|
9 |
+
"ipywidgets>=8.1.7",
|
10 |
+
"jupyter>=1.1.1",
|
11 |
+
"keras>=3.10.0",
|
12 |
+
"keras-cv>=0.9.0",
|
13 |
+
"keras-hub>=0.21.0",
|
14 |
+
"matplotlib>=3.10.3",
|
15 |
+
"notebook>=7.4.3",
|
16 |
+
"scikit-learn>=1.6.1",
|
17 |
+
"tensorflow>=2.19.0",
|
18 |
+
"tensorflow-metal>=1.2.0",
|
19 |
+
"wandb>=0.19.11",
|
20 |
+
]
|
random_brightness.py
DELETED
@@ -1,345 +0,0 @@
|
|
1 |
-
# @title Random Brightness Layer
|
2 |
-
import tensorflow as tf
|
3 |
-
from keras import backend
|
4 |
-
from keras.engine import base_layer
|
5 |
-
from keras.engine import base_preprocessing_layer
|
6 |
-
from keras.layers.preprocessing import preprocessing_utils as utils
|
7 |
-
from keras.utils import tf_utils
|
8 |
-
|
9 |
-
from tensorflow.python.ops import stateless_random_ops
|
10 |
-
from tensorflow.python.util.tf_export import keras_export
|
11 |
-
from tensorflow.tools.docs import doc_controls
|
12 |
-
|
13 |
-
|
14 |
-
@keras_export("keras.__internal__.layers.BaseImageAugmentationLayer")
|
15 |
-
class BaseImageAugmentationLayer(base_layer.BaseRandomLayer):
|
16 |
-
"""Abstract base layer for image augmentaion.
|
17 |
-
This layer contains base functionalities for preprocessing layers which
|
18 |
-
augment image related data, eg. image and in future, label and bounding boxes.
|
19 |
-
The subclasses could avoid making certain mistakes and reduce code
|
20 |
-
duplications.
|
21 |
-
This layer requires you to implement one method: `augment_image()`, which
|
22 |
-
augments one single image during the training. There are a few additional
|
23 |
-
methods that you can implement for added functionality on the layer:
|
24 |
-
`augment_label()`, which handles label augmentation if the layer supports
|
25 |
-
that.
|
26 |
-
`augment_bounding_box()`, which handles the bounding box augmentation, if the
|
27 |
-
layer supports that.
|
28 |
-
`get_random_transformation()`, which should produce a random transformation
|
29 |
-
setting. The tranformation object, which could be any type, will be passed to
|
30 |
-
`augment_image`, `augment_label` and `augment_bounding_box`, to coodinate
|
31 |
-
the randomness behavior, eg, in the RandomFlip layer, the image and
|
32 |
-
bounding_box should be changed in the same way.
|
33 |
-
The `call()` method support two formats of inputs:
|
34 |
-
1. Single image tensor with 3D (HWC) or 4D (NHWC) format.
|
35 |
-
2. A dict of tensors with stable keys. The supported keys are:
|
36 |
-
`"images"`, `"labels"` and `"bounding_boxes"` at the moment. We might add
|
37 |
-
more keys in future when we support more types of augmentation.
|
38 |
-
The output of the `call()` will be in two formats, which will be the same
|
39 |
-
structure as the inputs.
|
40 |
-
The `call()` will handle the logic detecting the training/inference
|
41 |
-
mode, unpack the inputs, forward to the correct function, and pack the output
|
42 |
-
back to the same structure as the inputs.
|
43 |
-
By default the `call()` method leverages the `tf.vectorized_map()` function.
|
44 |
-
Auto-vectorization can be disabled by setting `self.auto_vectorize = False`
|
45 |
-
in your `__init__()` method. When disabled, `call()` instead relies
|
46 |
-
on `tf.map_fn()`. For example:
|
47 |
-
```python
|
48 |
-
class SubclassLayer(BaseImageAugmentationLayer):
|
49 |
-
def __init__(self):
|
50 |
-
super().__init__()
|
51 |
-
self.auto_vectorize = False
|
52 |
-
```
|
53 |
-
Example:
|
54 |
-
```python
|
55 |
-
class RandomContrast(BaseImageAugmentationLayer):
|
56 |
-
def __init__(self, factor=(0.5, 1.5), **kwargs):
|
57 |
-
super().__init__(**kwargs)
|
58 |
-
self._factor = factor
|
59 |
-
def augment_image(self, image, transformation=None):
|
60 |
-
random_factor = tf.random.uniform([], self._factor[0], self._factor[1])
|
61 |
-
mean = tf.math.reduced_mean(inputs, axis=-1, keep_dim=True)
|
62 |
-
return (inputs - mean) * random_factor + mean
|
63 |
-
```
|
64 |
-
Note that since the randomness is also a common functionnality, this layer
|
65 |
-
also includes a tf.keras.backend.RandomGenerator, which can be used to produce
|
66 |
-
the random numbers. The random number generator is stored in the
|
67 |
-
`self._random_generator` attribute.
|
68 |
-
"""
|
69 |
-
|
70 |
-
def __init__(self, rate=1.0, seed=None, **kwargs):
|
71 |
-
super().__init__(seed=seed, **kwargs)
|
72 |
-
self.rate = rate
|
73 |
-
|
74 |
-
@property
|
75 |
-
def auto_vectorize(self):
|
76 |
-
"""Control whether automatic vectorization occurs.
|
77 |
-
By default the `call()` method leverages the `tf.vectorized_map()` function.
|
78 |
-
Auto-vectorization can be disabled by setting `self.auto_vectorize = False`
|
79 |
-
in your `__init__()` method. When disabled, `call()` instead relies
|
80 |
-
on `tf.map_fn()`. For example:
|
81 |
-
```python
|
82 |
-
class SubclassLayer(BaseImageAugmentationLayer):
|
83 |
-
def __init__(self):
|
84 |
-
super().__init__()
|
85 |
-
self.auto_vectorize = False
|
86 |
-
```
|
87 |
-
"""
|
88 |
-
return getattr(self, "_auto_vectorize", True)
|
89 |
-
|
90 |
-
@auto_vectorize.setter
|
91 |
-
def auto_vectorize(self, auto_vectorize):
|
92 |
-
self._auto_vectorize = auto_vectorize
|
93 |
-
|
94 |
-
@property
|
95 |
-
def _map_fn(self):
|
96 |
-
if self.auto_vectorize:
|
97 |
-
return tf.vectorized_map
|
98 |
-
else:
|
99 |
-
return tf.map_fn
|
100 |
-
|
101 |
-
@doc_controls.for_subclass_implementers
|
102 |
-
def augment_image(self, image, transformation=None):
|
103 |
-
"""Augment a single image during training.
|
104 |
-
Args:
|
105 |
-
image: 3D image input tensor to the layer. Forwarded from `layer.call()`.
|
106 |
-
transformation: The transformation object produced by
|
107 |
-
`get_random_transformation`. Used to coordinate the randomness between
|
108 |
-
image, label and bounding box.
|
109 |
-
Returns:
|
110 |
-
output 3D tensor, which will be forward to `layer.call()`.
|
111 |
-
"""
|
112 |
-
raise NotImplementedError()
|
113 |
-
|
114 |
-
@doc_controls.for_subclass_implementers
|
115 |
-
def augment_label(self, label, transformation=None):
|
116 |
-
"""Augment a single label during training.
|
117 |
-
Args:
|
118 |
-
label: 1D label to the layer. Forwarded from `layer.call()`.
|
119 |
-
transformation: The transformation object produced by
|
120 |
-
`get_random_transformation`. Used to coordinate the randomness between
|
121 |
-
image, label and bounding box.
|
122 |
-
Returns:
|
123 |
-
output 1D tensor, which will be forward to `layer.call()`.
|
124 |
-
"""
|
125 |
-
raise NotImplementedError()
|
126 |
-
|
127 |
-
@doc_controls.for_subclass_implementers
|
128 |
-
def augment_bounding_box(self, bounding_box, transformation=None):
|
129 |
-
"""Augment bounding boxes for one image during training.
|
130 |
-
Args:
|
131 |
-
bounding_box: 2D bounding boxes to the layer. Forwarded from `call()`.
|
132 |
-
transformation: The transformation object produced by
|
133 |
-
`get_random_transformation`. Used to coordinate the randomness between
|
134 |
-
image, label and bounding box.
|
135 |
-
Returns:
|
136 |
-
output 2D tensor, which will be forward to `layer.call()`.
|
137 |
-
"""
|
138 |
-
raise NotImplementedError()
|
139 |
-
|
140 |
-
@doc_controls.for_subclass_implementers
|
141 |
-
def get_random_transformation(self, image=None, label=None, bounding_box=None):
|
142 |
-
"""Produce random transformation config for one single input.
|
143 |
-
This is used to produce same randomness between image/label/bounding_box.
|
144 |
-
Args:
|
145 |
-
image: 3D image tensor from inputs.
|
146 |
-
label: optional 1D label tensor from inputs.
|
147 |
-
bounding_box: optional 2D bounding boxes tensor from inputs.
|
148 |
-
Returns:
|
149 |
-
Any type of object, which will be forwarded to `augment_image`,
|
150 |
-
`augment_label` and `augment_bounding_box` as the `transformation`
|
151 |
-
parameter.
|
152 |
-
"""
|
153 |
-
return None
|
154 |
-
|
155 |
-
def call(self, inputs, training=True):
|
156 |
-
inputs = self._ensure_inputs_are_compute_dtype(inputs)
|
157 |
-
if training:
|
158 |
-
inputs, is_dict = self._format_inputs(inputs)
|
159 |
-
images = inputs["images"]
|
160 |
-
if images.shape.rank == 3:
|
161 |
-
return self._format_output(self._augment(inputs), is_dict)
|
162 |
-
elif images.shape.rank == 4:
|
163 |
-
return self._format_output(self._batch_augment(inputs), is_dict)
|
164 |
-
else:
|
165 |
-
raise ValueError(
|
166 |
-
"Image augmentation layers are expecting inputs to be "
|
167 |
-
"rank 3 (HWC) or 4D (NHWC) tensors. Got shape: "
|
168 |
-
f"{images.shape}"
|
169 |
-
)
|
170 |
-
else:
|
171 |
-
return inputs
|
172 |
-
|
173 |
-
def _augment(self, inputs):
|
174 |
-
image = inputs.get("images", None)
|
175 |
-
label = inputs.get("labels", None)
|
176 |
-
bounding_box = inputs.get("bounding_boxes", None)
|
177 |
-
transformation = self.get_random_transformation(
|
178 |
-
image=image, label=label, bounding_box=bounding_box
|
179 |
-
) # pylint: disable=assignment-from-none
|
180 |
-
image = self.augment_image(image, transformation=transformation)
|
181 |
-
result = {"images": image}
|
182 |
-
if label is not None:
|
183 |
-
label = self.augment_label(label, transformation=transformation)
|
184 |
-
result["labels"] = label
|
185 |
-
if bounding_box is not None:
|
186 |
-
bounding_box = self.augment_bounding_box(
|
187 |
-
bounding_box, transformation=transformation
|
188 |
-
)
|
189 |
-
result["bounding_boxes"] = bounding_box
|
190 |
-
return result
|
191 |
-
|
192 |
-
def _batch_augment(self, inputs):
|
193 |
-
return self._map_fn(self._augment, inputs)
|
194 |
-
|
195 |
-
def _format_inputs(self, inputs):
|
196 |
-
if tf.is_tensor(inputs):
|
197 |
-
# single image input tensor
|
198 |
-
return {"images": inputs}, False
|
199 |
-
elif isinstance(inputs, dict):
|
200 |
-
# TODO(scottzhu): Check if it only contains the valid keys
|
201 |
-
return inputs, True
|
202 |
-
else:
|
203 |
-
raise ValueError(
|
204 |
-
f"Expect the inputs to be image tensor or dict. Got {inputs}"
|
205 |
-
)
|
206 |
-
|
207 |
-
def _format_output(self, output, is_dict):
|
208 |
-
if not is_dict:
|
209 |
-
return output["images"]
|
210 |
-
else:
|
211 |
-
return output
|
212 |
-
|
213 |
-
def _ensure_inputs_are_compute_dtype(self, inputs):
|
214 |
-
if isinstance(inputs, dict):
|
215 |
-
inputs["images"] = utils.ensure_tensor(inputs["images"], self.compute_dtype)
|
216 |
-
else:
|
217 |
-
inputs = utils.ensure_tensor(inputs, self.compute_dtype)
|
218 |
-
return inputs
|
219 |
-
|
220 |
-
|
221 |
-
@keras_export("keras.layers.RandomBrightness", v1=[])
|
222 |
-
class RandomBrightness(BaseImageAugmentationLayer):
|
223 |
-
"""A preprocessing layer which randomly adjusts brightness during training.
|
224 |
-
This layer will randomly increase/reduce the brightness for the input RGB
|
225 |
-
images. At inference time, the output will be identical to the input.
|
226 |
-
Call the layer with `training=True` to adjust the brightness of the input.
|
227 |
-
Note that different brightness adjustment factors
|
228 |
-
will be apply to each the images in the batch.
|
229 |
-
For an overview and full list of preprocessing layers, see the preprocessing
|
230 |
-
[guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).
|
231 |
-
Args:
|
232 |
-
factor: Float or a list/tuple of 2 floats between -1.0 and 1.0. The
|
233 |
-
factor is used to determine the lower bound and upper bound of the
|
234 |
-
brightness adjustment. A float value will be chosen randomly between
|
235 |
-
the limits. When -1.0 is chosen, the output image will be black, and
|
236 |
-
when 1.0 is chosen, the image will be fully white. When only one float
|
237 |
-
is provided, eg, 0.2, then -0.2 will be used for lower bound and 0.2
|
238 |
-
will be used for upper bound.
|
239 |
-
value_range: Optional list/tuple of 2 floats for the lower and upper limit
|
240 |
-
of the values of the input data. Defaults to [0.0, 255.0]. Can be changed
|
241 |
-
to e.g. [0.0, 1.0] if the image input has been scaled before this layer.
|
242 |
-
The brightness adjustment will be scaled to this range, and the
|
243 |
-
output values will be clipped to this range.
|
244 |
-
seed: optional integer, for fixed RNG behavior.
|
245 |
-
Inputs: 3D (HWC) or 4D (NHWC) tensor, with float or int dtype. Input pixel
|
246 |
-
values can be of any range (e.g. `[0., 1.)` or `[0, 255]`)
|
247 |
-
Output: 3D (HWC) or 4D (NHWC) tensor with brightness adjusted based on the
|
248 |
-
`factor`. By default, the layer will output floats. The output value will
|
249 |
-
be clipped to the range `[0, 255]`, the valid range of RGB colors, and
|
250 |
-
rescaled based on the `value_range` if needed.
|
251 |
-
Sample usage:
|
252 |
-
```python
|
253 |
-
random_bright = tf.keras.layers.RandomBrightness(factor=0.2)
|
254 |
-
# An image with shape [2, 2, 3]
|
255 |
-
image = [[[1, 2, 3], [4 ,5 ,6]], [[7, 8, 9], [10, 11, 12]]]
|
256 |
-
# Assume we randomly select the factor to be 0.1, then it will apply
|
257 |
-
# 0.1 * 255 to all the channel
|
258 |
-
output = random_bright(image, training=True)
|
259 |
-
# output will be int64 with 25.5 added to each channel and round down.
|
260 |
-
tf.Tensor([[[26.5, 27.5, 28.5]
|
261 |
-
[29.5, 30.5, 31.5]]
|
262 |
-
[[32.5, 33.5, 34.5]
|
263 |
-
[35.5, 36.5, 37.5]]],
|
264 |
-
shape=(2, 2, 3), dtype=int64)
|
265 |
-
```
|
266 |
-
"""
|
267 |
-
|
268 |
-
_FACTOR_VALIDATION_ERROR = (
|
269 |
-
"The `factor` argument should be a number (or a list of two numbers) "
|
270 |
-
"in the range [-1.0, 1.0]. "
|
271 |
-
)
|
272 |
-
_VALUE_RANGE_VALIDATION_ERROR = (
|
273 |
-
"The `value_range` argument should be a list of two numbers. "
|
274 |
-
)
|
275 |
-
|
276 |
-
def __init__(self, factor, value_range=(0, 255), seed=None, **kwargs):
|
277 |
-
base_preprocessing_layer.keras_kpl_gauge.get_cell("RandomBrightness").set(True)
|
278 |
-
super().__init__(seed=seed, force_generator=True, **kwargs)
|
279 |
-
self._set_factor(factor)
|
280 |
-
self._set_value_range(value_range)
|
281 |
-
self._seed = seed
|
282 |
-
|
283 |
-
def augment_image(self, image, transformation=None):
|
284 |
-
return self._brightness_adjust(image, transformation["rgb_delta"])
|
285 |
-
|
286 |
-
def augment_label(self, label, transformation=None):
|
287 |
-
return label
|
288 |
-
|
289 |
-
def get_random_transformation(self, image=None, label=None, bounding_box=None):
|
290 |
-
rgb_delta_shape = (1, 1, 1)
|
291 |
-
random_rgb_delta = self._random_generator.random_uniform(
|
292 |
-
shape=rgb_delta_shape,
|
293 |
-
minval=self._factor[0],
|
294 |
-
maxval=self._factor[1],
|
295 |
-
)
|
296 |
-
random_rgb_delta = random_rgb_delta * (
|
297 |
-
self._value_range[1] - self._value_range[0]
|
298 |
-
)
|
299 |
-
return {"rgb_delta": random_rgb_delta}
|
300 |
-
|
301 |
-
def _set_value_range(self, value_range):
|
302 |
-
if not isinstance(value_range, (tuple, list)):
|
303 |
-
raise ValueError(self._VALUE_RANGE_VALIDATION_ERROR + f"Got {value_range}")
|
304 |
-
if len(value_range) != 2:
|
305 |
-
raise ValueError(self._VALUE_RANGE_VALIDATION_ERROR + f"Got {value_range}")
|
306 |
-
self._value_range = sorted(value_range)
|
307 |
-
|
308 |
-
def _set_factor(self, factor):
|
309 |
-
if isinstance(factor, (tuple, list)):
|
310 |
-
if len(factor) != 2:
|
311 |
-
raise ValueError(self._FACTOR_VALIDATION_ERROR + f"Got {factor}")
|
312 |
-
self._check_factor_range(factor[0])
|
313 |
-
self._check_factor_range(factor[1])
|
314 |
-
self._factor = sorted(factor)
|
315 |
-
elif isinstance(factor, (int, float)):
|
316 |
-
self._check_factor_range(factor)
|
317 |
-
factor = abs(factor)
|
318 |
-
self._factor = [-factor, factor]
|
319 |
-
else:
|
320 |
-
raise ValueError(self._FACTOR_VALIDATION_ERROR + f"Got {factor}")
|
321 |
-
|
322 |
-
def _check_factor_range(self, input_number):
|
323 |
-
if input_number > 1.0 or input_number < -1.0:
|
324 |
-
raise ValueError(self._FACTOR_VALIDATION_ERROR + f"Got {input_number}")
|
325 |
-
|
326 |
-
def _brightness_adjust(self, image, rgb_delta):
|
327 |
-
image = utils.ensure_tensor(image, self.compute_dtype)
|
328 |
-
rank = image.shape.rank
|
329 |
-
if rank != 3:
|
330 |
-
raise ValueError(
|
331 |
-
"Expected the input image to be rank 3. Got "
|
332 |
-
f"inputs.shape = {image.shape}"
|
333 |
-
)
|
334 |
-
rgb_delta = tf.cast(rgb_delta, image.dtype)
|
335 |
-
image += rgb_delta
|
336 |
-
return tf.clip_by_value(image, self._value_range[0], self._value_range[1])
|
337 |
-
|
338 |
-
def get_config(self):
|
339 |
-
config = {
|
340 |
-
"factor": self._factor,
|
341 |
-
"value_range": self._value_range,
|
342 |
-
"seed": self._seed,
|
343 |
-
}
|
344 |
-
base_config = super().get_config()
|
345 |
-
return dict(list(base_config.items()) + list(config.items()))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
sdh_embedding_umap.ipynb
CHANGED
@@ -32,28 +32,25 @@
|
|
32 |
],
|
33 |
"source": [
|
34 |
"# List all file in data directory with Pathlib\n",
|
35 |
-
"from pathlib import Path\n",
|
36 |
"import numpy as np\n",
|
37 |
-
"import pandas as pd\n",
|
38 |
-
"import os\n",
|
39 |
-
"import tensorflow as tf\n",
|
40 |
-
"import glob\n",
|
41 |
"from tensorflow.keras.preprocessing import image\n",
|
42 |
"from tensorflow.keras.utils import img_to_array\n",
|
43 |
"\n",
|
44 |
-
"LABELS_DICT = {\"control\":0, \"sick\":1}\n",
|
45 |
"SUB_FOLDERS = [\"control\", \"sick\"]\n",
|
46 |
"\n",
|
|
|
47 |
"def get_mouse_model(file_path):\n",
|
48 |
-
"
|
49 |
-
"
|
50 |
-
"
|
51 |
-
"
|
52 |
-
"
|
53 |
-
"
|
54 |
-
"
|
55 |
-
"
|
56 |
-
"
|
|
|
57 |
"\n",
|
58 |
"def dirty_filter_file_names(file_name):\n",
|
59 |
" file_name = file_name.split(\"/\")[-1]\n",
|
@@ -64,10 +61,11 @@
|
|
64 |
" file_name = '_'.join(file_name.split(\"_\")[1:])\n",
|
65 |
" return file_name\n",
|
66 |
"\n",
|
|
|
67 |
"def generate_dataset(folder, sub_folders=[\"control\", \"inter\", \"sick\"]):\n",
|
68 |
" n_elem = 0\n",
|
69 |
" for sub_folder in sub_folders:\n",
|
70 |
-
"
|
71 |
" images_array = np.empty(shape=(n_elem, 256, 256, 3), dtype=np.uint8)\n",
|
72 |
" path_array = []\n",
|
73 |
" mouse_model = []\n",
|
@@ -75,19 +73,21 @@
|
|
75 |
" labels_array = np.empty(shape=n_elem, dtype=np.uint8)\n",
|
76 |
" counter = 0\n",
|
77 |
" for index, sub_folder in enumerate(sub_folders):\n",
|
78 |
-
"
|
79 |
-
"
|
80 |
-
"
|
81 |
-
"
|
82 |
-
"
|
83 |
-
"
|
84 |
-
"
|
85 |
-
"
|
86 |
-
"
|
87 |
-
"
|
88 |
" return images_array, path_array, labels_array, mouse_model, mouse_model_full\n",
|
89 |
"\n",
|
90 |
-
"
|
|
|
|
|
91 |
"file_dict = dict(\n",
|
92 |
" file=all_files,\n",
|
93 |
" label=labels,\n",
|
@@ -239,11 +239,13 @@
|
|
239 |
"# Load image embetter \n",
|
240 |
"import tensorflow as tf\n",
|
241 |
"import os\n",
|
242 |
-
"
|
|
|
243 |
"model = tf.keras.models.load_model(MODEL_NAME)\n",
|
244 |
"emb_model = tf.keras.models.Sequential()\n",
|
245 |
"emb_model.add(model.get_layer('sequential'))\n",
|
246 |
-
"emb_model.add(tf.keras.models.Model(inputs=model.get_layer('resnet50v2').input
|
|
|
247 |
"embeddings = emb_model.predict(file_dict[\"image\"])\n",
|
248 |
"with open('data/results/embedding/image_embedding_custom.npy', 'wb') as f:\n",
|
249 |
" np.save(f, embeddings)"
|
@@ -268,6 +270,7 @@
|
|
268 |
"source": [
|
269 |
"from umap import UMAP\n",
|
270 |
"import numpy as np\n",
|
|
|
271 |
"embeddings = np.load(open('data/results/embedding/image_embedding_custom.npy', 'rb'))\n",
|
272 |
"embedding_umap = UMAP().fit_transform(embeddings)\n",
|
273 |
"embedding_umap.shape"
|
@@ -291,27 +294,27 @@
|
|
291 |
],
|
292 |
"source": [
|
293 |
"import matplotlib.pyplot as plt\n",
|
294 |
-
"
|
295 |
"cdict = {0: 'green', 1: 'red'}\n",
|
296 |
"\n",
|
297 |
"# Get the index of row from embedding_umap where the first column is greater than 0 and the second column is greater than 0\n",
|
298 |
"\n",
|
299 |
-
"x_condition2 = ((embedding_umap[:,0] > 0) & (embedding_umap[:,0] < 1))\n",
|
300 |
-
"y_condition2 = ((embedding_umap[:,1] > 4.75) & (embedding_umap[:,1] < 5.5))\n",
|
301 |
"idx_left_cluster = np.where((x_condition2 & y_condition2))[0]\n",
|
302 |
"\n",
|
303 |
-
"x_condition = ((embedding_umap[:,0] > 4.75) & (embedding_umap[:,0] < 5.75))\n",
|
304 |
-
"y_condition = ((embedding_umap[:,1] > 4.5) & (embedding_umap[:,1] < 5.25))\n",
|
305 |
"idx_right_cluster = np.where((x_condition & y_condition))[0]\n",
|
306 |
"\n",
|
307 |
-
"fig, ax = plt.subplots(1, 1, figsize=(10,10))\n",
|
308 |
"for g in np.unique(labels):\n",
|
309 |
" ix = np.where(labels == g)\n",
|
310 |
-
" ax.scatter(embedding_umap[:, 0][ix]
|
311 |
-
"
|
312 |
-
"
|
313 |
-
"
|
314 |
-
"
|
315 |
"ax.legend()\n",
|
316 |
"plt.show()"
|
317 |
]
|
@@ -333,21 +336,21 @@
|
|
333 |
}
|
334 |
],
|
335 |
"source": [
|
336 |
-
"cdict_model_full = {'BIN1_KO_AAV_EMPTY_TAG'
|
337 |
-
"
|
338 |
-
"
|
339 |
-
"
|
340 |
-
"
|
341 |
-
"
|
342 |
-
"fig, ax = plt.subplots(1, 1, figsize=(10,10))\n",
|
343 |
"for g in np.unique(mouse_model_full):\n",
|
344 |
" numpy_mouse_model_full = np.array(mouse_model_full)\n",
|
345 |
" ix = np.where(numpy_mouse_model_full == g)\n",
|
346 |
-
" ax.scatter(embedding_umap[:, 0][ix]
|
347 |
-
"
|
348 |
-
"
|
349 |
-
"
|
350 |
-
"
|
351 |
"ax.legend()\n",
|
352 |
"plt.show()"
|
353 |
]
|
@@ -370,15 +373,15 @@
|
|
370 |
],
|
371 |
"source": [
|
372 |
"cdict_model = {\"wt\": 'green', \"bin1\": 'red', \"dnm2\": \"blue\", \"unknown\": \"black\"}\n",
|
373 |
-
"fig, ax = plt.subplots(1, 1, figsize=(10,10))\n",
|
374 |
"for g in np.unique(mouse_model):\n",
|
375 |
" numpy_mouse_model = np.array(mouse_model)\n",
|
376 |
" ix = np.where(numpy_mouse_model == g)\n",
|
377 |
-
" ax.scatter(embedding_umap[:, 0][ix]
|
378 |
-
"
|
379 |
-
"
|
380 |
-
"
|
381 |
-
"
|
382 |
"ax.legend()\n",
|
383 |
"plt.show()"
|
384 |
]
|
@@ -403,8 +406,8 @@
|
|
403 |
],
|
404 |
"source": [
|
405 |
"from doubtlab.ensemble import DoubtEnsemble\n",
|
406 |
-
"from doubtlab.reason import ProbaReason, LongConfidenceReason
|
407 |
-
"import pandas as pd
|
408 |
"\n",
|
409 |
"# Let's precalculate the proba values.\n",
|
410 |
"probas = model.predict(img_data)\n",
|
@@ -421,17 +424,19 @@
|
|
421 |
"# This dataframe now contains the predicates\n",
|
422 |
"doubtlab_df = pd.DataFrame(predicate_dict)\n",
|
423 |
"# Create a new column with 1 if the previous predicates are true else 0\n",
|
424 |
-
"doubtlab_df['doubt'] = doubtlab_df[[\"proba\"
|
425 |
"wrong_strong_idx = doubtlab_df[doubtlab_df[\"long\"] == 1.0].index\n",
|
426 |
"wrong_idx = doubtlab_df[doubtlab_df[\"wrong\"] == 1.0].index\n",
|
427 |
"low_idx = doubtlab_df[doubtlab_df[\"proba\"] == 1.0].index\n",
|
428 |
"cleanlab_idx = doubtlab_df[doubtlab_df[\"cleanlab\"] == 1.0].index\n",
|
429 |
"doubt_idx = doubtlab_df[doubtlab_df[\"doubt\"] == True].index\n",
|
430 |
-
"print(
|
431 |
-
"
|
432 |
-
"print(f\"Total Number of images with
|
433 |
-
"print(f\"Total Number of images with
|
434 |
-
"print(
|
|
|
|
|
435 |
]
|
436 |
},
|
437 |
{
|
@@ -459,12 +464,13 @@
|
|
459 |
],
|
460 |
"source": [
|
461 |
"wrong_strong_idx = doubtlab_df[doubtlab_df[\"long\"] == 1.0].index\n",
|
462 |
-
"print(
|
|
|
463 |
"SUB_FOLDERS = [\"control\", \"sick\"]\n",
|
464 |
"counter = 0\n",
|
465 |
-
"plt.figure(figsize=(10,10))\n",
|
466 |
"for idx in np.random.choice(wrong_strong_idx, 25, replace=False):\n",
|
467 |
-
" plt.subplot(5,5,counter+1)\n",
|
468 |
" plt.xticks([])\n",
|
469 |
" plt.yticks([])\n",
|
470 |
" plt.grid(False)\n",
|
@@ -473,9 +479,9 @@
|
|
473 |
" plt.imshow(im)\n",
|
474 |
"\n",
|
475 |
" predict_proba = max(probas[idx])\n",
|
476 |
-
" predicted_class = np.argmax(probas[idx])
|
477 |
" plt.xlabel(f\"{SUB_FOLDERS[label]} ({SUB_FOLDERS[predicted_class]} {predict_proba:.2f})\")\n",
|
478 |
-
" counter +=1\n",
|
479 |
"plt.show()\n",
|
480 |
"\n"
|
481 |
]
|
@@ -487,12 +493,12 @@
|
|
487 |
"outputs": [],
|
488 |
"source": [
|
489 |
"wrong_idx = doubtlab_df[doubtlab_df[\"wrong\"] == 1.0].index\n",
|
490 |
-
"print(f\"Total Number of images with wrong: {len(wrong_idx)} ({round(len(wrong_idx)/len(doubtlab_df)*100, 2)}%)\")\n",
|
491 |
"SUB_FOLDERS = [\"control\", \"sick\"]\n",
|
492 |
"counter = 0\n",
|
493 |
-
"plt.figure(figsize=(10,10))\n",
|
494 |
"for idx in np.random.choice(wrong_idx, 25, replace=False):\n",
|
495 |
-
" plt.subplot(5,5,counter+1)\n",
|
496 |
" plt.xticks([])\n",
|
497 |
" plt.yticks([])\n",
|
498 |
" plt.grid(False)\n",
|
@@ -501,9 +507,9 @@
|
|
501 |
" plt.imshow(im)\n",
|
502 |
"\n",
|
503 |
" predict_proba = max(probas[idx])\n",
|
504 |
-
" predicted_class = np.argmax(probas[idx])
|
505 |
" plt.xlabel(f\"{SUB_FOLDERS[label]} ({SUB_FOLDERS[predicted_class]} {predict_proba:.2f})\")\n",
|
506 |
-
" counter +=1\n",
|
507 |
"plt.show()\n",
|
508 |
"\n"
|
509 |
]
|
@@ -515,12 +521,12 @@
|
|
515 |
"outputs": [],
|
516 |
"source": [
|
517 |
"low_idx = doubtlab_df[doubtlab_df[\"proba\"] == 1.0].index\n",
|
518 |
-
"print(f\"Total Number of images with low probas: {len(low_idx)} ({round(len(low_idx)/len(doubtlab_df)*100, 2)}%)\")\n",
|
519 |
"SUB_FOLDERS = [\"control\", \"sick\"]\n",
|
520 |
"counter = 0\n",
|
521 |
-
"plt.figure(figsize=(10,10))\n",
|
522 |
"for idx in np.random.choice(low_idx, 25, replace=False):\n",
|
523 |
-
" plt.subplot(5,5,counter+1)\n",
|
524 |
" plt.xticks([])\n",
|
525 |
" plt.yticks([])\n",
|
526 |
" plt.grid(False)\n",
|
@@ -529,9 +535,9 @@
|
|
529 |
" plt.imshow(im)\n",
|
530 |
"\n",
|
531 |
" predict_proba = max(probas[idx])\n",
|
532 |
-
" predicted_class = np.argmax(probas[idx])
|
533 |
" plt.xlabel(f\"{SUB_FOLDERS[label]} ({SUB_FOLDERS[predicted_class]} {predict_proba:.2f})\")\n",
|
534 |
-
" counter +=1\n",
|
535 |
"plt.show()\n",
|
536 |
"\n"
|
537 |
]
|
@@ -543,12 +549,13 @@
|
|
543 |
"outputs": [],
|
544 |
"source": [
|
545 |
"cleanlab_idx = doubtlab_df[doubtlab_df[\"cleanlab\"] == 1.0].index\n",
|
546 |
-
"print(
|
|
|
547 |
"SUB_FOLDERS = [\"control\", \"sick\"]\n",
|
548 |
"counter = 0\n",
|
549 |
-
"plt.figure(figsize=(10,10))\n",
|
550 |
"for idx in np.random.choice(cleanlab_idx, 25, replace=False):\n",
|
551 |
-
" plt.subplot(5,5,counter+1)\n",
|
552 |
" plt.xticks([])\n",
|
553 |
" plt.yticks([])\n",
|
554 |
" plt.grid(False)\n",
|
@@ -557,9 +564,9 @@
|
|
557 |
" plt.imshow(im)\n",
|
558 |
"\n",
|
559 |
" predict_proba = max(probas[idx])\n",
|
560 |
-
" predicted_class = np.argmax(probas[idx])
|
561 |
" plt.xlabel(f\"{SUB_FOLDERS[label]} ({SUB_FOLDERS[predicted_class]} {predict_proba:.2f})\")\n",
|
562 |
-
" counter +=1\n",
|
563 |
"plt.show()\n",
|
564 |
"\n"
|
565 |
]
|
@@ -573,11 +580,12 @@
|
|
573 |
"from pigeon import annotate\n",
|
574 |
"from PIL import Image\n",
|
575 |
"from IPython.display import display\n",
|
576 |
-
"
|
|
|
577 |
"annotations = annotate(\n",
|
578 |
-
"
|
579 |
-
"
|
580 |
-
"
|
581 |
")"
|
582 |
]
|
583 |
},
|
|
|
32 |
],
|
33 |
"source": [
|
34 |
"# List all file in data directory with Pathlib\n",
|
|
|
35 |
"import numpy as np\n",
|
|
|
|
|
|
|
|
|
36 |
"from tensorflow.keras.preprocessing import image\n",
|
37 |
"from tensorflow.keras.utils import img_to_array\n",
|
38 |
"\n",
|
39 |
+
"LABELS_DICT = {\"control\": 0, \"sick\": 1}\n",
|
40 |
"SUB_FOLDERS = [\"control\", \"sick\"]\n",
|
41 |
"\n",
|
42 |
+
"\n",
|
43 |
"def get_mouse_model(file_path):\n",
|
44 |
+
" file_name = file_path.split(\"/\")[-1]\n",
|
45 |
+
" if \"wt\" in file_name.lower():\n",
|
46 |
+
" return \"wt\"\n",
|
47 |
+
" elif \"bin1\" in file_name.lower():\n",
|
48 |
+
" return \"bin1\"\n",
|
49 |
+
" elif \"dnm2\" in file_name.lower():\n",
|
50 |
+
" return \"dnm2\"\n",
|
51 |
+
" else:\n",
|
52 |
+
" return \"unknown\"\n",
|
53 |
+
"\n",
|
54 |
"\n",
|
55 |
"def dirty_filter_file_names(file_name):\n",
|
56 |
" file_name = file_name.split(\"/\")[-1]\n",
|
|
|
61 |
" file_name = '_'.join(file_name.split(\"_\")[1:])\n",
|
62 |
" return file_name\n",
|
63 |
"\n",
|
64 |
+
"\n",
|
65 |
"def generate_dataset(folder, sub_folders=[\"control\", \"inter\", \"sick\"]):\n",
|
66 |
" n_elem = 0\n",
|
67 |
" for sub_folder in sub_folders:\n",
|
68 |
+
" n_elem += len(glob.glob(os.path.join(folder, sub_folder, \"*.tif\")))\n",
|
69 |
" images_array = np.empty(shape=(n_elem, 256, 256, 3), dtype=np.uint8)\n",
|
70 |
" path_array = []\n",
|
71 |
" mouse_model = []\n",
|
|
|
73 |
" labels_array = np.empty(shape=n_elem, dtype=np.uint8)\n",
|
74 |
" counter = 0\n",
|
75 |
" for index, sub_folder in enumerate(sub_folders):\n",
|
76 |
+
" path_files = os.path.join(folder, sub_folder, \"*.tif\")\n",
|
77 |
+
" for img in glob.glob(path_files):\n",
|
78 |
+
" im = img_to_array(image.load_img(img))\n",
|
79 |
+
" # im_resized = image.smart_resize(im, (256, 256))\n",
|
80 |
+
" path_array.append(img)\n",
|
81 |
+
" mouse_model.append(get_mouse_model(img))\n",
|
82 |
+
" mouse_model_full.append(dirty_filter_file_names(img))\n",
|
83 |
+
" images_array[counter] = tf.image.resize(im, (256, 256))\n",
|
84 |
+
" labels_array[counter] = index\n",
|
85 |
+
" counter += 1\n",
|
86 |
" return images_array, path_array, labels_array, mouse_model, mouse_model_full\n",
|
87 |
"\n",
|
88 |
+
"\n",
|
89 |
+
"img_data, all_files, labels, mouse_model, mouse_model_full = generate_dataset(\"data/all_images\",\n",
|
90 |
+
" sub_folders=SUB_FOLDERS)\n",
|
91 |
"file_dict = dict(\n",
|
92 |
" file=all_files,\n",
|
93 |
" label=labels,\n",
|
|
|
239 |
"# Load image embetter \n",
|
240 |
"import tensorflow as tf\n",
|
241 |
"import os\n",
|
242 |
+
"\n",
|
243 |
+
"MODEL_NAME = \"data/model.keras\"\n",
|
244 |
"model = tf.keras.models.load_model(MODEL_NAME)\n",
|
245 |
"emb_model = tf.keras.models.Sequential()\n",
|
246 |
"emb_model.add(model.get_layer('sequential'))\n",
|
247 |
+
"emb_model.add(tf.keras.models.Model(inputs=model.get_layer('resnet50v2').input,\n",
|
248 |
+
" outputs=model.get_layer('resnet50v2').get_layer('avg_pool').output))\n",
|
249 |
"embeddings = emb_model.predict(file_dict[\"image\"])\n",
|
250 |
"with open('data/results/embedding/image_embedding_custom.npy', 'wb') as f:\n",
|
251 |
" np.save(f, embeddings)"
|
|
|
270 |
"source": [
|
271 |
"from umap import UMAP\n",
|
272 |
"import numpy as np\n",
|
273 |
+
"\n",
|
274 |
"embeddings = np.load(open('data/results/embedding/image_embedding_custom.npy', 'rb'))\n",
|
275 |
"embedding_umap = UMAP().fit_transform(embeddings)\n",
|
276 |
"embedding_umap.shape"
|
|
|
294 |
],
|
295 |
"source": [
|
296 |
"import matplotlib.pyplot as plt\n",
|
297 |
+
"\n",
|
298 |
"cdict = {0: 'green', 1: 'red'}\n",
|
299 |
"\n",
|
300 |
"# Get the index of row from embedding_umap where the first column is greater than 0 and the second column is greater than 0\n",
|
301 |
"\n",
|
302 |
+
"x_condition2 = ((embedding_umap[:, 0] > 0) & (embedding_umap[:, 0] < 1))\n",
|
303 |
+
"y_condition2 = ((embedding_umap[:, 1] > 4.75) & (embedding_umap[:, 1] < 5.5))\n",
|
304 |
"idx_left_cluster = np.where((x_condition2 & y_condition2))[0]\n",
|
305 |
"\n",
|
306 |
+
"x_condition = ((embedding_umap[:, 0] > 4.75) & (embedding_umap[:, 0] < 5.75))\n",
|
307 |
+
"y_condition = ((embedding_umap[:, 1] > 4.5) & (embedding_umap[:, 1] < 5.25))\n",
|
308 |
"idx_right_cluster = np.where((x_condition & y_condition))[0]\n",
|
309 |
"\n",
|
310 |
+
"fig, ax = plt.subplots(1, 1, figsize=(10, 10))\n",
|
311 |
"for g in np.unique(labels):\n",
|
312 |
" ix = np.where(labels == g)\n",
|
313 |
+
" ax.scatter(embedding_umap[:, 0][ix],\n",
|
314 |
+
" embedding_umap[:, 1][ix],\n",
|
315 |
+
" s=0.3,\n",
|
316 |
+
" c=cdict[g],\n",
|
317 |
+
" label=g)\n",
|
318 |
"ax.legend()\n",
|
319 |
"plt.show()"
|
320 |
]
|
|
|
336 |
}
|
337 |
],
|
338 |
"source": [
|
339 |
+
"cdict_model_full = {'BIN1_KO_AAV_EMPTY_TAG': \"red\",\n",
|
340 |
+
" 'BIN1_KO_AAV_MTM1_TAD': \"blue\",\n",
|
341 |
+
" 'BIN1_WT_AAV_EMPTY_TAG': \"green\",\n",
|
342 |
+
" 'SDH_TAM_Bin1cKO_ko_pla': \"orange\",\n",
|
343 |
+
" 'SDH_TAM_Dnm2S619L_sl_pla': \"brown\",\n",
|
344 |
+
" 'SDH_TAM_Dnm2S619L_sl_tam': \"black\"}\n",
|
345 |
+
"fig, ax = plt.subplots(1, 1, figsize=(10, 10))\n",
|
346 |
"for g in np.unique(mouse_model_full):\n",
|
347 |
" numpy_mouse_model_full = np.array(mouse_model_full)\n",
|
348 |
" ix = np.where(numpy_mouse_model_full == g)\n",
|
349 |
+
" ax.scatter(embedding_umap[:, 0][ix],\n",
|
350 |
+
" embedding_umap[:, 1][ix],\n",
|
351 |
+
" s=0.3,\n",
|
352 |
+
" c=cdict_model_full[g],\n",
|
353 |
+
" label=g)\n",
|
354 |
"ax.legend()\n",
|
355 |
"plt.show()"
|
356 |
]
|
|
|
373 |
],
|
374 |
"source": [
|
375 |
"cdict_model = {\"wt\": 'green', \"bin1\": 'red', \"dnm2\": \"blue\", \"unknown\": \"black\"}\n",
|
376 |
+
"fig, ax = plt.subplots(1, 1, figsize=(10, 10))\n",
|
377 |
"for g in np.unique(mouse_model):\n",
|
378 |
" numpy_mouse_model = np.array(mouse_model)\n",
|
379 |
" ix = np.where(numpy_mouse_model == g)\n",
|
380 |
+
" ax.scatter(embedding_umap[:, 0][ix],\n",
|
381 |
+
" embedding_umap[:, 1][ix],\n",
|
382 |
+
" s=0.3,\n",
|
383 |
+
" c=cdict_model[g],\n",
|
384 |
+
" label=g)\n",
|
385 |
"ax.legend()\n",
|
386 |
"plt.show()"
|
387 |
]
|
|
|
406 |
],
|
407 |
"source": [
|
408 |
"from doubtlab.ensemble import DoubtEnsemble\n",
|
409 |
+
"from doubtlab.reason import ProbaReason, LongConfidenceReason, WrongPredictionReason, CleanlabReason\n",
|
410 |
+
"import pandas as pd\n",
|
411 |
"\n",
|
412 |
"# Let's precalculate the proba values.\n",
|
413 |
"probas = model.predict(img_data)\n",
|
|
|
424 |
"# This dataframe now contains the predicates\n",
|
425 |
"doubtlab_df = pd.DataFrame(predicate_dict)\n",
|
426 |
"# Create a new column with 1 if the previous predicates are true else 0\n",
|
427 |
+
"doubtlab_df['doubt'] = doubtlab_df[[\"proba\", \"long\", \"wrong\", \"cleanlab\"]].ne(0).any(axis=1)\n",
|
428 |
"wrong_strong_idx = doubtlab_df[doubtlab_df[\"long\"] == 1.0].index\n",
|
429 |
"wrong_idx = doubtlab_df[doubtlab_df[\"wrong\"] == 1.0].index\n",
|
430 |
"low_idx = doubtlab_df[doubtlab_df[\"proba\"] == 1.0].index\n",
|
431 |
"cleanlab_idx = doubtlab_df[doubtlab_df[\"cleanlab\"] == 1.0].index\n",
|
432 |
"doubt_idx = doubtlab_df[doubtlab_df[\"doubt\"] == True].index\n",
|
433 |
+
"print(\n",
|
434 |
+
" f\"Total Number of images with wrong strong classficiation: {len(wrong_strong_idx)} ({round(len(wrong_strong_idx) / len(doubtlab_df) * 100, 2)}%)\")\n",
|
435 |
+
"print(f\"Total Number of images with wrong: {len(wrong_idx)} ({round(len(wrong_idx) / len(doubtlab_df) * 100, 2)}%)\")\n",
|
436 |
+
"print(f\"Total Number of images with low probas: {len(low_idx)} ({round(len(low_idx) / len(doubtlab_df) * 100, 2)}%)\")\n",
|
437 |
+
"print(\n",
|
438 |
+
" f\"Total Number of images with cleanlab: {len(cleanlab_idx)} ({round(len(cleanlab_idx) / len(doubtlab_df) * 100, 2)}%)\")\n",
|
439 |
+
"print(f\"Total Number of doubts images: {len(doubt_idx)} ({round(len(doubt_idx) / len(doubtlab_df) * 100, 2)}%)\")"
|
440 |
]
|
441 |
},
|
442 |
{
|
|
|
464 |
],
|
465 |
"source": [
|
466 |
"wrong_strong_idx = doubtlab_df[doubtlab_df[\"long\"] == 1.0].index\n",
|
467 |
+
"print(\n",
|
468 |
+
" f\"Total Number of images with wrong strong classficiation: {len(wrong_strong_idx)} ({round(len(wrong_strong_idx) / len(doubtlab_df) * 100, 2)}%)\")\n",
|
469 |
"SUB_FOLDERS = [\"control\", \"sick\"]\n",
|
470 |
"counter = 0\n",
|
471 |
+
"plt.figure(figsize=(10, 10))\n",
|
472 |
"for idx in np.random.choice(wrong_strong_idx, 25, replace=False):\n",
|
473 |
+
" plt.subplot(5, 5, counter + 1)\n",
|
474 |
" plt.xticks([])\n",
|
475 |
" plt.yticks([])\n",
|
476 |
" plt.grid(False)\n",
|
|
|
479 |
" plt.imshow(im)\n",
|
480 |
"\n",
|
481 |
" predict_proba = max(probas[idx])\n",
|
482 |
+
" predicted_class = np.argmax(probas[idx])\n",
|
483 |
" plt.xlabel(f\"{SUB_FOLDERS[label]} ({SUB_FOLDERS[predicted_class]} {predict_proba:.2f})\")\n",
|
484 |
+
" counter += 1\n",
|
485 |
"plt.show()\n",
|
486 |
"\n"
|
487 |
]
|
|
|
493 |
"outputs": [],
|
494 |
"source": [
|
495 |
"wrong_idx = doubtlab_df[doubtlab_df[\"wrong\"] == 1.0].index\n",
|
496 |
+
"print(f\"Total Number of images with wrong: {len(wrong_idx)} ({round(len(wrong_idx) / len(doubtlab_df) * 100, 2)}%)\")\n",
|
497 |
"SUB_FOLDERS = [\"control\", \"sick\"]\n",
|
498 |
"counter = 0\n",
|
499 |
+
"plt.figure(figsize=(10, 10))\n",
|
500 |
"for idx in np.random.choice(wrong_idx, 25, replace=False):\n",
|
501 |
+
" plt.subplot(5, 5, counter + 1)\n",
|
502 |
" plt.xticks([])\n",
|
503 |
" plt.yticks([])\n",
|
504 |
" plt.grid(False)\n",
|
|
|
507 |
" plt.imshow(im)\n",
|
508 |
"\n",
|
509 |
" predict_proba = max(probas[idx])\n",
|
510 |
+
" predicted_class = np.argmax(probas[idx])\n",
|
511 |
" plt.xlabel(f\"{SUB_FOLDERS[label]} ({SUB_FOLDERS[predicted_class]} {predict_proba:.2f})\")\n",
|
512 |
+
" counter += 1\n",
|
513 |
"plt.show()\n",
|
514 |
"\n"
|
515 |
]
|
|
|
521 |
"outputs": [],
|
522 |
"source": [
|
523 |
"low_idx = doubtlab_df[doubtlab_df[\"proba\"] == 1.0].index\n",
|
524 |
+
"print(f\"Total Number of images with low probas: {len(low_idx)} ({round(len(low_idx) / len(doubtlab_df) * 100, 2)}%)\")\n",
|
525 |
"SUB_FOLDERS = [\"control\", \"sick\"]\n",
|
526 |
"counter = 0\n",
|
527 |
+
"plt.figure(figsize=(10, 10))\n",
|
528 |
"for idx in np.random.choice(low_idx, 25, replace=False):\n",
|
529 |
+
" plt.subplot(5, 5, counter + 1)\n",
|
530 |
" plt.xticks([])\n",
|
531 |
" plt.yticks([])\n",
|
532 |
" plt.grid(False)\n",
|
|
|
535 |
" plt.imshow(im)\n",
|
536 |
"\n",
|
537 |
" predict_proba = max(probas[idx])\n",
|
538 |
+
" predicted_class = np.argmax(probas[idx])\n",
|
539 |
" plt.xlabel(f\"{SUB_FOLDERS[label]} ({SUB_FOLDERS[predicted_class]} {predict_proba:.2f})\")\n",
|
540 |
+
" counter += 1\n",
|
541 |
"plt.show()\n",
|
542 |
"\n"
|
543 |
]
|
|
|
549 |
"outputs": [],
|
550 |
"source": [
|
551 |
"cleanlab_idx = doubtlab_df[doubtlab_df[\"cleanlab\"] == 1.0].index\n",
|
552 |
+
"print(\n",
|
553 |
+
" f\"Total Number of images with cleanlab: {len(cleanlab_idx)} ({round(len(cleanlab_idx) / len(doubtlab_df) * 100, 2)}%)\")\n",
|
554 |
"SUB_FOLDERS = [\"control\", \"sick\"]\n",
|
555 |
"counter = 0\n",
|
556 |
+
"plt.figure(figsize=(10, 10))\n",
|
557 |
"for idx in np.random.choice(cleanlab_idx, 25, replace=False):\n",
|
558 |
+
" plt.subplot(5, 5, counter + 1)\n",
|
559 |
" plt.xticks([])\n",
|
560 |
" plt.yticks([])\n",
|
561 |
" plt.grid(False)\n",
|
|
|
564 |
" plt.imshow(im)\n",
|
565 |
"\n",
|
566 |
" predict_proba = max(probas[idx])\n",
|
567 |
+
" predicted_class = np.argmax(probas[idx])\n",
|
568 |
" plt.xlabel(f\"{SUB_FOLDERS[label]} ({SUB_FOLDERS[predicted_class]} {predict_proba:.2f})\")\n",
|
569 |
+
" counter += 1\n",
|
570 |
"plt.show()\n",
|
571 |
"\n"
|
572 |
]
|
|
|
580 |
"from pigeon import annotate\n",
|
581 |
"from PIL import Image\n",
|
582 |
"from IPython.display import display\n",
|
583 |
+
"\n",
|
584 |
+
"re_annotated_img_files = [all_files[i] for i in cleanlab_idx]\n",
|
585 |
"annotations = annotate(\n",
|
586 |
+
" re_annotated_img_files,\n",
|
587 |
+
" options=[\"control\", \"sick\", \"unsure\"],\n",
|
588 |
+
" display_fn=lambda filename: display(Image.open(filename, 'r'))\n",
|
589 |
")"
|
590 |
]
|
591 |
},
|
uv.lock
ADDED
The diff for this file is too large to render.
See raw diff
|
|