-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathliver_tumor_segmentation_using_v_net_based_approach.py
More file actions
1588 lines (1202 loc) · 63.1 KB
/
liver_tumor_segmentation_using_v_net_based_approach.py
File metadata and controls
1588 lines (1202 loc) · 63.1 KB
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
# -*- coding: utf-8 -*-
"""Liver Tumor Segmentation Using V-Net Based Approach.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1x7qsXmtOxTsIgocTlyLO3XEi5jzLv0J4
## **Medical Segmentation Decathlon: Effective VNet-based 3D Segmentation Model of the Liver**
---
* VNet was used as my backbone network to solve this decathlon "liver tumour" task (https://arxiv.org/abs/1606.04797)
* Use the Generalised Dice Score as my loss function (https://arxiv.org/abs/1707.03237)
**The data for this specific task can be downloaded from here:**
https://drive.google.com/open?id=1jyVGUGyxKBXV6_9ivuZapQS8eUJXCIpu
## **Imports**
---
"""
!pip install monai
import matplotlib
import monai
from monai.utils import first, set_determinism
from monai.transforms import (
AsDiscrete,
AsDiscreted,
EnsureChannelFirstd,
Compose,
CropForegroundd,
LoadImaged,
Orientationd,
Resized,
RandCropByPosNegLabeld,
SaveImaged,
ScaleIntensityRanged,
Spacingd,
Invertd,
RandAffined,
)
from monai.handlers.utils import from_engine
from monai.networks.nets import VNet
from monai.metrics import DiceMetric
from monai.losses import GeneralizedDiceLoss
from monai.inferers import sliding_window_inference
from monai.data import CacheDataset, DataLoader,ThreadDataLoader, Dataset, decollate_batch
from monai.config import print_config
from monai.apps import download_and_extract
import torch
import matplotlib.pyplot as plt
import tempfile
import shutil
import os
import glob
import nibabel as nib
import random
import numpy as np
print_config()
"""# **Data divsion**
---
**The following code is only run for the first time, for the purpose of dividing the data set. Later can be directly used**
---
"""
# original_imagesTr = "/content/drive/My Drive/AML_Final_Project/Data/imagesTr"
# original_labelsTr = "/content/drive/My Drive/AML_Final_Project/Data/labelsTr"
# train_imagesTr = "/content/drive/My Drive/AML_Final_Project/Data/Train/imagesTr"
# train_labelsTr = "/content/drive/My Drive/AML_Final_Project/Data/Train/labelsTr"
# test_imagesTr = "/content/drive/My Drive/AML_Final_Project/Data/Test/imagesTr"
# test_labelsTr = "/content/drive/My Drive/AML_Final_Project/Data/Test/labelsTr"
# os.makedirs(train_imagesTr, exist_ok=True)
# os.makedirs(train_labelsTr, exist_ok=True)
# os.makedirs(test_imagesTr, exist_ok=True)
# os.makedirs(test_labelsTr, exist_ok=True)
# # List all files in the original folders
# all_images = os.listdir(original_imagesTr)
# all_labels = os.listdir(original_labelsTr)
# # Shuffle the list of files
# random.seed(42)
# random.shuffle(all_images)
# # Split the files into training and testing sets
# train_images = all_images[:89]
# test_images = all_images[89:]
# # Copy the files to the destination folders
# for file in train_images:
# shutil.copy(os.path.join(original_imagesTr, file), os.path.join(train_imagesTr, file))
# shutil.copy(os.path.join(original_labelsTr, file), os.path.join(train_labelsTr, file))
# for file in test_images:
# shutil.copy(os.path.join(original_imagesTr, file), os.path.join(test_imagesTr, file))
# shutil.copy(os.path.join(original_labelsTr, file), os.path.join(test_labelsTr, file))
"""# **Pipeline**
---
## **Data loading**
---
131 3D volumes (89 Training + 42 Testing)
"""
# Mount the drive to colab
from google.colab import drive
drive.mount('/content/drive')
root_dir = os.path.join("/content/drive/My Drive/AML_Final_Project")
print(root_dir)
data_dir = os.path.join(root_dir, "Data")
print(data_dir)
# Set Liver dataset path
train_images = sorted(glob.glob(os.path.join(data_dir, "Train/imagesTr", "*.nii.gz")))
train_labels = sorted(glob.glob(os.path.join(data_dir, "Train/labelsTr", "*.nii.gz")))
data_dicts = [{"image": image_name, "label": label_name} for image_name, label_name in zip(train_images, train_labels)]
train_files, valid_files = data_dicts[:-19], data_dicts[-19:]
"""## **Preprocessing**
---
"""
# Set deterministic training for reproducibility
set_determinism(seed=0)
# Set transforms for training and validation
train_transforms = Compose(
[
LoadImaged(keys=["image", "label"]), # Load the liver CT images and labels from NIfTI format files
EnsureChannelFirstd(keys=["image", "label"]), # Ensure the original data to construct "channel first" shape
ScaleIntensityRanged(
keys=["image"],
a_min=-200,
a_max=200,
b_min=0.0,
b_max=1.0,
clip=True,
), # Extract intensity range [-200, 200] and scales to [0, 1]
CropForegroundd(keys=["image", "label"], source_key="image"), # Remove the background region from the label data
Orientationd(keys=["image", "label"], axcodes="RAS"), # Unify the data orientation based on the affine matrix
Spacingd(keys=["image", "label"], pixdim=(1.5, 1.5, 1.0), mode=("bilinear", "nearest")), # Adjust the spacing by pixdim based on the affine matrix
RandCropByPosNegLabeld(
keys=["image", "label"],
label_key="label",
spatial_size=(128, 128, 64),
pos=1,
neg=1,
num_samples=4,
image_key="image",
image_threshold=0,
), # Randomly crop patch samples from big image based on pos / neg ratio
]
)
valid_transforms = Compose(
[
LoadImaged(keys=["image", "label"]),
EnsureChannelFirstd(keys=["image", "label"]),
ScaleIntensityRanged(
keys=["image"],
a_min=-200,
a_max=200,
b_min=0.0,
b_max=1.0,
clip=True,
),
CropForegroundd(keys=["image", "label"], source_key="image"),
Orientationd(keys=["image", "label"], axcodes="RAS"),
Spacingd(keys=["image", "label"], pixdim=(1.5, 1.5, 1.0), mode=("bilinear", "nearest")),
]
)
"""## **Dataset and DataLoader**
---
"""
# Define CacheDataset and DataLoader for training and validation
train_ds = CacheDataset(data=train_files, transform=train_transforms, cache_rate=1.0, num_workers=4) # set cache_rate=1.0 to cache all the data
# Use batch_size=2 to load images and use RandCropByPosNegLabeld to generate 2 x 4 images for network training
train_loader = DataLoader(train_ds, batch_size=2, shuffle=True, num_workers=4)
valid_ds = CacheDataset(data=valid_files, transform=valid_transforms, cache_rate=1.0, num_workers=4)
valid_loader = DataLoader(valid_ds, batch_size=1, num_workers=4)
"""## **Model structure, Loss function and Optimizer**
---
"""
# Set the device to GPU
device = torch.device("cuda:0")
# Implement the VNet model with dropout_prob = 0.48
model = VNet(
spatial_dims=3,
in_channels=1,
out_channels=3,
dropout_prob=0.48
).to(device)
# Implements the GeneralizedDiceLoss function from MONAI,
# which is set to calculate the loss using one-hot encoded ground truth labels and sigmoid probabilities
loss_fn = GeneralizedDiceLoss(to_onehot_y=True, sigmoid=True)
# Initializes the Adam optimizer with a learning rate of 1e-5 for model training
optimizer = torch.optim.Adam(model.parameters(), 1e-5)
# Implements the DiceMetric from MONAI,
# which excludes the background and takes the mean of the dice scores for evaluation
dice_score = DiceMetric(include_background=False, reduction="mean")
"""## **Train**
---
"""
# Set the number of maximum epochs to 300 and the validation interval to 2
max_epochs = 300
valid_interval = 2
# Keep track of the best metric value and its corresponding epoch
best_metric = -1
best_metric_epoch = -1
# Store epoch loss values and metric values
epoch_loss_values = []
metric_values = []
# Process the model's output and ground truth labels
pred = Compose([AsDiscrete(argmax=True, to_onehot=3)])
label = Compose([AsDiscrete(to_onehot=3)])
for epoch in range(max_epochs):
print("-" * 10)
print(f"epoch {epoch + 1}/{max_epochs}")
# Set the model to training mode
model.train()
# Initializes the epoch loss and step
epoch_loss = 0
step = 0
# Iterate through the training data loader
for batch_data in train_loader:
step += 1
inputs, labels = (
batch_data["image"].to(device),
batch_data["label"].to(device),
)
# Forward pass
optimizer.zero_grad()
outputs = model(inputs)
# Calculate the loss
loss = loss_fn(outputs, labels)
loss.backward()
# Update the model's weights using the optimizer
optimizer.step()
epoch_loss += loss.item()
print(f"{step}/{len(train_ds) // train_loader.batch_size}, " f"train_loss: {loss.item():.4f}")
# Calculate the average epoch loss and appends it to the epoch_loss_values list
epoch_loss /= step
epoch_loss_values.append(epoch_loss)
print(f"epoch {epoch + 1} average loss: {epoch_loss:.4f}")
# If the current epoch is a validation epoch, it sets the model to evaluation mode
if (epoch + 1) % valid_interval == 0:
model.eval()
with torch.no_grad():
for valid_data in valid_loader:
valid_inputs, valid_labels = (
valid_data["image"].to(device),
valid_data["label"].to(device),
)
# Representing the size of the sliding window to generate predictions for each patch
roi_size = (128, 128, 64)
# Representing the batch size for sliding window inference
sw_batch_size = 4
# Performs inference on the validation dataset using sliding_window_inference
valid_outputs = sliding_window_inference(valid_inputs, roi_size, sw_batch_size, model)
# Calculate the Dice metric for the model's predictions
valid_outputs = [pred(i) for i in decollate_batch(valid_outputs)]
valid_labels = [label(i) for i in decollate_batch(valid_labels)]
# compute metric for current iteration
dice_score(y_pred=valid_outputs, y=valid_labels)
# aggregate the final mean dice result
metric = dice_score.aggregate().item()
# reset the status for next validation round
dice_score.reset()
# Update the best metric and its corresponding epoch if necessary
metric_values.append(metric)
if metric > best_metric:
best_metric = metric
best_metric_epoch = epoch + 1
# Save the model with the best metric
torch.save(model.state_dict(), os.path.join(root_dir, "best_metric_model1.pth"))
print("saved new best metric model")
print(
f"current epoch: {epoch + 1} current mean dice: {metric:.4f}"
f"\nbest mean dice: {best_metric:.4f} "
f"at epoch: {best_metric_epoch}"
)
print(f"train completed, best_metric: {best_metric:.4f} " f"at epoch: {best_metric_epoch}")
plt.figure("train", (12, 6))
plt.subplot(1, 2, 1)
plt.title("Epoch Average Loss")
x = [i + 1 for i in range(len(epoch_loss_values))]
y = epoch_loss_values
plt.xlabel("epoch")
plt.plot(x, y)
plt.subplot(1, 2, 2)
plt.title("Val Mean Dice")
x = [valid_interval * (i + 1) for i in range(len(metric_values))]
y = metric_values
plt.xlabel("epoch")
plt.plot(x, y)
plt.show()
"""## Report
---
A pipeline of 3D segmentation algorithms based on VNet as a model and a generalised sieve loss function as a loss function was constructed using the MONAI open source library for the "liver tumour" task.
The 131 CT scans in imagesTr were first divided into training and test data.Then, set up deterministic training for repeatability and set up transitions for training and validation. Using the MONAI open source database of LoadImaged, EnsureChannelFirstd, Orientationd, Spacingd, ScaleIntensityRanged, CropForegroundd, RandCropByPosNegLabeld and RandAffined transformations are used to augment the dataset. Load liver CT images and labels from NIfTI format files. Ensure that the raw data constructs a 'channel-first' shape and unifies the data orientation on the basis of the bionic matrix. Adjust the spacing based on the bionic matrix by pixdim=(1.5, 1.5, 1.). The intensity range [-200, 200] was extracted and scaled to [0, 1]. Also remove all zero borders to focus on the effective subject area of the image and label. Randomly crop patch samples from large images based on pos/neg ratios. where the negative samples must have the centre of the image in the valid subject area. For subsequent applications of data enhancement techniques, the PyTorch-based affine transform is retained.
For the use of datasets, I used the CacheDataset and DataLoader from the MONAI database for training and validation. Because the CacheDataset is used to speed up the training and validation process, it is 10 times faster than a normal dataset. For best performance, I set cache_rate to 1.0 to cache all the data. The num_workers setting is to enable multithreading during caching. I use the VNet model as the backbone network to solve this task, and for the loss function I use the Generalised Dice Score function. For the optimizer, I use the Adam optimizer.
The training loop iterated through a maximum of 300 epochs. For each epoch, the model's weights were updated using the optimizer based on the calculated loss. The training loss values were recorded for each epoch. Model evaluation occurred every 2 epochs (as determined by the val_interval parameter), using the validation dataset. During the validation phase, the model's performance was evaluated using sliding window inference, which processes the input image in smaller patches to generate predictions. The Dice metric (excluding the background) was used to assess the model's segmentation performance. The best metric value and its corresponding epoch were tracked throughout the training process, and the model with the best metric was saved as best_metric_model.pth.
After 300 epochs, the best metric is 0.4001 at epoch 256. Based on the results, the segmentation algorithm pipeline is performing as expected, with training losses converging gradually and the model gradually learning the data and predicting it, but the model may be over-fitted.
# **Data Enhancement**
---
Use MONAI's built-in transformers to add noise, contrast, and elastic deformation transformations to my data augmentation pipeline
"""
from monai.transforms import RandGaussianNoised, RandAdjustContrastd, Rand3DElasticd
# Applying random Gaussian noise, contrast adjustment, and 3D elastic deformation for data augmentation
train_transforms = Compose(
[
LoadImaged(keys=["image", "label"]),
EnsureChannelFirstd(keys=["image", "label"]),
ScaleIntensityRanged(
keys=["image"],
a_min=-200,
a_max=200,
b_min=0.0,
b_max=1.0,
clip=True,
),
CropForegroundd(keys=["image", "label"], source_key="image"),
Orientationd(keys=["image", "label"], axcodes="RAS"),
Spacingd(keys=["image", "label"], pixdim=(1.5, 1.5, 1.0), mode=("bilinear", "nearest")),
RandGaussianNoised(keys=["image"], prob=0.05, std=0.1), # Add Gaussian noise to the image with a probability of 0.05 and a standard deviation of 0.1
RandAdjustContrastd(keys=["image"], prob=0.05, gamma=(0.9, 1.0)), # Randomly adjust the contrast of the image with a probability of 0.05 and a gamma value range of [0.9, 1.0]
Rand3DElasticd(
keys=["image", "label"],
prob=0.05,
sigma_range=(4, 5),
magnitude_range=(50, 80),
rotate_range=(0, 0, np.pi / 30),
mode=("bilinear", "nearest"),
padding_mode="border",
), # Apply elastic deformation to the image and label with a probability of 0.05
RandCropByPosNegLabeld(
keys=["image", "label"],
label_key="label",
spatial_size=(128, 128, 64),
pos=1,
neg=1,
num_samples=1,
image_key="image",
image_threshold=0,
),
]
)
# valid transforms remains the same
valid_transforms = Compose(
[
LoadImaged(keys=["image", "label"]),
EnsureChannelFirstd(keys=["image", "label"]),
ScaleIntensityRanged(
keys=["image"],
a_min=-200,
a_max=200,
b_min=0.0,
b_max=1.0,
clip=True,
),
CropForegroundd(keys=["image", "label"], source_key="image"),
Orientationd(keys=["image", "label"], axcodes="RAS"),
Spacingd(keys=["image", "label"], pixdim=(1.5, 1.5, 1.0), mode=("bilinear", "nearest")),
]
)
# Define CacheDataset and DataLoader for training and validation
train_ds = CacheDataset(data=train_files, transform=train_transforms, cache_rate=1.0, num_workers=4) # set cache_rate=1.0 to cache all the data
# Use batch_size=2 to load images and use RandCropByPosNegLabeld to generate 2 x 1 images for network training
train_loader = DataLoader(train_ds, batch_size=2, shuffle=True, num_workers=4)
valid_ds = CacheDataset(data=valid_files, transform=valid_transforms, cache_rate=1.0, num_workers=4)
valid_loader = DataLoader(valid_ds, batch_size=1, num_workers=4)
"""## Train
---
"""
# Train again
# Set the number of maximum epochs to 300 and the validation interval to 2
max_epochs = 300
valid_interval = 2
# Keep track of the best metric value and its corresponding epoch
best_metric = -1
best_metric_epoch = -1
# Store epoch loss values and metric values
epoch_loss_values = []
metric_values = []
# Process the model's output and ground truth labels
pred = Compose([AsDiscrete(argmax=True, to_onehot=3)])
label = Compose([AsDiscrete(to_onehot=3)])
for epoch in range(max_epochs):
print("-" * 10)
print(f"epoch {epoch + 1}/{max_epochs}")
# Set the model to training mode
model.train()
# Initializes the epoch loss and step
epoch_loss = 0
step = 0
# Iterate through the training data loader
for batch_data in train_loader:
step += 1
inputs, labels = (
batch_data["image"].to(device),
batch_data["label"].to(device),
)
# Forward pass
optimizer.zero_grad()
outputs = model(inputs)
# Calculate the loss
loss = loss_fn(outputs, labels)
loss.backward()
# Update the model's weights using the optimizer
optimizer.step()
epoch_loss += loss.item()
print(f"{step}/{len(train_ds) // train_loader.batch_size}, " f"train_loss: {loss.item():.4f}")
# Calculate the average epoch loss and appends it to the epoch_loss_values list
epoch_loss /= step
epoch_loss_values.append(epoch_loss)
print(f"epoch {epoch + 1} average loss: {epoch_loss:.4f}")
# If the current epoch is a validation epoch, it sets the model to evaluation mode
if (epoch + 1) % valid_interval == 0:
model.eval()
with torch.no_grad():
for valid_data in valid_loader:
valid_inputs, valid_labels = (
valid_data["image"].to(device),
valid_data["label"].to(device),
)
# Representing the size of the sliding window to generate predictions for each patch
roi_size = (128, 128, 64)
# Representing the batch size for sliding window inference
sw_batch_size = 4
# Performs inference on the validation dataset using sliding_window_inference
valid_outputs = sliding_window_inference(valid_inputs, roi_size, sw_batch_size, model)
# Calculate the Dice metric for the model's predictions
valid_outputs = [pred(i) for i in decollate_batch(valid_outputs)]
valid_labels = [label(i) for i in decollate_batch(valid_labels)]
# compute metric for current iteration
dice_score(y_pred=valid_outputs, y=valid_labels)
# aggregate the final mean dice result
metric = dice_score.aggregate().item()
# reset the status for next validation round
dice_score.reset()
# Update the best metric and its corresponding epoch if necessary
metric_values.append(metric)
if metric > best_metric:
best_metric = metric
best_metric_epoch = epoch + 1
# Save the model with the best metric
torch.save(model.state_dict(), os.path.join(root_dir, "best_metric_model2.pth"))
print("saved new best metric model")
print(
f"current epoch: {epoch + 1} current mean dice: {metric:.4f}"
f"\nbest mean dice: {best_metric:.4f} "
f"at epoch: {best_metric_epoch}"
)
print(f"train completed, best_metric: {best_metric:.4f} " f"at epoch: {best_metric_epoch}")
"""## **Test**
---
"""
test_images = sorted(glob.glob(os.path.join(data_dir, "Test/imagesTr", "*.nii.gz")))
test_data = [{"image": image} for image in test_images]
test_org_transforms = Compose(
[
LoadImaged(keys="image"),
EnsureChannelFirstd(keys="image"),
Orientationd(keys=["image"], axcodes="RAS"),
Spacingd(keys=["image"], pixdim=(1.5, 1.5, 1.0), mode="bilinear"),
ScaleIntensityRanged(
keys=["image"],
a_min=-200,
a_max=200,
b_min=0.0,
b_max=1.0,
clip=True,
),
CropForegroundd(keys=["image"], source_key="image"),
]
)
test_org_ds = Dataset(data=test_data, transform=test_org_transforms)
# test_org_ds = CacheDataset(data=test_data, transform=test_org_transforms, cache_rate=1.0, num_workers=4)
test_org_loader = DataLoader(test_org_ds, batch_size=1, num_workers=4)
post_transforms = Compose(
[
Invertd(
keys="pred",
transform=test_org_transforms,
orig_keys="image",
meta_keys="pred_meta_dict",
orig_meta_keys="image_meta_dict",
meta_key_postfix="meta_dict",
nearest_interp=False,
to_tensor=True,
),
AsDiscreted(keys="pred", argmax=True, to_onehot=3),
SaveImaged(keys="pred", meta_keys="pred_meta_dict", output_dir="./out", output_postfix="seg", resample=False),
]
)
# Test again
# liver category is represented by channel 0 and the tumor category is represented by channel 1
model.load_state_dict(torch.load(os.path.join(root_dir, "best_metric_model2.pth")))
model.eval()
with torch.no_grad():
for test_data in test_org_loader:
test_inputs = test_data["image"].to(device)
roi_size = (128, 128, 64)
sw_batch_size = 4
test_data["pred"] = sliding_window_inference(test_inputs, roi_size, sw_batch_size, model)
test_data = [post_transforms(i) for i in decollate_batch(test_data)]
# Visualize the predicted results
test_output = from_engine(["pred"])(test_data)
original_image = nib.load(test_output[0].meta["filename_or_obj"]).get_fdata()
plt.figure("check", (18, 6))
plt.subplot(1, 2, 1)
plt.imshow(original_image[:, :, 20], cmap="gray")
plt.subplot(1, 2, 2)
plt.imshow(test_output[0].detach().cpu()[1, :, :, 20])
plt.show()
"""## **Report**
---
Since common data enhancement techniques already exist in the MONAI open source library, I directly invoke data enhancement techniques for Gaussian noise, contrast, and Elastic deformation.
RandGaussianNoised: Adds Gaussian noise to the image with a probability of 0.05 and a standard deviation of 0.1. This helps to simulate the noise present in real-world medical images, which can improve the robustness of the model.
RandAdjustContrastd: Randomly adjusts the contrast of the image with a probability of 0.05 and a gamma value range of [0.9, 1.0]. This helps to simulate the variability in contrast present in real-world medical images, which can also improve the robustness of the model.
Rand3DElasticd: Applies elastic deformation to the image and label with a probability of 0.05. Elastic deformation simulates the tissue deformation that can occur during medical imaging and can help the model to better capture variations in the shape and size of structures in the image.
By using these data augmentation techniques, the model is exposed to a wider range of variations in the input data, which can improve its generalization performance and help it to better adapt to new and unseen data.After 300 epochs, it was found that the best dice score was obtained at epoch 296 for 0.6320. This is a better performance of the model compared to previous training without the use of data enhancement techniques, rising from a best dice score of 0.4001 to 0.6320, indicating that the training process is more robust to against overfitting and generalize better to unseen data. In tests, the generation of prediction maps worked well.
# **Optimise**
---
"""
# Define CacheDataset and DataLoader for training and validation
train_ds = CacheDataset(data=train_files, transform=train_transforms, cache_rate=1.0, num_workers=4) # set cache_rate=1.0 to cache all the data
# Use batch_size=2 to load images and use RandCropByPosNegLabeld to generate 2 x 4 images for network training
train_loader = DataLoader(train_ds, batch_size=2, shuffle=True, num_workers=4)
valid_ds = CacheDataset(data=valid_files, transform=valid_transforms, cache_rate=1.0, num_workers=4)
valid_loader = DataLoader(valid_ds, batch_size=1, num_workers=4)
# Set the device to GPU
device = torch.device("cuda:0")
# Implement the VNet model and Change the dropout rate to 0.5
model = VNet(
spatial_dims=3,
in_channels=1,
out_channels=3,
dropout_prob=0.5,
).to(device)
# Implements the GeneralizedDiceLoss function from MONAI,
# which is set to calculate the loss using one-hot encoded ground truth labels and softmax probabilities
loss_fn = GeneralizedDiceLoss(to_onehot_y=True, softmax=True)
# Initializes the Adam optimizer with a learning rate of 1e-4 for model training
optimizer = torch.optim.Adam(model.parameters(), 1e-4)
# Implements the DiceMetric from MONAI,
# which excludes the background and takes the mean of the dice scores for evaluation
dice_score = DiceMetric(include_background=False, reduction="mean")
"""## **Train**
---
"""
# The training process after optimising
max_epochs = 600
valid_interval = 2
# Keep track of the best metric value and its corresponding epoch
best_metric = -1
best_metric_epoch = -1
# Store epoch loss values and metric values
epoch_loss_values = []
metric_values = []
# Process the model's output and ground truth labels
pred = Compose([AsDiscrete(argmax=True, to_onehot=3)])
label = Compose([AsDiscrete(to_onehot=3)])
for epoch in range(max_epochs):
print("-" * 10)
print(f"epoch {epoch + 1}/{max_epochs}")
# Set the model to training mode
model.train()
# Initializes the epoch loss and step
epoch_loss = 0
step = 0
# Iterate through the training data loader
for batch_data in train_loader:
step += 1
inputs, labels = (
batch_data["image"].to(device),
batch_data["label"].to(device),
)
# Forward pass
optimizer.zero_grad()
outputs = model(inputs)
# Calculate the loss
loss = loss_fn(outputs, labels)
loss.backward()
# Update the model's weights using the optimizer
optimizer.step()
epoch_loss += loss.item()
print(f"{step}/{len(train_ds) // train_loader.batch_size}, " f"train_loss: {loss.item():.4f}")
# Calculate the average epoch loss and appends it to the epoch_loss_values list
epoch_loss /= step
epoch_loss_values.append(epoch_loss)
print(f"epoch {epoch + 1} average loss: {epoch_loss:.4f}")
# If the current epoch is a validation epoch, it sets the model to evaluation mode
if (epoch + 1) % valid_interval == 0:
model.eval()
with torch.no_grad():
for valid_data in valid_loader:
valid_inputs, valid_labels = (
valid_data["image"].to(device),
valid_data["label"].to(device),
)
# Representing the size of the sliding window to generate predictions for each patch
roi_size = (128, 128, 64)
# Representing the batch size for sliding window inference
sw_batch_size = 4
# Performs inference on the validation dataset using sliding_window_inference
valid_outputs = sliding_window_inference(valid_inputs, roi_size, sw_batch_size, model)
# Calculate the Dice metric for the model's predictions
valid_outputs = [pred(i) for i in decollate_batch(valid_outputs)]
valid_labels = [label(i) for i in decollate_batch(valid_labels)]
# compute metric for current iteration
dice_score(y_pred=valid_outputs, y=valid_labels)
# aggregate the final mean dice result
metric = dice_score.aggregate().item()
# reset the status for next validation round
dice_score.reset()
# Update the best metric and its corresponding epoch if necessary
metric_values.append(metric)
if metric > best_metric:
best_metric = metric
best_metric_epoch = epoch + 1
# Save the model with the best metric
torch.save(model.state_dict(), os.path.join(root_dir, "best_metric_model3.pth"))
print("saved new best metric model")
print(
f"current epoch: {epoch + 1} current mean dice: {metric:.4f}"
f"\nbest mean dice: {best_metric:.4f} "
f"at epoch: {best_metric_epoch}"
)
print(f"train completed, best_metric: {best_metric:.4f} " f"at epoch: {best_metric_epoch}")
plt.figure("train", (12, 6))
plt.subplot(1, 2, 1)
plt.title("Epoch Average Loss")
x = [i + 1 for i in range(len(epoch_loss_values))]
y = epoch_loss_values
plt.xlabel("epoch")
plt.plot(x, y)
plt.subplot(1, 2, 2)
plt.title("Val Mean Dice")
x = [valid_interval * (i + 1) for i in range(len(metric_values))]
y = metric_values
plt.xlabel("epoch")
plt.plot(x, y)
plt.show()
"""## **Test**
---
"""
test_images = sorted(glob.glob(os.path.join(data_dir, "Test/imagesTr", "*.nii.gz")))
test_data = [{"image": image} for image in test_images]
test_org_transforms = Compose(
[
LoadImaged(keys="image"),
EnsureChannelFirstd(keys="image"),
Orientationd(keys=["image"], axcodes="RAS"),
Spacingd(keys=["image"], pixdim=(1.5, 1.5, 1.0), mode="bilinear"),
ScaleIntensityRanged(
keys=["image"],
a_min=-200,
a_max=200,
b_min=0.0,
b_max=1.0,
clip=True,
),
CropForegroundd(keys=["image"], source_key="image"),
]
)
test_org_ds = Dataset(data=test_data, transform=test_org_transforms)
test_org_loader = DataLoader(test_org_ds, batch_size=1, num_workers=4)
post_transforms = Compose(
[
Invertd(
keys="pred",
transform=test_org_transforms,
orig_keys="image",
meta_keys="pred_meta_dict",
orig_meta_keys="image_meta_dict",
meta_key_postfix="meta_dict",
nearest_interp=False,
to_tensor=True,
),
AsDiscreted(keys="pred", argmax=True, to_onehot=3),
SaveImaged(keys="pred", meta_keys="pred_meta_dict", output_dir="./out", output_postfix="seg", resample=False),
]
)
# liver category is represented by channel 0 and the tumor category is represented by channel 1
model.load_state_dict(torch.load(os.path.join(root_dir, "best_metric_model3.pth")))
model.eval()
with torch.no_grad():
for test_data in test_org_loader:
test_inputs = test_data["image"].to(device)
roi_size = (128, 128, 64)
sw_batch_size = 4
test_data["pred"] = sliding_window_inference(test_inputs, roi_size, sw_batch_size, model)
test_data = [post_transforms(i) for i in decollate_batch(test_data)]
# Visualize the predicted results
test_output = from_engine(["pred"])(test_data)
original_image = nib.load(test_output[0].meta["filename_or_obj"]).get_fdata()
plt.figure("check", (18, 6))
plt.subplot(1, 2, 1)
plt.imshow(original_image[:, :, 20], cmap="gray")
plt.subplot(1, 2, 2)
plt.imshow(test_output[0].detach().cpu()[1, :, :, 20])
plt.show()
"""## **Report**
---
In the process of the optimisation, I changed the dropout probability in the VNet network parameters from 0.48 to 0.5, which helps the model to be more robust to overfitting. In the loss function section, I found that the sigmoid function used in the generalised sieve loss function did not perform well and I replaced it with a softmax probabilities to calculate the loss. In the optimiser section, I adjusted the learning rate from 1e-5 to 1e-4 to make the model converge more consistently.
As three data augmentation techniques were added to the previous transformation, I run the training loop again. Based on the results, a maximum of 600 runs gave the best sieve score, 0.7358, out of 588 epochs, indicating that the optimisation was effective and the model learning capability was significantly improved and it means that the model is able to segment the liver and tumor regions with a good accuracy.
Finally, the selected model is evaluated on the test set.The output tensor has 3 channels, where the first channel represents the background (label 0), the second channel represents the liver (label 1), and the third channel represents the tumor (label 2). Visualisation of results based on predictions, only a small number of tumour labels are shown in the colour map, possibly because the tumour area does not appear in most of the slices of the image, or it is too small to be seen in the image. This made it necessary to process the loss function later to improve the network's ability to segment small tumours.
# **Adjusting the loss function**
---
"""
from monai.losses import GeneralizedDiceFocalLoss
# Define CacheDataset and DataLoader for training and validation
train_ds = CacheDataset(data=train_files, transform=train_transforms, cache_rate=1.0, num_workers=4) # set cache_rate=1.0 to cache all the data
# Use batch_size=2 to load images and use RandCropByPosNegLabeld to generate 2 x 4 images for network training
train_loader = DataLoader(train_ds, batch_size=2, shuffle=True, num_workers=4)
valid_ds = CacheDataset(data=valid_files, transform=valid_transforms, cache_rate=1.0, num_workers=4)
valid_loader = DataLoader(valid_ds, batch_size=1, num_workers=4)
# Set the device to GPU
device = torch.device("cuda:0")
# Implement the VNet model
model = VNet(
spatial_dims=3,
in_channels=1,
out_channels=3,
).to(device)
# Apply GeneralizedDiceFocalLoss to improve the network's ability to cut small tumours
# Setting a weight of 2.0 for the 'cancer' class, a weight of 1.0 for the 'liver' class and a weight of 0 for the 'background' class
focal_weight = torch.tensor([0.0, 1.0, 2.0])
loss_fn = GeneralizedDiceFocalLoss(to_onehot_y=True, softmax=True, focal_weight=focal_weight)
# Initializes the Adam optimizer with a learning rate of 1e-4 for model training
optimizer = torch.optim.Adam(model.parameters(), 1e-4)
# Implements the DiceMetric from MONAI,
# which excludes the background and takes the mean of the dice scores for evaluation
dice_score = DiceMetric(include_background=False, reduction="mean")
# Set the number of maximum epochs to 600 and the validation interval to 2
max_epochs = 600
valid_interval = 2
# Keep track of the best metric value and its corresponding epoch
best_metric = -1
best_metric_epoch = -1
# Store epoch loss values and metric values
epoch_loss_values = []
metric_values = []
# Process the model's output and ground truth labels
pred = Compose([AsDiscrete(argmax=True, to_onehot=3)])
label = Compose([AsDiscrete(to_onehot=3)])
for epoch in range(max_epochs):
print("-" * 10)
print(f"epoch {epoch + 1}/{max_epochs}")
# Set the model to training mode
model.train()
# Initializes the epoch loss and step
epoch_loss = 0
step = 0
# Iterate through the training data loader
for batch_data in train_loader:
step += 1
inputs, labels = (
batch_data["image"].to(device),
batch_data["label"].to(device),
)
# Forward pass
optimizer.zero_grad()
outputs = model(inputs)
# Calculate the loss
loss = loss_fn(outputs, labels)
loss.backward()
# Update the model's weights using the optimizer
optimizer.step()
epoch_loss += loss.item()
print(f"{step}/{len(train_ds) // train_loader.batch_size}, " f"train_loss: {loss.item():.4f}")
# Calculate the average epoch loss and appends it to the epoch_loss_values list
epoch_loss /= step
epoch_loss_values.append(epoch_loss)
print(f"epoch {epoch + 1} average loss: {epoch_loss:.4f}")
# If the current epoch is a validation epoch, it sets the model to evaluation mode
if (epoch + 1) % valid_interval == 0:
model.eval()
with torch.no_grad():
for valid_data in valid_loader:
valid_inputs, valid_labels = (
valid_data["image"].to(device),
valid_data["label"].to(device),
)