-
Notifications
You must be signed in to change notification settings - Fork 2
/
train.py
271 lines (217 loc) · 8.6 KB
/
train.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
import os
import random
import time
import datetime
import numpy as np
import albumentations as A
import cv2
from PIL import Image
from glob import glob
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from utils import seeding, create_dir, print_and_save, shuffling, epoch_time, calculate_metrics
from model import Model
from metrics import DiceLoss, DiceBCELoss
def load_names(path, file_path):
f = open(file_path, "r")
data = f.read().split("\n")[:-1]
images = [os.path.join(path,"images", name) + ".jpg" for name in data]
masks = [os.path.join(path,"masks", name) + ".jpg" for name in data]
return images, masks
def load_data(path):
train_names_path = f"{path}/train.txt"
valid_names_path = f"{path}/val.txt"
train_x, train_y = load_names(path, train_names_path)
valid_x, valid_y = load_names(path, valid_names_path)
return (train_x, train_y), (valid_x, valid_y)
class DATASET(Dataset):
def __init__(self, images_path, masks_path, size, transform=None):
super().__init__()
self.images_path = images_path
self.masks_path = masks_path
self.transform = transform
self.n_samples = len(images_path)
def __getitem__(self, index):
""" Image """
image = cv2.imread(self.images_path[index], cv2.IMREAD_COLOR)
mask = cv2.imread(self.masks_path[index], cv2.IMREAD_GRAYSCALE)
if self.transform is not None:
augmentations = self.transform(image=image, mask=mask)
image = augmentations["image"]
mask = augmentations["mask"]
image = cv2.resize(image, size)
image = np.transpose(image, (2, 0, 1))
image = image/255.0
mask = cv2.resize(mask, size)
mask = np.expand_dims(mask, axis=0)
mask = mask/255.0
return image, mask
def __len__(self):
return self.n_samples
def train(model, loader, optimizer, loss_fn, device):
model.train()
epoch_loss = 0.0
epoch_jac = 0.0
epoch_f1 = 0.0
epoch_recall = 0.0
epoch_precision = 0.0
for i, (x, y) in enumerate(loader):
x = x.to(device, dtype=torch.float32)
y = y.to(device, dtype=torch.float32)
optimizer.zero_grad()
y_pred = model(x)
loss = loss_fn(y_pred, y)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
""" Calculate the metrics """
batch_jac = []
batch_f1 = []
batch_recall = []
batch_precision = []
for yt, yp in zip(y, y_pred):
score = calculate_metrics(yt, yp)
batch_jac.append(score[0])
batch_f1.append(score[1])
batch_recall.append(score[2])
batch_precision.append(score[3])
epoch_jac += np.mean(batch_jac)
epoch_f1 += np.mean(batch_f1)
epoch_recall += np.mean(batch_recall)
epoch_precision += np.mean(batch_precision)
epoch_loss = epoch_loss/len(loader)
epoch_jac = epoch_jac/len(loader)
epoch_f1 = epoch_f1/len(loader)
epoch_recall = epoch_recall/len(loader)
epoch_precision = epoch_precision/len(loader)
return epoch_loss, [epoch_jac, epoch_f1, epoch_recall, epoch_precision]
def evaluate(model, loader, loss_fn, device):
model.eval()
epoch_loss = 0
epoch_loss = 0.0
epoch_jac = 0.0
epoch_f1 = 0.0
epoch_recall = 0.0
epoch_precision = 0.0
with torch.no_grad():
for i, (x, y) in enumerate(loader):
x = x.to(device, dtype=torch.float32)
y = y.to(device, dtype=torch.float32)
y_pred = model(x)
loss = loss_fn(y_pred, y)
epoch_loss += loss.item()
""" Calculate the metrics """
batch_jac = []
batch_f1 = []
batch_recall = []
batch_precision = []
for yt, yp in zip(y, y_pred):
score = calculate_metrics(yt, yp)
batch_jac.append(score[0])
batch_f1.append(score[1])
batch_recall.append(score[2])
batch_precision.append(score[3])
epoch_jac += np.mean(batch_jac)
epoch_f1 += np.mean(batch_f1)
epoch_recall += np.mean(batch_recall)
epoch_precision += np.mean(batch_precision)
epoch_loss = epoch_loss/len(loader)
epoch_jac = epoch_jac/len(loader)
epoch_f1 = epoch_f1/len(loader)
epoch_recall = epoch_recall/len(loader)
epoch_precision = epoch_precision/len(loader)
return epoch_loss, [epoch_jac, epoch_f1, epoch_recall, epoch_precision]
if __name__ == "__main__":
""" Seeding """
seeding(42)
""" Directories """
create_dir("files")
""" Training logfile """
train_log_path = "files/train_log.txt"
if os.path.exists(train_log_path):
print("Log file exists")
else:
train_log = open("files/train_log.txt", "w")
train_log.write("\n")
train_log.close()
""" Record Date & Time """
datetime_object = str(datetime.datetime.now())
print_and_save(train_log_path, datetime_object)
print("")
""" Hyperparameters """
image_size = 256
size = (image_size, image_size)
batch_size = 8
num_epochs = 500
lr = 1e-4
early_stopping_patience = 50
checkpoint_path = "files/checkpoint.pth"
path = "/../Kvasir-SEG"
data_str = f"Image Size: {size}\nBatch Size: {batch_size}\nLR: {lr}\nEpochs: {num_epochs}\n"
data_str += f"Early Stopping Patience: {early_stopping_patience}\n"
print_and_save(train_log_path, data_str)
""" Dataset """
(train_x, train_y), (valid_x, valid_y) = load_data(path)
train_x, train_y = shuffling(train_x, train_y)
data_str = f"Dataset Size:\nTrain: {len(train_x)} - Valid: {len(valid_x)}\n"
print_and_save(train_log_path, data_str)
""" Data augmentation: Transforms """
transform = A.Compose([
A.Rotate(limit=35, p=0.3),
A.HorizontalFlip(p=0.3),
A.VerticalFlip(p=0.3),
A.CoarseDropout(p=0.3, max_holes=10, max_height=32, max_width=32)
])
""" Dataset and loader """
train_dataset = DATASET(train_x, train_y, size, transform=transform)
valid_dataset = DATASET(valid_x, valid_y, size, transform=None)
train_loader = DataLoader(
dataset=train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=2
)
valid_loader = DataLoader(
dataset=valid_dataset,
batch_size=batch_size,
shuffle=False,
num_workers=2
)
""" Model """
device = torch.device('cuda')
model = Model()
model = model.to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience=5, verbose=True)
loss_fn = DiceBCELoss()
loss_name = "BCE Dice Loss"
data_str = f"Optimizer: Adam\nLoss: {loss_name}\n"
print_and_save(train_log_path, data_str)
""" Training the model """
best_valid_metrics = 0.0
early_stopping_count = 0
for epoch in range(num_epochs):
start_time = time.time()
train_loss, train_metrics = train(model, train_loader, optimizer, loss_fn, device)
valid_loss, valid_metrics = evaluate(model, valid_loader, loss_fn, device)
scheduler.step(valid_loss)
if valid_metrics[1] > best_valid_metrics:
data_str = f"Valid F1 improved from {best_valid_metrics:2.4f} to {valid_metrics[1]:2.4f}. Saving checkpoint: {checkpoint_path}"
print_and_save(train_log_path, data_str)
best_valid_metrics = valid_metrics[1]
torch.save(model.state_dict(), checkpoint_path)
early_stopping_count = 0
elif valid_metrics[1] < best_valid_metrics:
early_stopping_count += 1
end_time = time.time()
epoch_mins, epoch_secs = epoch_time(start_time, end_time)
data_str = f"Epoch: {epoch+1:02} | Epoch Time: {epoch_mins}m {epoch_secs}s\n"
data_str += f"\tTrain Loss: {train_loss:.4f} - Jaccard: {train_metrics[0]:.4f} - F1: {train_metrics[1]:.4f} - Recall: {train_metrics[2]:.4f} - Precision: {train_metrics[3]:.4f}\n"
data_str += f"\t Val. Loss: {valid_loss:.4f} - Jaccard: {valid_metrics[0]:.4f} - F1: {valid_metrics[1]:.4f} - Recall: {valid_metrics[2]:.4f} - Precision: {valid_metrics[3]:.4f}\n"
print_and_save(train_log_path, data_str)
if early_stopping_count == early_stopping_patience:
data_str = f"Early stopping: validation loss stops improving from last {early_stopping_patience} continously.\n"
print_and_save(train_log_path, data_str)
break