-
Notifications
You must be signed in to change notification settings - Fork 0
/
HiCARN_1_Train.py
191 lines (148 loc) · 6.17 KB
/
HiCARN_1_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
import os
import time
import numpy as np
from tqdm import tqdm
import torch
import torch.optim as optim
from torch.utils.data import TensorDataset, DataLoader
from Models.HiCARN_1 import Generator
from Models.HiCARN_1_Loss import GeneratorLoss
from Utils.SSIM import ssim
from math import log10
from Arg_Parser import root_dir
cs = np.column_stack
def adjust_learning_rate(epoch):
lr = 0.0003 * (0.1 ** (epoch // 30))
return lr
# data_dir: directory storing processed data
data_dir = os.path.join(root_dir, 'data')
# out_dir: directory storing checkpoint files
out_dir = os.path.join(root_dir, 'checkpoints')
os.makedirs(out_dir, exist_ok=True)
datestr = time.strftime('%m_%d_%H_%M')
visdom_str = time.strftime('%m%d')
resos = '10kb40kb'
chunk = 40
stride = 40
bound = 201
pool = 'nonpool'
name = 'HiCARN_1'
num_epochs = 200
batch_size = 64
# whether using GPU for training
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print("CUDA available? ", torch.cuda.is_available())
print("Device being used: ", device)
# prepare training dataset
train_file = os.path.join(data_dir, f'hicarn_{resos}_c{chunk}_s{stride}_b{bound}_{pool}_train.npz')
train = np.load(train_file)
train_data = torch.tensor(train['data'], dtype=torch.float)
train_target = torch.tensor(train['target'], dtype=torch.float)
train_inds = torch.tensor(train['inds'], dtype=torch.long)
train_set = TensorDataset(train_data, train_target, train_inds)
# prepare valid dataset
valid_file = os.path.join(data_dir, f'hicarn_{resos}_c{chunk}_s{stride}_b{bound}_{pool}_valid.npz')
valid = np.load(valid_file)
valid_data = torch.tensor(valid['data'], dtype=torch.float)
valid_target = torch.tensor(valid['target'], dtype=torch.float)
valid_inds = torch.tensor(valid['inds'], dtype=torch.long)
valid_set = TensorDataset(valid_data, valid_target, valid_inds)
# DataLoader for batched training
train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True, drop_last=True)
valid_loader = DataLoader(valid_set, batch_size=batch_size, shuffle=False, drop_last=True)
# load network
netG = Generator(num_channels=64).to(device)
# loss function
criterionG = GeneratorLoss().to(device)
# optimizer
optimizerG = optim.Adam(netG.parameters(), lr=0.0003)
ssim_scores = []
psnr_scores = []
mse_scores = []
mae_scores = []
best_ssim = 0
for epoch in range(1, num_epochs + 1):
run_result = {'nsamples': 0, 'g_loss': 0, 'g_score': 0}
alr = adjust_learning_rate(epoch)
optimizerG = optim.Adam(netG.parameters(), lr=alr)
for p in netG.parameters():
if p.grad is not None:
del p.grad # free some memory
torch.cuda.empty_cache()
netG.train()
train_bar = tqdm(train_loader)
for data, target, _ in train_bar:
batch_size = data.size(0)
run_result['nsamples'] += batch_size
real_img = target.to(device)
z = data.to(device)
fake_img = netG(z)
######### Train generator #########
netG.zero_grad()
g_loss = criterionG(fake_img, real_img)
g_loss.backward()
optimizerG.step()
run_result['g_loss'] += g_loss.item() * batch_size
train_bar.set_description(
desc=f"[{epoch}/{num_epochs}] Loss_G: {run_result['g_loss'] / run_result['nsamples']:.4f}")
train_gloss = run_result['g_loss'] / run_result['nsamples']
train_gscore = run_result['g_score'] / run_result['nsamples']
valid_result = {'g_loss': 0,
'mse': 0, 'ssims': 0, 'psnr': 0, 'ssim': 0, 'nsamples': 0}
netG.eval()
batch_ssims = []
batch_mses = []
batch_psnrs = []
batch_maes = []
valid_bar = tqdm(valid_loader)
with torch.no_grad():
for val_lr, val_hr, inds in valid_bar:
batch_size = val_lr.size(0)
valid_result['nsamples'] += batch_size
lr = val_lr.to(device)
hr = val_hr.to(device)
sr = netG(lr)
sr_out = sr
hr_out = hr
g_loss = criterionG(sr, hr)
valid_result['g_loss'] += g_loss.item() * batch_size
batch_mse = ((sr - hr) ** 2).mean()
batch_mae = (abs(sr - hr)).mean()
valid_result['mse'] += batch_mse * batch_size
batch_ssim = ssim(sr, hr)
valid_result['ssims'] += batch_ssim * batch_size
valid_result['psnr'] = 10 * log10(1 / (valid_result['mse'] / valid_result['nsamples']))
valid_result['ssim'] = valid_result['ssims'] / valid_result['nsamples']
valid_bar.set_description(
desc=f"[Predicting in Test set] PSNR: {valid_result['psnr']:.4f} dB SSIM: {valid_result['ssim']:.4f}")
batch_ssims.append(valid_result['ssim'])
batch_psnrs.append(valid_result['psnr'])
batch_mses.append(batch_mse)
batch_maes.append(batch_mae)
ssim_scores.append((sum(batch_ssims) / len(batch_ssims)))
psnr_scores.append((sum(batch_psnrs) / len(batch_psnrs)))
mse_scores.append((sum(batch_mses) / len(batch_mses)))
mae_scores.append((sum(batch_maes) / len(batch_maes)))
valid_gloss = valid_result['g_loss'] / valid_result['nsamples']
now_ssim = valid_result['ssim'].item()
if now_ssim > best_ssim:
best_ssim = now_ssim
print(f'Now, Best ssim is {best_ssim:.6f}')
best_ckpt_file = f'{datestr}_bestg_{resos}_c{chunk}_s{stride}_b{bound}_{pool}_{name}.pytorch'
torch.save(netG.state_dict(), os.path.join(out_dir, best_ckpt_file))
final_ckpt_g = f'{datestr}_finalg_{resos}_c{chunk}_s{stride}_b{bound}_{pool}_{name}.pytorch'
######### Uncomment to track scores across epochs #########
# ssim_scores = ssim_scores.cpu()
# psnr_scores = psnr_scores.cpu()
# mse_scores = mse_scores.cpu()
# mae_scores = mae_scores.cpu()
# ssim_scores = np.array(ssim_scores)
# psnr_scores = np.array(psnr_scores)
# mse_scores = np.array(mse_scores)
# mae_scores = np.array(mae_scores)
#
# np.savetxt(f'valid_ssim_scores_{name}', X=ssim_scores, delimiter=',')
# np.savetxt(f'valid_psnr_scores_{name}', X=psnr_scores, delimiter=',')
# np.savetxt(f'valid_mse_scores_{name}', X=mse_scores, delimiter=',')
# np.savetxt(f'valid_mae_scores_{name}', X=mae_scores, delimiter=',')
torch.save(netG.state_dict(), os.path.join(out_dir, final_ckpt_g))