-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
280 lines (240 loc) · 8.11 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
272
273
274
275
276
277
278
279
280
import os, shutil
import argparse
import time, datetime
import numpy as np
import math
from tqdm import tqdm
import yaml
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as tf
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader, random_split
import _helpers as helpers
from _parsers import parser
import utils.mytransform as mtf
import utils.visual as visual
from utils.dataset import DatasetFromH5PY
from utils.imgdataset import PatchFromImageFolder, pil_loader
from utils.measure import batch_PSNR, batch_SNR
from utils.meter import AverageMeter
from models import *
from loss import *
blind_noise = [0, 55]
args = parser.parse_args()
args.has_cuda = torch.cuda.is_available()
device = 'cuda' if args.has_cuda else 'cpu'
args.data_workers=1
if args.log_dir is not None:
os.makedirs(args.log_dir, exist_ok=True)
else:
args.log_dir = os.path.join('./logs/',
'{0:%Y-%m-%dT%H%M%S}'.format(datetime.datetime.now()))
cudnn.benchmark = True
print('Arguments:')
for p in vars(args).items():
print(' ', p[0]+': ',p[1])
print('\n')
# Data loaders
try:
data_set = DatasetFromH5PY(args.dataset_train,
mtf.Compose([mtf.ToTensor(255)]),
mtf.Compose([mtf.ToTensor(255)]))
except:
data_set = PatchFromImageFolder(args.dataset_train, loader=pil_loader('L'),
transform=tf.ToTensor(), patchSize=40, stride=40, augTimes=1)
numValSamples = math.floor(len(data_set)*0.1)
val_set, train_set = random_split(data_set, [numValSamples, len(data_set)-numValSamples])
train_loader = DataLoader(dataset=train_set, num_workers=args.data_workers, batch_size=args.batch_size, shuffle=True)
val_loader = DataLoader(dataset=val_set, num_workers=args.data_workers, batch_size=args.batch_size, shuffle=False)
print("Train Samples: %d, Validate Samples: %d"%(len(data_set)-numValSamples, numValSamples))
training_logger, testing_logger = helpers.loggers(args)
# Initialize model
model = DnCNN(args.depth, args.n_channels, args.img_channels, args.kernel_size)
model.apply(helpers.weights_init_kaiming)
numParams = helpers.countParam(model)
print("numParameters: %d"%(numParams))
# Loss function and regularizers
criterion = nn.MSELoss(reduction='sum')
# Move to device
criterion = criterion.to(device)
model = model.to(device)
# Optimizer and learning rate schedule
optimizer = optim.Adam(model.parameters(), lr=args.lr,
betas=tuple(args.betas), weight_decay=args.weight_decay)
scheduler = helpers.scheduler(optimizer, args)
class TrainError(Exception):
"""Exception raised for error during training."""
pass
def train(epoch, ttot):
# Run through the training data
if args.has_cuda:
torch.cuda.synchronize()
tepoch = time.time()
el_loss = AverageMeter()
el_measure = AverageMeter()
data_stream = tqdm(enumerate(train_loader, 1))
for batch_idx, data in data_stream:
model.train()
# unpack the data if needed.
try:
x, y = data
except ValueError:
y = data
if args.add_noise:
if args.blind:
noise = torch.zeros(y.size())
stdN = np.random.uniform(blind_noise[0], blind_noise[1], size=noise.size(0))
for n in range(noise.size(0)):
sizeN = noise[0, :, :, :].size()
noise[n, :, :, :] = torch.FloatTensor(sizeN).normal_(mean=0, std=stdN[n]/255.)
else:
noise = torch.FloatTensor(y.size()).normal_(mean=0, std=args.noise_level/255.)
x = y + noise
# where are we.
dataset_size = len(train_set)
dataset_batches = len(train_loader)
iteration = (epoch-1) * (dataset_size // args.batch_size) + batch_idx + 1
x, y = x.to(device), y.to(device)
optimizer.zero_grad()
model.zero_grad()
y_hat = model(x)
loss = criterion(y_hat, noise.to(device)) / (x.size(0)*2)
if np.isnan(loss.data.item()):
raise(TrainError('model returned nan during training'))
# compute gradient and step
loss.backward()
if args.clip_grad:
nn.utils.clip_grad_norm_(model.parameters(), args.clipping)
optimizer.step()
# measure performance and record loss
model.eval()
y_tilde = model(x)
y_tilde = torch.clamp(x-y_tilde, 0., 1.)
l_measure = batch_SNR(y_tilde, y, 1.) if args.snr else batch_PSNR(y_tilde, y, 1.)
el_measure.update(l_measure, y.size(0))
el_loss.update(loss.data.item(), y.size(0))
# update the progress.
data_stream.set_description((
'epoch: {epoch}/{epochs} | '
'iteration: {iteration} | '
'progress: [{trained}/{total}] ({progress:.0f}%) | '
'loss: {loss.val:.4f}({loss.avg:.4f}) '
'{measure}: {mvalue.val:.3f}({mvalue.avg:.3f})'
).format(
epoch=epoch,
epochs=args.epochs,
iteration=iteration,
trained=batch_idx*args.batch_size,
total=dataset_size,
progress=(100.*batch_idx/dataset_batches),
loss=el_loss,
measure=('SNR' if args.snr else 'PSNR'),
mvalue=el_measure,
))
if args.log_dir is not None and iteration % args.log_interval == 0:
training_logger(el_loss.avg, optimizer, tepoch, ttot)
if args.visualize: # send losses and sample images to the visdom server
visual.visualize_scalar(
loss.data.item(),
'Loss',
iteration=iteration,
env='Train'
)
visual.visualize_images(
x.data*255,
'Noisy Images',
env='Train'
)
visual.visualize_images(
y_tilde.data*255,
'Denoised Images',
env='Train'
)
return ttot + time.time() - tepoch
def test(epoch, ttot):
model.eval()
with torch.no_grad():
test_loss = AverageMeter()
test_measure = AverageMeter()
for batch_idx, data in enumerate(val_loader, 1):
# unpack the data if needed.
try:
x, y = data
except ValueError:
y = data
if args.add_noise:
if args.blind:
noise = torch.zeros(y.size())
stdN = np.random.uniform(blind_noise[0], blind_noise[1], size=noise.size(0))
for n in range(noise.size(0)):
sizeN = noise[0, :, :, :].size()
noise[n, :, :, :] = torch.FloatTensor(sizeN).normal_(mean=0, std=stdN[n]/255.)
else:
noise = torch.FloatTensor(y.size()).normal_(mean=0, std=args.noise_level/255.)
x = y + noise
# where are we.
dataset_size = len(val_set)
dataset_batches = len(val_loader)
iteration = (epoch-1) * (dataset_size // args.batch_size) + batch_idx + 1
x, y = x.to(device), y.to(device)
y_tilde = model(x)
loss = criterion(y_tilde, noise.to(device)) / (x.size(0)*2)
y_tilde = torch.clamp(x-y_tilde, 0., 1.)
l_measure = batch_SNR(y_tilde, y, 1.) if args.snr else batch_PSNR(y_tilde, y, 1.)
test_loss.update(loss.data.item(), y.size(0))
test_measure.update(l_measure, y.size(0))
# Report results
if args.log_dir is not None and iteration % args.log_interval == 0:
testing_logger(epoch, test_loss.avg, test_measure.avg, optimizer)
if args.visualize: # send losses and sample images to the visdom server
visual.visualize_scalar(
loss.data.item(),
'Loss',
iteration=iteration,
env='Test'
)
visual.visualize_images(
x.data*255,
'Noisy Images',
env='Test'
)
visual.visualize_images(
y_tilde.data*255,
'Denoised Images',
env='Test'
)
print('[Epoch %2d] Average test loss: %.3f, Average test %s: %.3f'
%(epoch, test_loss.avg, 'SNR' if args.snr else 'PSNR', test_measure.avg))
return test_loss.avg, test_measure.avg
def main():
save_path = args.log_dir if args.log_dir is not None else '.'
# Save argument values to yaml file
args_file_path = os.path.join(save_path, 'args.yaml')
with open(args_file_path, 'w') as f:
yaml.dump(vars(args), f, default_flow_style=False)
save_model_path = os.path.join(save_path, 'checkpoint.pth.tar')
best_model_path = os.path.join(save_path, 'best.pth.tar')
best_measure = 0.
t = 0.
for e in range(1, args.epochs+1):
# Update the learning rate
scheduler.step()
#try:
t = train(e, t)
loss, c_measure = test(e, time)
torch.save({'epoch': e,
'state_dict': model.state_dict(),
'(p)snr': c_measure,
'loss': loss,
'optimizer': optimizer.state_dict()}, save_model_path)
if c_measure >= best_measure:
shutil.copyfile(save_model_path, best_model_path)
best_measure = c_measure
print('Best %s: %.3f' %('SNR' if args.snr else 'PSNR', best_measure))
if __name__ =='__main__':
try:
main()
except KeyboardInterrupt:
print('Keyboard interrupt; exiting')