-
Notifications
You must be signed in to change notification settings - Fork 2
/
train_print.py
228 lines (182 loc) · 7.5 KB
/
train_print.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
# =============================================================================
# Code to train EDoF CNNS models
# =============================================================================
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', choices=['cervix93','fraunhofer','fraunhofer_separate','fraunhofer_elastic','fraunhofer_elastic_only'], default='fraunhofer_elastic_only')
parser.add_argument('--image_size', choices=[512,640], default=512)
parser.add_argument('--method', choices=[
'EDOF_CNN_max','EDOF_CNN_3D','EDOF_CNN_concat','EDOF_CNN_backbone','EDOF_CNN_fast','EDOF_CNN_RGB','EDOF_CNN_pairwise'], default='EDOF_CNN_fast')
parser.add_argument('--Z', choices=[3,5,7,9], type=int, default=5)
parser.add_argument('--fold', type=int, choices=range(5),default=0)
parser.add_argument('--epochs', type=int, default=200)
parser.add_argument('--batchsize', type=int, default=6)
parser.add_argument('--lr', type=float, default=1e-3)
parser.add_argument('--cudan', type=int, default=0)
parser.add_argument('--image_channels', choices=['rgb','grayscale'], default='grayscale')
args = parser.parse_args()
import numpy as np
from time import time
from torch import optim
from torch.utils.data import Dataset, DataLoader, Subset
from sklearn.model_selection import KFold
import torch
import dataset, models
from tqdm import tqdm
from PIL import Image
device = torch.device('cuda:'+str(args.cudan) if torch.cuda.is_available() else 'cpu')
#define transforms if rgb or not
if args.image_channels=='rgb':
train_transform=dataset.aug_transforms_rgb
test_transform=dataset.val_transforms_rgb
else:
train_transform=dataset.aug_transforms
test_transform=dataset.val_transforms
############################# data loaders #######################################
tr_ds = dataset.Dataset('train', train_transform, args.dataset, args.Z, args.fold)
tr = DataLoader(tr_ds, args.batchsize, True, pin_memory=True)
ts_ds = dataset.Dataset('test', test_transform, args.dataset, args.Z, args.fold)
ts = DataLoader(ts_ds, args.batchsize,False, pin_memory=True)
#to view images
tst = DataLoader(ts_ds, 1,False, pin_memory=True)
def view_images(epochv):
Yhats=[]
Ytrues=[]
stacks=[]
model.eval()
with torch.no_grad():
for XX, Y in tst:
XX = [X.to(device) for X in XX]
Y = Y.to(device, torch.float)
Yhat = model(XX)
Yhats.append(Yhat[0].cpu().numpy())
Ytrues.append(Y[0].cpu().numpy())
stacks.append([z.cpu().numpy() for z in XX])
from PIL import Image
from matplotlib import cm
for i in range(20):
if args.epochs==200:
stack = stacks[i]
for s in range(args.Z):
stack0 = Image.fromarray(stack[s][0,0,:,:]* 255)
if stack0.mode != 'RGB':
stack0 = stack0.convert('RGB')
stack0.save('teste_'+str(i)+'_stack_'+str(s)+'.png')
x = np.moveaxis(Yhats[i], 0,2 )
xt = np.moveaxis(Ytrues[i], 0,2 )
x = x[:, :, 0]
xt = xt[:, :, 0]
# img = Image.fromarray(np.uint8(x*255), 'RGB')
img = Image.fromarray(x* 255)
if img.mode != 'RGB':
img = img.convert('RGB')
# img.save('image/teste'+str(i)+'_epoch_'+str(epochv)+'.png')
img.save('PRED_'+str(i)+'.png')
# imgt = Image.fromarray(np.uint8(xt*255), 'RGB')
imgt = Image.fromarray(xt* 255)
if imgt.mode != 'RGB':
imgt = imgt.convert('RGB')
imgt.save('GT_'+str(i)+'.png')
def test(val):
model.eval()
avg_loss_val = 0
with torch.no_grad():
for XX, Y in val:
XX = [X.to(device, torch.float) for X in XX]
Y = Y.to(device, torch.float)
Yhat = model(XX)
loss = model.loss(Yhat, Y.to(torch.float))
avg_loss_val += loss / len(val)
return avg_loss_val
def train(tr, val, epochs=args.epochs, verbose=True):
for epoch in range(epochs):
if verbose:
print(f'* Epoch {epoch+1}/{args.epochs}')
tic = time()
model.train()
avg_acc = 0
avg_loss = 0
for XX, Y in tr:
XX = [X.to(device, torch.float) for X in XX]
Y = Y.to(device, torch.float)
opt.zero_grad()
Yhat = model(XX)
loss = model.loss(Yhat, Y)
loss.backward()
opt.step()
avg_loss += loss / len(tr)
dt = time() - tic
out = ' - %ds - Loss: %f' % (dt, avg_loss)
if val:
model.eval()
out += ', Test loss: %f' % test(val)
if verbose:
print(out)
scheduler.step(avg_loss)
#uncomment to see the examples
view_images(epoch)
prefix = '-'.join(f'{k}-{v}' for k, v in vars(args).items())
if args.method=='EDOF_CNN_max':
model = models.EDOF_CNN_max()
elif args.method=='EDOF_CNN_3D':
model = models.EDOF_CNN_3D(args.Z)
elif args.method=='EDOF_CNN_backbone':
model = models.EDOF_CNN_backbone()
elif args.method=='EDOF_CNN_fast':
model = models.EDOF_CNN_fast()
elif args.method=='EDOF_CNN_RGB':
model = models.EDOF_CNN_RGB()
elif args.method=='EDOF_CNN_pairwise':
model = models.EDOF_CNN_pairwise()
else:
model = models.EDOF_CNN_concat()
model.load_state_dict(torch.load('dataset-fraunhofer_elastic_only-image_size-512-method-EDOF_CNN_fast-Z-5-fold-0-epochs-200-batchsize-6-lr-0.001-image_channels-grayscale.pth'))
model = model.to(device)
opt = optim.Adam(model.parameters(), args.lr)
scheduler = optim.lr_scheduler.ReduceLROnPlateau(opt, verbose=True,patience=5)
view_images(0)
# train(tr, ts)
# torch.save(model.state_dict(), str(prefix)+'.pth')
#print some metrics
# def predict_metrics(data):
# model.eval()
# Phat = []
# Y_true=[]
# with torch.no_grad():
# for XX, Y in data:
# XX = [X.to(device, torch.float) for X in XX]
# Y = Y.to(device, torch.float)
# Yhat = model(XX)
# Phat += list(Yhat.cpu().numpy())
# Y_true += list(Y.cpu().numpy())
# return Y_true, Phat
# from skimage.metrics import structural_similarity as ssim
# from skimage.metrics import mean_squared_error, peak_signal_noise_ratio, normalized_root_mse
# data_test = DataLoader(ts_ds, 1,False, pin_memory=True)
# Y_true, Phat = predict_metrics(data_test)
# mse = np.mean([mean_squared_error(Y_true[i], Phat[i]) for i in range(len(Y_true))])
# rmse = np.mean([normalized_root_mse(Y_true[i], Phat[i]) for i in range(len(Y_true))])
# ssim =np.mean([ssim(Y_true[i], Phat[i],channel_axis=0) for i in range(len(Y_true))])
# psnr =np.mean([peak_signal_noise_ratio(Y_true[i], Phat[i]) for i in range(len(Y_true))])
# f = open('results\\'+ str(prefix)+'.txt', 'a+')
# f.write('\n\nModel:'+str(prefix)+
# ' \nMSE:'+ str(mse)+
# ' \nRMSE:'+ str(rmse)+
# ' \nSSIM:'+str(ssim)+
# ' \nPSNR:'+ str(psnr))
# f.close()
# def test_cyto(path_f='test_data_aligned',img_size=640):
# cyto_ds = dataset.Dataset_folder(dataset.val_transforms, path_f , args.Z,img_size)
# cyto_ts = DataLoader(cyto_ds, 1 ,False, pin_memory=True)
# model.eval()
# avg_loss_val = 0
# with torch.no_grad():
# for XX in tqdm(cyto_ts):
# print(XX)
# XX = [X.to(device, torch.float) for X in XX]
# Yhat = model(XX)
# final_edf=Yhat.cpu().numpy()
# img=Image.fromarray(final_edf[0,0,:,:]* 255)
# if img.mode != 'RGB':
# img = img.convert('RGB')
# img.save('teste_cyto.png')