-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrain_Unet.py
147 lines (129 loc) · 8.16 KB
/
train_Unet.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
import os
import argparse
import torch
import numpy as np
import torchvision.transforms as transforms
from tqdm import tqdm
from time import sleep
from datasets.utils import DeepLIIFImgMaskDataset, create_color_transform, create_data_ihc_aug
from models import CustomUnet, load_optimal_hyperparameters
from performance import dice, f1_m, precision_m, recall_m, dice_by_sample
def dice_coef_loss(pred, targs):
return 1 - dice(pred, targs)
def main():
parser = argparse.ArgumentParser(
description='Train Unet Model for IHC nuclei segmentation for benchmarking generator'
' trained in a supervised setting')
parser.add_argument('dataihcroot_images', type=str, default=None,
help='IHC images root path')
parser.add_argument('--dataset_name', type=str, choices=["deepliif", "warwick"], default="deepliif",
help='Choose between deepliif (KI67) or warwick (HER2) dataset (not implemented)')
parser.add_argument('--exp_save_path', type=str, default="./",
help='Result save path (must contain optimal set of parameters produced by tuning_Unet.py)')
parser.add_argument('--num_epochs', type=int, default=600,
help='Number of epochs for training (default: 200)')
parser.add_argument('--batch_size_validation', type=int, default=34,
help='Batch size for validation (default: 34)')
parser.add_argument('--workers', type=int, default=5,
help='Number of worker nodes (default: 5)')
args = parser.parse_args()
optimal_parameters_file_path = os.path.join(args.exp_save_path, "optimal_parameters.pickle")
if not os.path.isfile(optimal_parameters_file_path):
raise ValueError("Please provide a valid path for experiment results")
mean = 0.5
std = 0.5
if args.dataset_name == "deepliif":
dataset_ihc_train_path = os.path.join(args.dataihcroot_images, "DeepLIIF_Training_Set")
dataset_ihc_val_path = os.path.join(args.dataihcroot_images, "DeepLIIF_Validation_Set")
dataset_ihc_train = DeepLIIFImgMaskDataset(dataset_ihc_train_path,
img_transform=transforms.Compose([transforms.RandomChoice(
[transforms.RandomRotation((0, 0)),
transforms.RandomRotation((90, 90)),
transforms.RandomRotation((2 * 90, 2 * 90)),
transforms.RandomRotation((3 * 90, 3 * 90))]),
transforms.RandomVerticalFlip(),
transforms.RandomHorizontalFlip(),
transforms.RandomCrop((256, 256)),
transforms.ToTensor(),
transforms.Normalize((mean, mean, mean),
(std, std, std))]),
mask_transform=transforms.Compose([transforms.RandomChoice(
[transforms.RandomRotation((0, 0)),
transforms.RandomRotation((90, 90)),
transforms.RandomRotation((2 * 90, 2 * 90)),
transforms.RandomRotation((3 * 90, 3 * 90))]),
transforms.RandomVerticalFlip(),
transforms.RandomHorizontalFlip(),
transforms.RandomCrop((256, 256)),
transforms.ToTensor()])
)
dataset_ihc_val = DeepLIIFImgMaskDataset(dataset_ihc_val_path,
img_transform=transforms.Compose([transforms.ToTensor(),
transforms.Normalize(
(mean, mean, mean),
(std, std,
std))]),
mask_transform=transforms.ToTensor())
else:
raise NotImplementedError
optimal_parameters = load_optimal_hyperparameters(optimal_parameters_file_path)
dataloader_ihc_train = torch.utils.data.DataLoader(dataset_ihc_train,
batch_size=int(optimal_parameters["batch_size"]),
shuffle=True, num_workers=args.workers)
dataloader_ihc_val = torch.utils.data.DataLoader(dataset_ihc_val, batch_size=args.batch_size_validation,
shuffle=False, num_workers=args.workers)
device = torch.device("cuda:0" if (torch.cuda.is_available()) else "cpu")
color_transform = create_color_transform(1, 0.75)
criterion_consistency = torch.nn.L1Loss()
model = CustomUnet(ngf=int(optimal_parameters["ngf"]), dropout_value=optimal_parameters["dropout"])
optimizer = torch.optim.Adam(model.parameters(), lr=optimal_parameters["learning_rate"],
betas=(0.9, 0.999), weight_decay=optimal_parameters["decay"])
model = model.to(device)
best_score = 0
for epoch in range(args.num_epochs):
accuracies = []
f1_scores = []
precisions = []
recalls = []
dice_scores = []
with tqdm(dataloader_ihc_train, unit="batch") as tepoch:
tepoch.set_description(f"Epoch {epoch}, training :")
for data, target in tepoch:
data_aug = create_data_ihc_aug(data, color_transform, mean, std).to(device)
data, target = data.to(device), target.to(device)
model.train()
optimizer.zero_grad()
pred = model(data)
pred_aug = model(data_aug)
loss_consistency = criterion_consistency(pred, pred_aug)
err_train = dice_coef_loss(pred, target) + loss_consistency
err_train.backward()
optimizer.step()
pred = (pred > 0.5).float()
perf = f1_m(pred, target).cpu().item()
tepoch.set_postfix(loss=err_train.item(), f1_score=perf)
sleep(0.1)
with torch.no_grad():
for data, target in dataloader_ihc_val:
data, target = data.to(device), target.to(device)
model.eval()
pred = model(data)
pred = (pred > 0.5).float()
perf = f1_m(pred, target).cpu().item()
accuracies.append(((pred == target).sum(axis=(1, 2, 3)) / target[0].numel()).mean().cpu().item())
f1_scores.append(perf)
precisions.append(precision_m(pred, target).cpu().item())
recalls.append(recall_m(pred, target).cpu().item())
dice_scores.append(dice_by_sample(pred, target).cpu().item())
score = np.mean(f1_scores)
print(f"Averaged validation : acc = {np.mean(accuracies)}, Dice = {np.mean(dice_scores)}, "
f"F1 score = {score}, precision = {np.mean(precisions)}, recall = {np.mean(recalls)}")
if score > best_score:
best_score = score
best_perf = {"acc": np.mean(accuracies), "dice": np.mean(dice_scores), "f1_score": score,
"precision": np.mean(precisions), "recall": np.mean(recalls)}
PATH = os.path.join(args.exp_save_path, "best_model.pt")
torch.save(model.state_dict(), PATH)
print(f"Best performance on validation set: {best_perf}")
if __name__ == '__main__':
main()