-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_cls.py
214 lines (180 loc) · 9.24 KB
/
train_cls.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
import argparse
import os
import numpy as np
import torch
import torch.cuda
import torch.nn as nn
import torch.optim as optim
from network import KeNet
from tensorboardX import SummaryWriter
from torch.utils.data import DataLoader
from tqdm import tqdm
from data_pre_process.data_process import DRDataset
# python train_cls.py -b resnet-wam -g 0 -bc 8 -e 150 -d _4
parser = argparse.ArgumentParser(description='train_cls')
parser.add_argument('-b', '--basic_net', type=str, required=True, help='basic_net')
parser.add_argument('-g', '--gpu', type=int, required=True, help='gpu id')
parser.add_argument('-pre', '--pretrain', type=str, required=False, default='False', help='pretrain')
parser.add_argument('-w', '--wam', type=str, required=False, default=False, help="whether to use windows attention")
parser.add_argument('-n', '--win_num', type=int, required=False, default=3, help="The windows number")
parser.add_argument('-lr', '--LR', type=int, required=False, default=1, help="Learning rate")
parser.add_argument('-bc', '--batch', type=int, required=False, default=4, help="batch_size")
parser.add_argument('-e', '--epoc', type=int, required=False, default=800, help="epoc_num")
parser.add_argument('-l_num', '--layer_num', type=int, required=False, default=1, help="the num of resnet wam layer")
parser.add_argument('-ld', '--load_model', type=int, required=False, default='-1', help="the number of model")
parser.add_argument('-d', '--dataset', type=str, required=False, default='', help="dataset describe")
parser.add_argument('-pth', '--pre_path', type=str, required=False, default='', help="pretrain model path")
args = parser.parse_args()
EPOCH = args.epoc
num_epochs_decay = 400
img_size = 1024
num_class = 2
dataset = 'DKD'
num_thread = 8
device_ids = [2, 3]
basic_model = args.basic_net # inception densenet resnet
pretrain = True if args.pretrain == 'True' else False
from config.train_config import *
if args.wam == 'True' or args.wam == 'true':
windows_attention = True
else:
windows_attention = False
print(windows_attention)
net = KeNet(classes_num=num_class, basic_model=basic_model, windows_attention=windows_attention, pretrain=pretrain
, windows_num=args.win_num, initial_method="Uniform", k=0.8, layer_num=args.layer_num).cuda(device_ids[0])
# net = torch.compile(net)
net = torch.nn.DataParallel(net, device_ids)
if pretrain:
pre_model_dir = args.pre_path
save_model = torch.load(pre_model_dir)
model_dict = net.state_dict()
state_dict = {k: v for k, v in save_model.items() if k in model_dict.keys()}
model_dict.update(state_dict)
net.load_state_dict(model_dict)
model_name = basic_model + '_win_num' + str(args.win_num) + '_lr' + str(args.LR) + '_ep' + str(
args.epoc) + 'bc_' + str(args.batch) + 'lnum_' + str(args.layer_num) + 'ims_' + str(img_size)
if args.wam == "True" or args.wam == "true":
model_name = 'begin_wam_' + model_name
if not pretrain:
model_name = model_name + '_Nopretrain'
epoc_begin = 0
if args.load_model > 0:
net.load_state_dict(
torch.load('%s/net_%03d.pth' % ('model/model_' + model_name + '_' + dataset, args.load_model)))
epoc_begin = args.load_model
train_BATCH_SIZE = args.batch
test_BATCH_SIZE = 1
def main():
criterion = nn.CrossEntropyLoss(
weight=torch.from_numpy(np.array([weight[0], weight[1]])).float().cuda(device_ids[0]))
optimizer = optim.Adam(net.parameters(), lr=LR * args.LR, weight_decay=weight_decay)
scheduler = optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=5, T_mult=2)
dr_dataset_train = DRDataset(root_img='data/' + 'cls' + args.dataset + '/',
phase='Train', img_size=img_size, num_class=num_class, transform=True, if_after=True)
dr_dataset_test = DRDataset(root_img='data/' + 'cls' + args.dataset + '/',
phase='Test', img_size=img_size, num_class=num_class, transform=False, if_after=False)
loader_train = DataLoader(dr_dataset_train, batch_size=train_BATCH_SIZE, num_workers=num_thread, shuffle=True)
loader_test = DataLoader(dr_dataset_test, batch_size=test_BATCH_SIZE, num_workers=num_thread, shuffle=False)
writer = SummaryWriter(logdir='runs/runs_' + model_name + '_' + dataset)
count_all = 0
new_lr = LR * args.LR
with open('acc/acc_' + model_name + '_' + dataset + '.txt', "w+") as f:
for epoch in range(epoc_begin, EPOCH):
# if (epoch + 1) > (EPOCH - num_epochs_decay):
# new_lr -= (LR / float(num_epochs_decay))
# for param_group in optimizer.param_groups:
# param_group['lr'] = new_lr
# print('Decay learning rate to lr: {}.'.format(new_lr))
running_results = {'acc': 0, 'acc_loss': 0}
print('Decay learning rate to lr: {}.'.format(optimizer.param_groups[0]['lr']))
train_bar = tqdm(loader_train)
count = 0
"""--------------------------------------Train---------------------------------------"""
for packs in train_bar:
count += 1
count_all += 1
net.train()
inputs, labels = packs[0].cuda(device_ids[0]), packs[1].cuda(device_ids[0])
optimizer.zero_grad()
outputs = net(inputs)
loss_ce = criterion(outputs, labels) # vanilla softmax loss
_, predicted = torch.max(outputs.data, 1)
loss = loss_ce
loss.backward()
optimizer.step()
total = labels.size(0)
correct = predicted.eq(labels.data).cpu().sum()
running_results['acc'] += 100. * correct / total
running_results['acc_loss'] += loss.item()
train_bar.set_description(
desc=model_name + ' [%d/%d] acc_loss: %.4f' % (
epoch, EPOCH,
running_results['acc_loss'] / count
))
"""------------------tensorboard test--------------"""
if count % 4 == 0:
writer.add_scalar('scalar/train_loss_per_iter', loss.item(), count_all)
writer.add_scalar('scalar/acc_batchwise', (100. * correct / total), count_all)
"""------------------Test--------------"""
if epoch % 4 == 0:
test_bar = tqdm(loader_test)
print("Waiting Test!")
with torch.no_grad():
correct_all = 0
total_all = 0
tp = 0
tn = 0
fp = 0
fn = 0
for packs in test_bar:
net.eval()
images, labels = packs[0].cuda(device_ids[0]), packs[1].cuda(device_ids[0])
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total_all += labels.size(0)
correct_all += (predicted == labels).sum()
labels = labels.cpu().numpy()
predicted = predicted.cpu().numpy()
for i_test in range(test_BATCH_SIZE):
if labels[i_test] == 1 and predicted[i_test] == 1:
tp += 1
if labels[i_test] == 1 and predicted[i_test] == 0:
fn += 1
if labels[i_test] == 0 and predicted[i_test] == 1:
fp += 1
if labels[i_test] == 0 and predicted[i_test] == 0:
tn += 1
Acc = (tp + tn) / (tp + tn + fp + fn)
Sen = (tp) / (tp + fn)
Spec = (tn) / (tn + fp)
print('Testset Acc=:%.1f%% | Sen=:%.1f%% | Spec=:%.1f%% ' % (Acc * 100, Sen * 100, Spec * 100))
torch.save(net.state_dict(),
'%s/net_%03d.pth' % ('model/model_' + model_name + '_' + dataset, epoch + 1))
f.write("EPOCH=%03d | Acc=:%.1f%% | Sen=:%.1f%% | Spec=:%.1f%% "
% (epoch + 1, Acc * 100, Sen * 100, Spec * 100))
f.write('\n')
f.flush()
writer.add_scalar('scalar/test_Acc', Acc, epoch)
writer.add_scalar('scalar/test_Sen', Sen, epoch)
writer.add_scalar('scalar/test_Spec', Spec, epoch)
scheduler.step()
writer.close()
def remove_all_file(path):
if os.path.isdir(path):
for i in os.listdir(path):
path_file = os.path.join(path, i)
os.remove(path_file)
if __name__ == "__main__":
init_seed = 1115
np.random.seed(init_seed)
torch.manual_seed(init_seed)
torch.cuda.manual_seed_all(init_seed)
if not os.path.isdir('model/model_' + model_name + '_' + dataset):
os.makedirs('model/model_' + model_name + '_' + dataset)
else:
if args.load_model < 0:
remove_all_file('model/model_' + model_name + '_' + dataset)
if os.path.isdir('runs/runs_' + model_name + '_' + dataset):
if args.load_model < 0:
remove_all_file('runs/runs_' + model_name + '_' + dataset)
main()