-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
187 lines (148 loc) · 5.28 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
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
#!/usr/bin/env python3
import os
import pickle
import json
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
from torch.utils.data import DataLoader
import pathlib
from customdatasets import CustomDataSet
from transformations import Compose, RandomFlip, Resize
from transformations import MoveAxis, Normalize01, RandomCrop
import segmentation_models_pytorch as smp
from sklearn.model_selection import train_test_split
from os import walk
import torch as t
import numpy as np
import torch.nn as nn
def get_files(path):
files = []
for (dirpath, dirnames, filenames) in walk(path):
for names in sorted(filenames):
files.append(dirpath + '/' + names)
return files
def makedirs(dirname):
if not os.path.exists(dirname):
os.makedirs(dirname)
def get_model(device, cl):
unet = smp.Unet('resnet152', classes=cl, activation=None, encoder_weights='imagenet')
if t.cuda.is_available():
unet.cuda()
unet = unet.to(device)
return unet
def import_data(args, batch_sz, set, img_size, crop_size):
if set == 'project_1':
inputs = get_files('./input_data/project_1/image/')
targets = get_files('./input_data/project_1/target/')
if set == 'project_2':
inputs = get_files('./input_data/project_2/image/')
targets = get_files('./input_data/project_2/target/')
if set == 'project_3':
inputs = get_files('./input_data/project_3/image/')
targets = get_files('./input_data/project_3/target/')
# ratio of whole number of images/ number of training images
split = 0.8
inputs_train, inputs_valid = train_test_split(
inputs,
random_state=42,
train_size=split,
shuffle=True)
targets_train, targets_valid = train_test_split(
targets,
random_state=42,
train_size=split,
shuffle=True)
transforms = Compose([
MoveAxis(),
Normalize01(),
Resize(img_size),
RandomCrop(crop_size),
RandomFlip()
])
# train dataset
dataset_train = CustomDataSet(inputs=inputs_train,
targets=targets_train,
transform=transforms)
# validation dataset
dataset_valid = CustomDataSet(inputs=inputs_valid,
targets=targets_valid,
transform=transforms)
batchsize = batch_sz
# train dataloader
dataloader_training = DataLoader(dataset=dataset_train,
batch_size=batchsize,
shuffle=True)
# validation dataloader
dataloader_validation = DataLoader(dataset=dataset_valid,
batch_size=batchsize,
shuffle=True)
return dataloader_training, dataloader_validation
def eval_classification(f, dload, device):
corrects, losses = [], []
for input, target in dload:
input, target = input.to(device), target.to(device)
logits = f(input)
loss = nn.CrossEntropyLoss(reduce=False)(logits, target).cpu().numpy()
losses.extend(loss)
correct = (logits.max(1)[1] == target).float().cpu().numpy()
logits_max = logits.max(1)[1].float().cpu().numpy()
label = target.float().cpu().numpy()
# You can plot the evaluation results, if needed
'''
fig, axs = plt.subplots(2)
axs[0].imshow(logits_max[0,:,:])
axs[1].imshow(label[0,:,:])
plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()
'''
corrects.extend(correct)
loss = np.mean(losses)
correct = np.mean(corrects)
return correct, loss
def checkpoint(f, tag, args, device, dload_train, dload_valid):
f.cpu()
ckpt_dict = {
"model_state_dict": f.state_dict(),
"train": dload_train,
"valid": dload_valid
}
t.save(ckpt_dict, os.path.join(args.save_dir, tag))
f.to(device)
def logits2rgb(img):
red = [200, 0, 10]
green = [187,207, 74]
blue = [0,108,132]
yellow = [255,204,184]
black = [0,0,0]
white = [226,232,228]
cyan = [174,214,220]
orange = [232,167,53]
colours = [red, green, blue, yellow, black, white, cyan, orange]
shape = np.shape(img)
h = int(shape[0])
w = int(shape[1])
col = np.zeros((h, w, 3))
unique = np.unique(img)
for i, val in enumerate(unique):
mask = np.where(img == val)
for j, row in enumerate(mask[0]):
x = mask[0][j]
y = mask[1][j]
col[x, y, :] = colours[int(val)]
return col.astype(int)
def mIOU(pred, label, num_classes=8):
iou_list = list()
present_iou_list = list()
for sem_class in range(num_classes):
pred_inds = (pred == sem_class)
target_inds = (label == sem_class)
if target_inds.sum().item() == 0:
iou_now = float('nan')
else:
intersection_now = (pred_inds[target_inds]).sum().item()
union_now = pred_inds.sum().item() + target_inds.sum().item() - intersection_now
iou_now = float(intersection_now) / float(union_now)
present_iou_list.append(iou_now)
iou_list.append(iou_now)
miou = np.mean(present_iou_list)
return miou