-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
63 lines (52 loc) · 1.75 KB
/
utils.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
import os
import random
import numpy as np
import cv2
from tqdm import tqdm
import torch
from sklearn.utils import shuffle
from metrics import precision, recall, F2, dice_score, jac_score, hd_dist
from sklearn.metrics import accuracy_score, confusion_matrix
""" Seeding the randomness. """
def seeding(seed):
random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
""" Create a directory """
def create_dir(path):
if not os.path.exists(path):
os.makedirs(path)
""" Shuffle the dataset. """
def shuffling(x, y):
x, y = shuffle(x, y, random_state=42)
return x, y
def epoch_time(start_time, end_time):
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs
def print_and_save(file_path, data_str):
print(data_str)
with open(file_path, "a") as file:
file.write(data_str)
file.write("\n")
def calculate_metrics(y_true, y_pred):
y_true = y_true.detach().cpu().numpy()
y_pred = y_pred.detach().cpu().numpy()
y_pred = y_pred > 0.5
y_pred = y_pred.reshape(-1)
y_pred = y_pred.astype(np.uint8)
y_true = y_true > 0.5
y_true = y_true.reshape(-1)
y_true = y_true.astype(np.uint8)
## Score
score_jaccard = jac_score(y_true, y_pred)
score_f1 = dice_score(y_true, y_pred)
score_recall = recall(y_true, y_pred)
score_precision = precision(y_true, y_pred)
score_fbeta = F2(y_true, y_pred)
score_acc = accuracy_score(y_true, y_pred)
return [score_jaccard, score_f1, score_recall, score_precision, score_acc, score_fbeta]