-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmodelTrain.py
177 lines (168 loc) · 6.76 KB
/
modelTrain.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
import argparse
import re
import os
import glob
import datetime
import time
import numpy as np
import torch
import torch.nn as nn
import h5py
from scipy import io
from utils import *
from models import *
import torch.optim as optim
from torch.optim.lr_scheduler import MultiStepLR
# check if cuda is available
cuda_available = torch.cuda.is_available()
print('cuda_available:', cuda_available)
if cuda_available:
device = torch.device('cuda')
else:
device = torch.device('cpu')
# Params
parser = argparse.ArgumentParser(description='PyTorch Complex DnCNN')
parser.add_argument(
'--model',
default='cDnCNN',
type=str,
help='choose a type of model')
parser.add_argument('--batch_size', default=2, type=int, help='batch size')
parser.add_argument('--train_data',
default='channel',
type=str,
help='path of train data')
parser.add_argument('--snr', default=5, type=int, help='noise level')
parser.add_argument('--channel_clusters', default=6,
type=int, help='clusters of channel')
parser.add_argument('--paths_per_cluster', default=8,
type=int, help='paths per cluster')
parser.add_argument('--angle_spread', default=7.5,
type=int, help='angle spread')
parser.add_argument('--epoch',
default=150,
type=int,
help='number of train epoches')
parser.add_argument('--lr',
default=3e-4,
type=float,
help='initial learning rate for Adam')
args = parser.parse_args()
clusters = args.channel_clusters
paths = args.paths_per_cluster
AS = args.angle_spread
batch_size = args.batch_size
print(batch_size)
train_data = args.train_data
n_epoch = args.epoch
snr = args.snr
PRINT_FREQ = 20
# snr = 10
save_dir = os.path.join('./models', args.model + '_' + 'snr' + str(snr))
if not os.path.exists(save_dir):
os.makedirs(save_dir)
if __name__ == '__main__':
print('>>> Building Model')
model = ComplexDnCNN().to(device)
# uncomment to use dataparallel (unstable)
# device_ids = [0, 1]
# model = nn.DataParallel(model, device_ids=device_ids).cuda()
initial_epoch = findLastCheckpoint(save_dir=save_dir)
if initial_epoch > 0:
print('resuming by loading epoch %03d' % initial_epoch)
model.load_state_dict(
torch.load(os.path.join(save_dir,
'model_%03d.pth' % initial_epoch)))
print(">>> Building Model Finished")
# model.train() # Enable BN and Dropout
# criterion = nn.MSELoss(reduction='sum').cuda()
criterion = NMSELoss()
optimizer = optim.Adam(model.parameters(), lr=args.lr)
scheduler = MultiStepLR(optimizer, milestones=[20, 40, 60, 80, 100, 120],
gamma=0.7) # learning rates
print("Loading Data")
# should be generated by yourself
train_est = train_data + '/' + \
str(snr)+'dB/trainingChannel'+str(snr) + \
'_C' + str(clusters) + 'P' + str(paths) + '_AS' + str(AS) + '.mat'
train_true = train_data + '/' + \
str(snr)+'dB/trueTrainingChannel'+str(snr) + \
'_C' + str(clusters) + 'P' + str(paths) + '_AS' + str(AS) + '.mat'
train_est_mat = h5py.File(train_est, mode='r')
# print(train_est_mat.keys())
x_train = train_est_mat['trainingChannel']
x_train = np.transpose(x_train, [3, 2, 1, 0])
print('>>> training Set setup complete')
# ground truth
train_true_mat = h5py.File(train_true, mode='r')
# y_train = train_true_mat['trueTrainingChannel']
y_train = train_true_mat['trueTrainingChannel']
y_train = np.transpose(y_train, [3, 2, 1, 0])
print('>>> groundTruth Set setup complete')
data_num = x_train.shape[0]
split = int(data_num * 0.9)
h_hat = torch.from_numpy(x_train).float().reshape(
[x_train.shape[0], x_train.shape[1], 1, x_train.shape[2], x_train.shape[3]])
# x_train = x_train[0:2000, :]
h_hat_train = h_hat[0:split, :, :, :, :]
h_hat_test = h_hat[split:, :, :, :, :]
print(h_hat_train.shape)
h_true = torch.from_numpy(y_train).float().reshape(
[y_train.shape[0], y_train.shape[1], 1, y_train.shape[2], y_train.shape[3]])
h_true_train = h_true[0:split, :, :, :, :]
h_true_test = h_true[split:, :, :, :, :]
print(h_true_train.shape)
train_dataset = MyDenoisingDataset(h_true_train, h_hat_train)
test_dataset = MyDenoisingDataset(h_true_test, h_hat_test)
trainLoader = DataLoader(dataset=train_dataset,
num_workers=0,
drop_last=True,
batch_size=batch_size,
shuffle=True)
testloader = DataLoader(dataset=test_dataset,
num_workers=0,
drop_last=False,
batch_size=batch_size,
shuffle=False)
best_loss = 100
for epoch in range(initial_epoch, n_epoch):
epoch_loss = 0
start_time = time.time()
model.train()
for n_count, batch_yx in enumerate(trainLoader):
if cuda_available:
batch_x, batch_y = batch_yx[1].cuda(), batch_yx[0].cuda()
else:
batch_x, batch_y = batch_yx[1], batch_yx[0]
out = model(batch_y)
loss = criterion(out, batch_x)
optimizer.zero_grad()
loss.backward()
optimizer.step()
scheduler.step() # step to the learning rate in this epoch
epoch_loss += loss.item()
del batch_x # free some memory
del batch_y
del batch_yx
del out
if n_count % PRINT_FREQ == 0:
print('[%4d] - [%4d]/[%4d] loss = %2.4f\ttime: %2.4f' %
(epoch + 1, n_count, len(trainLoader), loss.item(), time.time() - start_time))
elapsed_time = time.time() - start_time
log('epoch = %4d , loss = %4.4f , time = %4.2f s' %
(epoch + 1, epoch_loss / n_count, elapsed_time))
model.eval()
test_loss = 0
with torch.no_grad():
for n_count, batch_yx in enumerate(testloader):
if cuda_available:
batch_x, batch_y = batch_yx[1].cuda(), batch_yx[0].cuda()
loss = criterion(model(batch_y), batch_x)
test_loss += loss.item()
print('test loss = %4.4f' % (test_loss/len(testloader)))
if test_loss/len(testloader) <= best_loss:
torch.save(model.state_dict(),
os.path.join(save_dir, 'model_%03d.pth' % (epoch + 1)))
best_loss = test_loss/len(testloader)
print('save model\n')
# torch.save(model, os.path.join(save_dir, 'model_%03d.pth' % (epoch+1)))