-
Notifications
You must be signed in to change notification settings - Fork 1
/
functions.py
6447 lines (4532 loc) · 269 KB
/
functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import numpy as np
import cv2
import io
import contextlib
import tensorflow as tf
import tensorflow_addons as tfa
from tensorflow.keras.preprocessing.image import load_img, img_to_array
from tensorflow.keras.utils import to_categorical
import configparser
import random
import shutil
import gc
import csv
import math
import pandas as pd
from tqdm import tqdm
config = configparser.ConfigParser()
config.read(os.path.join('config.ini'))
SEED = int(config['DEFAULT']['SEED'])
BATCH_SIZE = int(config['DEFAULT']['BATCH_SIZE'])
LR = float(config['DEFAULT']['LR'])
WD = float(config['DEFAULT']['WD'])
THRESHOLD = float(config['DEFAULT']['THRESHOLD'])
NUM_EPOCHS = int(config['DEFAULT']['NUM_EPOCHS'])
NUM_EPOCHS_CS = int(config['DEFAULT']['NUM_EPOCHS_CS'])
def rmse(y_true, y_pred):
return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true)))
def delta_metric(threshold=1.25):
def metric(y_true, y_pred):
ratio_1 = y_pred / y_true
ratio_2 = y_true / y_pred
max_ratio = tf.maximum(ratio_1, ratio_2)
return tf.reduce_mean(tf.cast(max_ratio < threshold, tf.float32))
metric.__name__ = f'delta_{threshold}'
return metric
class MeanIoU(tf.keras.metrics.Metric):
'''
This class represents a Mean Intersection over Union (IoU) metric for evaluating segmentation models.
The Mean IoU is a common evaluation metric for semantic image segmentation, which calculates the mean of IoU scores over multiple classes.
Attributes:
num_classes (int): The number of classes in the segmentation task.
Methods:
compute_iou: Computes the IoU between the ground truth and predicted masks for a single class.
update_state: Updates the state of the metric with new predictions and ground truths.
result: Returns the current value of the metric.
reset_state: Resets all state variables of the metric.
get_config: Returns the configuration of the metric.
from_config: Creates a new instance from the given configuration.
'''
def __init__(self, num_classes, **kwargs):
super(MeanIoU, self).__init__(**kwargs)
self.num_classes = num_classes
self.total_iou = self.add_weight(name="total_iou", initializer="zeros")
self.count = self.add_weight(name="count", initializer="zeros")
def compute_iou(self, y_true, y_pred):
y_true_f = tf.reshape(y_true, [-1])
y_pred_f = tf.reshape(y_pred, [-1])
intersection = tf.reduce_sum(y_true_f * y_pred_f)
union = tf.reduce_sum(y_true_f) + tf.reduce_sum(y_pred_f) - intersection
return intersection / union
def update_state(self, y_true, y_pred, sample_weight=None):
iou_values = [self.compute_iou(y_true[:,:,:,k], y_pred[:,:,:,k]) for k in range(self.num_classes)]
mean_iou_val = tf.reduce_mean(iou_values)
self.total_iou.assign_add(mean_iou_val)
self.count.assign_add(1.0)
def result(self):
return self.total_iou / self.count
def reset_state(self):
self.total_iou.assign(0.0)
self.count.assign(0.0)
def get_config(self):
config = super(MeanIoU, self).get_config()
config.update({'num_classes': self.num_classes})
return config
@classmethod
def from_config(cls, config):
return cls(**config)
class ignore_im_categorical_crossentropy(tf.keras.losses.Loss):
'''
This class is a custom loss function for categorical cross-entropy that ignores the inconsistency mask.
Methods:
call: Calculates the loss, ignoring the IM class.
'''
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.cce = tf.keras.losses.CategoricalCrossentropy(reduction=tf.keras.losses.Reduction.NONE)
def call(self, y_true, y_pred):
loss = self.cce(y_true, y_pred)
# Create a mask to remove the loss for class 0
mask = 1. - y_true[:, 0]
loss *= mask
return tf.reduce_mean(loss)
class ignore_im_dice_loss_multiclass(tf.keras.losses.Loss):
'''
This class is a custom loss function that ignores the contribution of the inconsistency mask.
Assumes that the segmentation masks are given in one-hot encoded format.
Args:
y_true: Tensor of true masks.
y_pred: Tensor of predicted masks.
Returns:
Tensor of the computed Dice loss.
'''
def call(self, y_true, y_pred):
# Remove contribution of class 0
y_true = y_true[:, :, 1:]
y_pred = y_pred[:, :, 1:]
# Intersection of the two sets
intersection = tf.reduce_sum(y_true * y_pred, axis=[1, 2])
# Size of each set
size_true = tf.reduce_sum(y_true, axis=[1, 2])
size_pred = tf.reduce_sum(y_pred, axis=[1, 2])
# Compute Dice loss
dice_coefficient = (2. * intersection + 1e-7) / (size_true + size_pred + 1e-7)
dice_loss = 1 - dice_coefficient
return tf.reduce_mean(dice_loss)
def dice_loss(y_true, y_pred, smooth=1):
'''
Compute the Dice Loss for binary segmentation tasks.
Args:
y_true (tf.Tensor): Ground truth segmentation masks, shape (batch_size, height, width, 1).
y_pred (tf.Tensor): Predicted segmentation masks, shape (batch_size, height, width, 1).
smooth (float, optional): Smoothing factor to prevent division by zero. Defaults to 1.
Returns:
tf.Tensor: Dice loss value.
'''
y_true = tf.cast(y_true, dtype=tf.float32)
y_pred = tf.cast(y_pred, dtype=tf.float32)
intersection = tf.reduce_sum(y_true * y_pred, axis=[1, 2, 3])
union = tf.reduce_sum(y_true, axis=[1, 2, 3]) + tf.reduce_sum(y_pred, axis=[1, 2, 3])
dice_coeff = (2 * intersection + smooth) / (union + smooth)
dice_loss = 1 - tf.reduce_mean(dice_coeff)
return dice_loss
def train_ISIC_2018(train_images_dir,
val_images_dir,
val_masks_dir,
test_images_dir,
test_masks_dir,
unlabeled_images_dir,
unlabeled_masks_dir,
modelname,
filepath_h5,
model,
loss_func,
steps_per_epoch,
h, w, c,
val_pred_dir,
test_pred_dir,
unlabeled_pred_dir,
print_results=False):
train_images_path = os.path.join(train_images_dir, '*.png')
train_dataset = tf.data.Dataset.list_files(train_images_path, seed=SEED)
train_dataset = train_dataset.map(parse_image_ISIC_2018).batch(BATCH_SIZE).repeat().prefetch(tf.data.AUTOTUNE)
val_images_path = os.path.join(val_images_dir, '*.png')
val_dataset = tf.data.Dataset.list_files(val_images_path, seed=SEED)
val_dataset = val_dataset.map(parse_image_ISIC_2018).batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)
opt = tfa.optimizers.AdamW(learning_rate=LR, weight_decay=WD)
model.compile(optimizer=opt, loss=loss_func, metrics=[dice_loss, tf.keras.metrics.BinaryIoU(target_class_ids=[1], threshold=0.5)])
callbacks = [tf.keras.callbacks.ModelCheckpoint(filepath_h5, verbose=1, save_best_only=True, monitor='val_binary_io_u', mode='max')]
model.fit(train_dataset, epochs=NUM_EPOCHS, steps_per_epoch=steps_per_epoch, callbacks=callbacks, validation_data=val_dataset)
best_model = tf.keras.models.load_model(filepath_h5, custom_objects={'dice_loss': dice_loss})
mIoU_val, dice_score_val = benchmark_ISIC2018(best_model, val_images_dir, val_masks_dir, val_pred_dir, h, w, c, print_results=print_results)
mIoU_test, dice_score_test = benchmark_ISIC2018(best_model, test_images_dir, test_masks_dir, test_pred_dir, h, w, c, print_results=print_results)
mIoU_train_unlabeled, dice_score_train_unlabeled = benchmark_ISIC2018(best_model, unlabeled_images_dir, unlabeled_masks_dir, unlabeled_pred_dir, h, w, c, print_results=print_results)
print(f'{modelname} mIoU_val: {mIoU_val}')
return mIoU_val, mIoU_test, mIoU_train_unlabeled, dice_score_val, dice_score_test, dice_score_train_unlabeled
def train_hela(train_images_dir,
val_images_dir,
val_gt_dir,
test_gt_dir,
unlabeled_gt_dir,
modelname,
filepath_h5,
model,
loss_func,
steps_per_epoch,
h, w, c,
val_pred_dir,
test_pred_dir,
unlabeled_pred_dir):
train_images_path = os.path.join(train_images_dir, '*.png')
train_dataset = tf.data.Dataset.list_files(train_images_path, seed=SEED)
train_dataset = train_dataset.map(parse_image_hela).batch(BATCH_SIZE).repeat().prefetch(tf.data.AUTOTUNE)
val_images_path = os.path.join(val_images_dir, '*.png')
val_dataset = tf.data.Dataset.list_files(val_images_path, seed=SEED)
val_dataset = val_dataset.map(parse_image_hela).batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)
opt = tfa.optimizers.AdamW(learning_rate=LR, weight_decay=WD)
model.compile(optimizer=opt, loss=loss_func)#, metrics=['acc', MeanIoU(num_classes=n_classes)]) val_mean_io_u
callbacks = [tf.keras.callbacks.ModelCheckpoint(filepath_h5, verbose=1, save_best_only=True, monitor='val_loss', mode='min')]
model.fit(train_dataset, epochs=NUM_EPOCHS, steps_per_epoch=steps_per_epoch, callbacks=callbacks, validation_data=val_dataset)
best_model = tf.keras.models.load_model(filepath_h5)
mIoU_val, mIoU_ad_val, mean_cell_count_error_val = benchmark_hela(best_model, val_gt_dir, val_pred_dir, h, w, c)
mIoU_test, mIoU_ad_test, mean_cell_count_error_test = benchmark_hela(best_model, test_gt_dir, test_pred_dir, h, w, c)
mIoU_unlabeled, mIoU_ad_unlabeled, mean_cell_count_error_unlabeled = benchmark_hela(best_model, unlabeled_gt_dir, unlabeled_pred_dir, h, w, c)
print(f'{modelname} mIoU_val: {mIoU_val} mean_cell_count_error_val: {mean_cell_count_error_val}')
return mIoU_val, mIoU_ad_val, mean_cell_count_error_val, mIoU_test, mIoU_ad_test, mean_cell_count_error_test, mIoU_unlabeled, mIoU_ad_unlabeled, mean_cell_count_error_unlabeled
def train_multiclass(train_images_dir,
val_images_dir,
val_masks_dir,
test_images_dir,
test_masks_dir,
unlabeled_images_dir,
unlabeled_masks_dir,
modelname,
filepath_h5,
model,
loss_func,
steps_per_epoch,
h, w, c,
n_classes,
class_to_color_mapping,
val_pred_dir,
test_pred_dir,
unlabeled_pred_dir,
print_results=False):
train_images_path = os.path.join(train_images_dir, '*.png')
train_dataset = tf.data.Dataset.list_files(train_images_path, seed=SEED)
train_dataset = train_dataset.map(lambda x: parse_image_multiclass(x, n_classes=n_classes, image_channels=3)).batch(BATCH_SIZE).repeat().prefetch(tf.data.AUTOTUNE)
val_images_path = os.path.join(val_images_dir, '*.png')
val_dataset = tf.data.Dataset.list_files(val_images_path, seed=SEED)
val_dataset = val_dataset.map(lambda x: parse_image_multiclass(x, n_classes=n_classes, image_channels=3)).batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)
opt = tfa.optimizers.AdamW(learning_rate=LR, weight_decay=WD)
model.compile(optimizer=opt, loss=loss_func, metrics=['acc', MeanIoU(num_classes=n_classes)])
callbacks = [tf.keras.callbacks.ModelCheckpoint(filepath_h5, verbose=1, save_best_only=True, monitor='val_mean_io_u', mode='max')]
model.fit(train_dataset, epochs=NUM_EPOCHS, steps_per_epoch=steps_per_epoch, callbacks=callbacks, validation_data=val_dataset)
best_model = tf.keras.models.load_model(filepath_h5, custom_objects={'MeanIoU': MeanIoU})
mPA_val, mIoU_val = benchmark_multiclass(best_model, val_images_dir, val_masks_dir, val_pred_dir, h, w, c, class_to_color_mapping, print_results=print_results)
mPA_test, mIoU_test = benchmark_multiclass(best_model, test_images_dir, test_masks_dir, test_pred_dir, h, w, c, class_to_color_mapping, print_results=print_results)
mPA_train_unlabeled, mIoU_train_unlabeled = benchmark_multiclass(best_model, unlabeled_images_dir, unlabeled_masks_dir, unlabeled_pred_dir, h, w, c, class_to_color_mapping, print_results=print_results)
print(f'{modelname} mIoU_val: {mIoU_val}')
return mPA_val, mPA_test, mPA_train_unlabeled, mIoU_val, mIoU_test, mIoU_train_unlabeled
def train_depth_map(train_images_dir,
val_images_dir,
test_images_dir,
unlabeled_images_dir,
modelname,
filepath_h5,
model,
loss_func,
steps_per_epoch,
val_pred_dir,
test_pred_dir,
unlabeled_pred_dir):
train_images_path = os.path.join(train_images_dir, '*.png')
train_dataset = tf.data.Dataset.list_files(train_images_path, seed=SEED)
train_dataset = train_dataset.map(parse_image_depth_map).batch(BATCH_SIZE).repeat().prefetch(tf.data.AUTOTUNE)
val_images_path = os.path.join(val_images_dir, '*.png')
val_dataset = tf.data.Dataset.list_files(val_images_path, seed=SEED)
val_dataset = val_dataset.map(parse_image_depth_map).batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)
opt = tfa.optimizers.AdamW(learning_rate=LR, weight_decay=WD)
model.compile(optimizer=opt, loss=loss_func, metrics=['mse', delta_metric(1.25)])
callbacks = [tf.keras.callbacks.ModelCheckpoint(filepath_h5, verbose=1, save_best_only=True, monitor='val_loss', mode='min')]
model.fit(train_dataset, epochs=NUM_EPOCHS, steps_per_epoch=steps_per_epoch, callbacks=callbacks, validation_data=val_dataset)
best_model = tf.keras.models.load_model(filepath_h5, custom_objects={'rmse': rmse, 'delta_1.25': delta_metric(1.25)})
test_images_path = os.path.join(test_images_dir, '*.png')
test_dataset = tf.data.Dataset.list_files(test_images_path, seed=SEED)
test_dataset = test_dataset.map(parse_image_depth_map).batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)
unlabeled_images_path = os.path.join(unlabeled_images_dir, '*.png')
unlabeled_dataset = tf.data.Dataset.list_files(unlabeled_images_path, seed=SEED)
unlabeled_dataset = unlabeled_dataset.map(parse_image_depth_map).batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)
rmse_val, mse_val = benchmark_depth_map(best_model, val_dataset, val_images_dir, val_pred_dir)
rmse_test, mse_test = benchmark_depth_map(best_model, test_dataset, test_images_dir, test_pred_dir)
rmse_unlabeled, mse_unlabeled = benchmark_depth_map(best_model, unlabeled_dataset, unlabeled_images_dir, unlabeled_pred_dir)
print(f'{modelname} rmse_val: {rmse_val}')
return rmse_val, rmse_test, rmse_unlabeled, mse_val, mse_test, mse_unlabeled
def train_ISIC_2018_consistency_loss(train_images_dir,
train_masks_dir,
val_images_dir,
val_masks_dir,
test_images_dir,
test_masks_dir,
unlabeled_images_dir,
unlabeled_masks_dir,
modelname,
filepath_h5,
model,
loss_func,
h, w, c,
val_pred_dir,
test_pred_dir,
unlabeled_pred_dir,
max_blur, max_noise, brightness_range_alpha, brightness_range_beta,
validation_frequency=1
):
labeled_images, labeled_masks = load_labeled_data_single_mask(train_images_dir, train_masks_dir)
unlabeled_images = load_unlabeled_images(unlabeled_images_dir)
validation_images, validation_masks = load_labeled_data_single_mask(val_images_dir, val_masks_dir)
opt = tfa.optimizers.AdamW(learning_rate=LR, weight_decay=WD)
model.compile(optimizer=opt, loss=loss_func) #, metrics=[dice_loss]
current_validation_loss = 100
for epoch in range(NUM_EPOCHS_CS):
# Shuffle the data
labeled_indices = np.random.permutation(len(labeled_images))
unlabeled_indices = np.random.permutation(len(unlabeled_images))
# Create batches for labeled and unlabeled data
num_labeled_batches = int(np.ceil(len(labeled_images) / BATCH_SIZE))
num_unlabeled_batches = int(np.ceil(len(unlabeled_images) / BATCH_SIZE))
# Iterate through labeled data batches
for batch_idx in range(num_labeled_batches):
batch_start = batch_idx * BATCH_SIZE
batch_end = (batch_idx + 1) * BATCH_SIZE
batch_indices = labeled_indices[batch_start:batch_end]
batch_labeled_images = labeled_images[batch_indices]
batch_labeled_masks = labeled_masks[batch_indices]
model.train_on_batch(batch_labeled_images, batch_labeled_masks)
if epoch % validation_frequency == 0:
validation_loss = model.evaluate(validation_images, validation_masks)
print(f'Epoch: {epoch}, Validation Loss: {round(validation_loss,4)} after labeled training')
if validation_loss < current_validation_loss:
current_validation_loss = validation_loss
print(f' -------------------------- Model saved with val_loss {round(validation_loss,4)}')
model.save(filepath_h5)
# Iterate through unlabeled data batches
for batch_idx in range(num_unlabeled_batches):
batch_start = batch_idx * BATCH_SIZE
batch_end = (batch_idx + 1) * BATCH_SIZE
batch_indices = unlabeled_indices[batch_start:batch_end]
batch_unlabeled_images = unlabeled_images[batch_indices]
batch_unlabeled_images_rotated_flipped = np.array([apply_random_flip_and_rotation(image) for image in batch_unlabeled_images])
augmented_unlabeled_images_1 = np.array([data_augmentation_image2tensor(image, max_blur, max_noise, brightness_range_alpha, brightness_range_beta ) for image in batch_unlabeled_images_rotated_flipped])
augmented_unlabeled_images_2 = np.array([data_augmentation_image2tensor(image, max_blur, max_noise, brightness_range_alpha, brightness_range_beta ) for image in batch_unlabeled_images_rotated_flipped])
with tf.GradientTape() as tape:
predictions_1 = model(augmented_unlabeled_images_1, training=True)
predictions_2 = model(augmented_unlabeled_images_2, training=True)
consistency_loss = tf.reduce_mean(tf.keras.losses.mean_squared_error(predictions_1, predictions_2))
current_weights = model.trainable_variables
gradients = tape.gradient(consistency_loss, current_weights)
opt.apply_gradients(zip(gradients, current_weights))
# Evaluate the model on the validation set (optional)
if epoch % validation_frequency == 0:
validation_loss = model.evaluate(validation_images, validation_masks)
print(f'Epoch: {epoch}, Validation Loss: {round(validation_loss,4)} after unlabeled training')
if validation_loss < current_validation_loss:
current_validation_loss = validation_loss
print(f' -------------------------- Model saved with val_loss {round(validation_loss,4)}')
model.save(filepath_h5)
best_model = tf.keras.models.load_model(filepath_h5, custom_objects={'dice_loss': dice_loss})
mIoU_val, dice_score_val = benchmark_ISIC2018(best_model, val_images_dir, val_masks_dir, val_pred_dir, h, w, c)
mIoU_test, dice_score_test = benchmark_ISIC2018(best_model, test_images_dir, test_masks_dir, test_pred_dir, h, w, c)
mIoU_train_unlabeled, dice_score_train_unlabeled = benchmark_ISIC2018(best_model, unlabeled_images_dir, unlabeled_masks_dir, unlabeled_pred_dir, h, w, c)
print(f'{modelname} mIoU_val: {mIoU_val}')
return mIoU_val, mIoU_test, mIoU_train_unlabeled, dice_score_val, dice_score_test, dice_score_train_unlabeled
def train_hela_consistency_loss(train_main_dir,
val_main_dir,
test_main_dir,
unlabeled_main_dir,
modelname,
filepath_h5,
model,
loss_func,
h, w, c,
val_pred_dir,
test_pred_dir,
unlabeled_pred_dir,
max_blur, max_noise, brightness_range_alpha, brightness_range_beta,
validation_frequency=1):
labeled_images, labeled_masks_alive, labeled_masks_dead, labeled_masks_pos = load_images_and_masks_hela(train_main_dir)
unlabeled_images = load_unlabeled_images_hela(os.path.join(unlabeled_main_dir, 'brightfield'))
validation_images, validation_binary_masks_alive, validation_binary_masks_dead, validation_binary_masks_pos = load_images_and_masks_hela(val_main_dir)
validation_binary_masks_alive = np.expand_dims(validation_binary_masks_alive, axis=-1)
validation_binary_masks_dead = np.expand_dims(validation_binary_masks_dead, axis=-1)
validation_binary_masks_pos = np.expand_dims(validation_binary_masks_pos, axis=-1)
validation_masks = np.concatenate([validation_binary_masks_alive, validation_binary_masks_dead, validation_binary_masks_pos], axis=-1)
opt = tfa.optimizers.AdamW(learning_rate=LR, weight_decay=WD)
model.compile(optimizer=opt, loss=loss_func) #, metrics=[dice_loss]
current_validation_loss = 100
for epoch in range(NUM_EPOCHS_CS):
# Shuffle the data
labeled_indices = np.random.permutation(len(labeled_images))
unlabeled_indices = np.random.permutation(len(unlabeled_images))
# Create batches for labeled and unlabeled data
num_labeled_batches = int(np.ceil(len(labeled_images) / BATCH_SIZE))
num_unlabeled_batches = int(np.ceil(len(unlabeled_images) / BATCH_SIZE))
# Iterate through labeled data batches
for batch_idx in range(num_labeled_batches):
batch_start = batch_idx * BATCH_SIZE
batch_end = (batch_idx + 1) * BATCH_SIZE
batch_indices = labeled_indices[batch_start:batch_end]
batch_labeled_images = labeled_images[batch_indices]
batch_labeled_masks_alive = labeled_masks_alive[batch_indices]
batch_labeled_masks_dead = labeled_masks_dead[batch_indices]
batch_labeled_masks_pos = labeled_masks_pos[batch_indices]
batch_labeled_masks_alive = np.expand_dims(batch_labeled_masks_alive, axis=-1)
batch_labeled_masks_dead = np.expand_dims(batch_labeled_masks_dead, axis=-1)
batch_labeled_masks_pos = np.expand_dims(batch_labeled_masks_pos, axis=-1)
batch_labeled_masks = np.concatenate([batch_labeled_masks_alive, batch_labeled_masks_dead, batch_labeled_masks_pos], axis=-1)
model.train_on_batch(batch_labeled_images, batch_labeled_masks)
if epoch % validation_frequency == 0:
validation_loss = model.evaluate(validation_images, validation_masks)
print(f'Epoch: {epoch}, Validation Loss: {round(validation_loss,4)} after labeled training')
if validation_loss < current_validation_loss:
current_validation_loss = validation_loss
print(f' -------------------------- Model saved with val_loss {round(validation_loss,4)}')
model.save(filepath_h5)
# Iterate through unlabeled data batches
for batch_idx in range(num_unlabeled_batches):
batch_start = batch_idx * BATCH_SIZE
batch_end = (batch_idx + 1) * BATCH_SIZE
batch_indices = unlabeled_indices[batch_start:batch_end]
batch_unlabeled_images = unlabeled_images[batch_indices]
batch_unlabeled_images_rotated_flipped = np.array([apply_random_flip_and_rotation(image) for image in batch_unlabeled_images])
augmented_unlabeled_images_1 = np.array([data_augmentation_image2tensor(image, max_blur, max_noise, brightness_range_alpha, brightness_range_beta) for image in batch_unlabeled_images_rotated_flipped])
augmented_unlabeled_images_2 = np.array([data_augmentation_image2tensor(image, max_blur, max_noise, brightness_range_alpha, brightness_range_beta) for image in batch_unlabeled_images_rotated_flipped])
with tf.GradientTape() as tape:
predictions_1 = model(augmented_unlabeled_images_1, training=True)
predictions_2 = model(augmented_unlabeled_images_2, training=True)
consistency_loss = tf.reduce_mean(tf.keras.losses.mean_squared_error(predictions_1, predictions_2))
current_weights = model.trainable_variables
gradients = tape.gradient(consistency_loss, current_weights)
opt.apply_gradients(zip(gradients, current_weights))
# Evaluate the model on the validation set (optional)
if epoch % validation_frequency == 0:
validation_loss = model.evaluate(validation_images, validation_masks)
print(f'Epoch: {epoch}, Validation Loss: {round(validation_loss,4)} after unlabeled training')
if validation_loss < current_validation_loss:
current_validation_loss = validation_loss
print(f' -------------------------- Model saved with val_loss {round(validation_loss,4)}')
model.save(filepath_h5)
best_model = tf.keras.models.load_model(filepath_h5)
mIoU_val, mIoU_ad_val, mean_cell_count_error_val = benchmark_hela(best_model, val_main_dir, val_pred_dir, h, w, c)
mIoU_test, mIoU_ad_test, mean_cell_count_error_test = benchmark_hela(best_model, test_main_dir, test_pred_dir, h, w, c)
mIoU_unlabeled, mIoU_ad_unlabeled, mean_cell_count_error_unlabeled = benchmark_hela(best_model, unlabeled_main_dir, unlabeled_pred_dir, h, w, c)
print(f'{modelname} mIoU_val: {mIoU_val} mean_cell_count_error_val: {mean_cell_count_error_val}')
return mIoU_val, mIoU_ad_val, mean_cell_count_error_val, mIoU_test, mIoU_ad_test, mean_cell_count_error_test, mIoU_unlabeled, mIoU_ad_unlabeled, mean_cell_count_error_unlabeled
def train_multiclass_consistency_loss(train_images_dir,
train_masks_dir,
val_images_dir,
val_masks_dir,
test_images_dir,
test_masks_dir,
unlabeled_images_dir,
unlabeled_masks_dir,
modelname,
filepath_h5,
model,
loss_func,
h, w, c,
n_classes,
class_to_color_mapping,
val_pred_dir,
test_pred_dir,
unlabeled_pred_dir,
max_blur, max_noise, brightness_range_alpha, brightness_range_beta,
validation_frequency=1,
print_results=False):
labeled_images, labeled_masks = load_labeled_data_multiclass_mask(train_images_dir, train_masks_dir, n_classes)
unlabeled_images = load_unlabeled_images(unlabeled_images_dir)
validation_images, validation_masks = load_labeled_data_multiclass_mask(val_images_dir, val_masks_dir, n_classes)
opt = tfa.optimizers.AdamW(learning_rate=LR, weight_decay=WD)
model.compile(optimizer=opt, loss=loss_func) #, metrics=[dice_loss]
current_validation_loss = 100
for epoch in range(NUM_EPOCHS_CS):
# Shuffle the data
labeled_indices = np.random.permutation(len(labeled_images))
unlabeled_indices = np.random.permutation(len(unlabeled_images))
# Create batches for labeled and unlabeled data
num_labeled_batches = int(np.ceil(len(labeled_images) / BATCH_SIZE))
num_unlabeled_batches = int(np.ceil(len(unlabeled_images) / BATCH_SIZE))
# Iterate through labeled data batches
for batch_idx in range(num_labeled_batches):
batch_start = batch_idx * BATCH_SIZE
batch_end = (batch_idx + 1) * BATCH_SIZE
batch_indices = labeled_indices[batch_start:batch_end]
batch_labeled_images = labeled_images[batch_indices]
batch_labeled_masks = labeled_masks[batch_indices]
model.train_on_batch(batch_labeled_images, batch_labeled_masks)
if epoch % validation_frequency == 0:
validation_loss = model.evaluate(validation_images, validation_masks)
print(f'Epoch: {epoch}, Validation Loss: {round(validation_loss,4)} after labeled training')
if validation_loss < current_validation_loss:
current_validation_loss = validation_loss
print(f' -------------------------- Model saved with val_loss {round(validation_loss,4)}')
model.save(filepath_h5)
# Iterate through unlabeled data batches
for batch_idx in range(num_unlabeled_batches):
batch_start = batch_idx * BATCH_SIZE
batch_end = (batch_idx + 1) * BATCH_SIZE
batch_indices = unlabeled_indices[batch_start:batch_end]
batch_unlabeled_images = unlabeled_images[batch_indices]
augmented_unlabeled_images_1 = np.array([data_augmentation_image2tensor(image, max_blur, max_noise, brightness_range_alpha, brightness_range_beta) for image in batch_unlabeled_images])
augmented_unlabeled_images_2 = np.array([data_augmentation_image2tensor(image, max_blur, max_noise, brightness_range_alpha, brightness_range_beta) for image in batch_unlabeled_images])
with tf.GradientTape() as tape:
predictions_1 = model(augmented_unlabeled_images_1, training=True)
predictions_2 = model(augmented_unlabeled_images_2, training=True)
consistency_loss = tf.reduce_mean(tf.keras.losses.mean_squared_error(predictions_1, predictions_2))
current_weights = model.trainable_variables
gradients = tape.gradient(consistency_loss, current_weights)
opt.apply_gradients(zip(gradients, current_weights))
# Evaluate the model on the validation set (optional)
if epoch % validation_frequency == 0:
validation_loss = model.evaluate(validation_images, validation_masks)
print(f'Epoch: {epoch}, Validation Loss: {round(validation_loss,4)} after unlabeled training')
if validation_loss < current_validation_loss:
current_validation_loss = validation_loss
print(f' -------------------------- Model saved with val_loss {round(validation_loss,4)}')
model.save(filepath_h5)
best_model = tf.keras.models.load_model(filepath_h5, custom_objects={'dice_loss': dice_loss})
mPA_val, mIoU_val = benchmark_multiclass(best_model, val_images_dir, val_masks_dir, val_pred_dir, h, w, c, class_to_color_mapping, print_results=print_results)
mPA_test, mIoU_test = benchmark_multiclass(best_model, test_images_dir, test_masks_dir, test_pred_dir, h, w, c, class_to_color_mapping, print_results=print_results)
mPA_train_unlabeled, mIoU_train_unlabeled = benchmark_multiclass(best_model, unlabeled_images_dir, unlabeled_masks_dir, unlabeled_pred_dir, h, w, c, class_to_color_mapping, print_results=print_results)
print(f'{modelname} mIoU_val: {mIoU_val}')
return mPA_val, mPA_test, mPA_train_unlabeled, mIoU_val, mIoU_test, mIoU_train_unlabeled
def train_depth_map_consistency_loss(train_images_dir,
train_depth_maps_dir,
val_images_dir,
val_depth_maps_dir,
test_images_dir,
unlabeled_images_dir,
modelname,
filepath_h5,
model,
loss_func,
h, w, c,
val_pred_dir,
test_pred_dir,
unlabeled_pred_dir,
max_blur, max_noise, brightness_range_alpha, brightness_range_beta,
validation_frequency=1
):
labeled_images, labeled_depth_maps = load_labeled_data_depth_map(train_images_dir, train_depth_maps_dir)
unlabeled_images = load_unlabeled_images(unlabeled_images_dir)
validation_images, validation_depth_maps = load_labeled_data_depth_map(val_images_dir, val_depth_maps_dir)
opt = tfa.optimizers.AdamW(learning_rate=LR, weight_decay=WD)
model.compile(optimizer=opt, loss=loss_func) #, metrics=[dice_loss]
current_validation_loss = 100
for epoch in range(NUM_EPOCHS_CS):
# Shuffle the data
labeled_indices = np.random.permutation(len(labeled_images))
unlabeled_indices = np.random.permutation(len(unlabeled_images))
# Create batches for labeled and unlabeled data
num_labeled_batches = int(np.ceil(len(labeled_images) / BATCH_SIZE))
num_unlabeled_batches = int(np.ceil(len(unlabeled_images) / BATCH_SIZE))
# Iterate through labeled data batches
for batch_idx in range(num_labeled_batches):
batch_start = batch_idx * BATCH_SIZE
batch_end = (batch_idx + 1) * BATCH_SIZE
batch_indices = labeled_indices[batch_start:batch_end]
batch_labeled_images = labeled_images[batch_indices]
batch_labeled_depth_maps = labeled_depth_maps[batch_indices]
model.train_on_batch(batch_labeled_images, batch_labeled_depth_maps)
if epoch % validation_frequency == 0:
validation_loss = model.evaluate(validation_images, validation_depth_maps)
print(f'Epoch: {epoch}, Validation Loss: {round(validation_loss,4)} after labeled training')
if validation_loss < current_validation_loss:
current_validation_loss = validation_loss
print(f' -------------------------- Model saved with val_loss {round(validation_loss,4)}')
model.save(filepath_h5)
# Iterate through unlabeled data batches
for batch_idx in range(num_unlabeled_batches):
batch_start = batch_idx * BATCH_SIZE
batch_end = (batch_idx + 1) * BATCH_SIZE
batch_indices = unlabeled_indices[batch_start:batch_end]
batch_unlabeled_images = unlabeled_images[batch_indices]
augmented_unlabeled_images_1 = np.array([data_augmentation_image2tensor(image, max_blur, max_noise, brightness_range_alpha, brightness_range_beta) for image in batch_unlabeled_images])
augmented_unlabeled_images_2 = np.array([data_augmentation_image2tensor(image, max_blur, max_noise, brightness_range_alpha, brightness_range_beta) for image in batch_unlabeled_images])
with tf.GradientTape() as tape:
predictions_1 = model(augmented_unlabeled_images_1, training=True)
predictions_2 = model(augmented_unlabeled_images_2, training=True)
consistency_loss = tf.reduce_mean(tf.keras.losses.mean_squared_error(predictions_1, predictions_2))
current_weights = model.trainable_variables
gradients = tape.gradient(consistency_loss, current_weights)
opt.apply_gradients(zip(gradients, current_weights))
# Evaluate the model on the validation set (optional)
if epoch % validation_frequency == 0:
validation_loss = model.evaluate(validation_images, validation_depth_maps)
print(f'Epoch: {epoch}, Validation Loss: {round(validation_loss,4)} after unlabeled training')
if validation_loss < current_validation_loss:
current_validation_loss = validation_loss
print(f' -------------------------- Model saved with val_loss {round(validation_loss,4)}')
model.save(filepath_h5)
best_model = tf.keras.models.load_model(filepath_h5)
val_images_path = os.path.join(val_images_dir, '*.png')
val_dataset = tf.data.Dataset.list_files(val_images_path, seed=SEED)
val_dataset = val_dataset.map(parse_image_depth_map).batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)
test_images_path = os.path.join(test_images_dir, '*.png')
test_dataset = tf.data.Dataset.list_files(test_images_path, seed=SEED)
test_dataset = test_dataset.map(parse_image_depth_map).batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)
unlabeled_images_path = os.path.join(unlabeled_images_dir, '*.png')
unlabeled_dataset = tf.data.Dataset.list_files(unlabeled_images_path, seed=SEED)
unlabeled_dataset = unlabeled_dataset.map(parse_image_depth_map).batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)
rmse_val, mse_val = benchmark_depth_map(best_model, val_dataset, val_pred_dir)
rmse_test, mse_test = benchmark_depth_map(best_model, test_dataset, test_pred_dir)
rmse_unlabeled, mse_unlabeled = benchmark_depth_map(best_model, unlabeled_dataset, unlabeled_pred_dir)
print(f'{modelname} rmse_val: {rmse_val}')
return rmse_val, rmse_test, rmse_unlabeled, mse_val, mse_test, mse_unlabeled
def load_labeled_data_single_mask(labeled_images_dir, labeled_masks_dir):
'''
Reads images and masks from specified directories, processes them, and returns them as numpy arrays.
Args:
labeled_images_dir (str): Directory containing labeled images.
labeled_masks_dir (str): Directory containing corresponding masks for the images.
Returns:
tuple: A tuple containing two numpy arrays:
- images: RGB images as numpy arrays.
- binary_masks: Binary masks corresponding to the images.
'''
image_filenames = sorted(os.listdir(labeled_images_dir))
mask_filenames = sorted(os.listdir(labeled_masks_dir))
# Added the color conversion for each image after reading it
images = [cv2.cvtColor(cv2.imread(os.path.join(labeled_images_dir, fname)), cv2.COLOR_BGR2RGB) for fname in image_filenames]
masks = [cv2.imread(os.path.join(labeled_masks_dir, fname), cv2.IMREAD_GRAYSCALE) for fname in mask_filenames]
images = np.array(images)
masks = np.array(masks)
# Normalize the masks by dividing them by 255
masks_normalized = masks.astype(np.float32) / 255.0
# Threshold the normalized masks to obtain binary masks (0 or 1)
binary_masks = np.where(masks_normalized > 0.5, 1, 0)
return images, binary_masks
def load_labeled_data_multiclass_mask(labeled_images_dir, labeled_masks_dir, num_classes):
'''
Reads images and masks from specified directories, processes them for multiclass segmentation tasks, and returns them as numpy arrays. Masks are converted to one-hot encoded format based on the number of classes.
Args:
labeled_images_dir (str): Directory containing labeled images.
labeled_masks_dir (str): Directory containing corresponding masks for the images.
num_classes (int): The number of classes for segmentation.
Returns:
tuple: A tuple containing two numpy arrays:
- images: RGB images as numpy arrays.
- masks: One-hot encoded masks corresponding to the images.
'''
image_filenames = sorted(os.listdir(labeled_images_dir))
mask_filenames = sorted(os.listdir(labeled_masks_dir))
# Added the color conversion for each image after reading it
images = [cv2.cvtColor(cv2.imread(os.path.join(labeled_images_dir, fname)), cv2.COLOR_BGR2RGB) for fname in image_filenames]
masks = [cv2.imread(os.path.join(labeled_masks_dir, fname), cv2.IMREAD_GRAYSCALE) for fname in mask_filenames]
images = np.array(images)
masks = np.array(masks)
# One-hot encoding
masks = to_categorical(masks, num_classes)
return images, masks
def load_labeled_data_depth_map(labeled_images_dir, labeled_depth_maps_dir):
'''
Reads images and depth maps from specified directories, processes them, and returns them as numpy arrays. Depth maps are normalized to float values between 0 and 1.
Args:
labeled_images_dir (str): Directory containing labeled images.
labeled_depth_maps_dir (str): Directory containing corresponding depth maps for the images.
Returns:
tuple: A tuple containing two numpy arrays:
- images: Images as numpy arrays.
- depth_maps_normalized: Normalized depth maps corresponding to the images.
'''
image_filenames = sorted(os.listdir(labeled_images_dir))
mask_filenames = sorted(os.listdir(labeled_depth_maps_dir))
images = [cv2.imread(os.path.join(labeled_images_dir, fname)) for fname in image_filenames]
depth_maps = [cv2.imread(os.path.join(labeled_depth_maps_dir, fname), cv2.IMREAD_GRAYSCALE) for fname in mask_filenames]
images = np.array(images)
depth_maps = np.array(depth_maps)
depth_maps_normalized = depth_maps.astype(np.float32) / 255.0
return images, depth_maps_normalized
def load_unlabeled_images(unlabeled_images_dir, read_as_grayscale=False):
'''
Reads images from the given directory and can optionally convert them to grayscale. The images are returned as a numpy array.
Args:
unlabeled_images_dir (str): Directory containing unlabeled images.
read_as_grayscale (bool, optional): Flag to indicate whether the images should be read in grayscale. Defaults to False.
Returns:
np.array: Array of images read from the directory.
'''
image_filenames = os.listdir(unlabeled_images_dir)
if read_as_grayscale:
unlabeled_images = [cv2.imread(os.path.join(unlabeled_images_dir, fname), cv2.IMREAD_GRAYSCALE) for fname in image_filenames]
else:
unlabeled_images = [cv2.imread(os.path.join(unlabeled_images_dir, fname)) for fname in image_filenames]
unlabeled_images = np.array(unlabeled_images)
return unlabeled_images
def parse_image_ISIC_2018(image_dir, IMG_CHANNELS=3):
'''
Parse an image and its corresponding mask from the ISIC 2018 dataset.
Args:
image_dir (str): Directory of the image file.
IMG_CHANNELS (int, optional): Number of channels in the image (e.g., 3 for RGB). Defaults to 3.
Returns:
tuple: A tuple containing:
- image: The decoded image tensor.
- mask: The corresponding binary mask tensor.
'''
image = tf.io.read_file(image_dir)
image = tf.image.decode_png(image, channels = IMG_CHANNELS)
path_mask = tf.strings.regex_replace(image_dir, 'images', 'masks')
mask = tf.io.read_file(path_mask)
mask = tf.image.decode_png(mask, channels=1)
mask = tf.cast((mask / 255), tf.uint8)
return image, mask
def parse_image_hela(path_brightfield, IMG_CHANNELS=1, Position_weight=3):
'''
Reads a brightfield image along with its corresponding 'alive', 'dead', and 'position' masks.
Args:
path_brightfield (str): Path to the brightfield image.
IMG_CHANNELS (int, optional): Number of channels in the brightfield image. Defaults to 1.
Position_weight (int, optional): Weighting factor for the position image. Defaults to 3.
Returns:
tuple: A tuple containing:
- bf_img: The brightfield image tensor.
- comb_outputs: Combined tensor of 'alive', 'dead', and weighted 'position' images.
'''
bf_img = tf.io.read_file(path_brightfield)
bf_img = tf.image.decode_png(bf_img, channels = IMG_CHANNELS)
path_alive = tf.strings.regex_replace(path_brightfield, 'brightfield', 'alive')
alive_img = tf.io.read_file(path_alive)
alive_img = tf.image.decode_png(alive_img, channels=1)