-
Notifications
You must be signed in to change notification settings - Fork 1
/
train.py
168 lines (122 loc) · 5.3 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
import os
import pprint
from collections import OrderedDict, defaultdict
import numpy as np
import torch
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.data import DataLoader
from batch_engine import valid_trainer, batch_trainer
from config import argument_parser
from dataset.AttrDataset import AttrDataset, get_transform
from loss.CE_loss import CEL_Sigmoid
from models.base_block import MSSC, BaseClassifier
from models.resnet import resnet50
from tools.function import get_model_log_path, get_pedestrian_metrics
from tools.utils import time_str, save_ckpt, ReDirectSTD, set_seed, return_attr_name_list
set_seed(605)
def main(args):
visenv_name = args.dataset
exp_dir = os.path.join('exp_result', args.dataset)
model_dir, log_dir = get_model_log_path(exp_dir, visenv_name)
stdout_file = os.path.join(log_dir, f'stdout_{time_str()}.txt')
save_model_path = os.path.join(model_dir, 'ckpt_max.pth')
if args.redirector:
print('redirector stdout')
ReDirectSTD(stdout_file, 'stdout', False)
pprint.pprint(OrderedDict(args.__dict__))
print('-' * 60)
print(f'use GPU{args.device} for training')
print(f'train set: {args.dataset} {args.train_split}, test set: {args.valid_split}')
train_tsfm, valid_tsfm = get_transform(args)
print(train_tsfm)
train_set = AttrDataset(args=args, split=args.train_split, transform=train_tsfm)
train_loader = DataLoader(
dataset=train_set,
batch_size=args.batchsize,
shuffle=True,
num_workers=4,
pin_memory=True,
drop_last=True
)
valid_set = AttrDataset(args=args, split=args.valid_split, transform=valid_tsfm)
valid_loader = DataLoader(
dataset=valid_set,
batch_size=args.batchsize,
shuffle=False,
num_workers=4,
pin_memory=True,
drop_last=True
)
print(f'{args.train_split} set: {len(train_loader.dataset)}, '
f'{args.valid_split} set: {len(valid_loader.dataset)}, '
f'attr_num : {train_set.attr_num}')
labels = train_set.label
sample_weight = labels.mean(0)
backbone = resnet50()
classifier = BaseClassifier(nattr=train_set.attr_num)
model = MSSC(backbone, classifier)
if torch.cuda.is_available():
model = torch.nn.DataParallel(model).cuda()
criterion = CEL_Sigmoid(sample_weight)
param_groups = [{'params': model.module.finetune_params(), 'lr': args.lr_ft},
{'params': model.module.fresh_params(), 'lr': args.lr_new}]
optimizer = torch.optim.SGD(param_groups, momentum=args.momentum, weight_decay=args.weight_decay, nesterov=False)
lr_scheduler = ReduceLROnPlateau(optimizer, factor=0.1, patience=4)
best_metric, epoch = trainer(epoch=args.train_epoch,
model=model,
train_loader=train_loader,
valid_loader=valid_loader,
criterion=criterion,
optimizer=optimizer,
lr_scheduler=lr_scheduler,
path=save_model_path,
dataset=args.dataset)
print(f'{visenv_name}, best_metrc : {best_metric} in epoch{epoch}')
def trainer(epoch, model, train_loader, valid_loader, criterion, optimizer, lr_scheduler,
path, dataset):
maximum = float(-np.inf)
best_epoch = 0
result_list = defaultdict()
for i in range(epoch):
train_loss, train_gt, train_probs = batch_trainer(
epoch=i,
model=model,
train_loader=train_loader,
criterion=criterion,
optimizer=optimizer,
)
valid_loss, valid_gt, valid_probs = valid_trainer(
epoch=i,
model=model,
valid_loader=valid_loader,
criterion=criterion,
)
lr_scheduler.step(metrics=valid_loss)
train_result = get_pedestrian_metrics(train_gt, train_probs)
valid_result = get_pedestrian_metrics(valid_gt, valid_probs)
print(f'Evaluation on test set, \n',
'ma: {:.4f}, pos_recall: {:.4f} , neg_recall: {:.4f} \n'.format(
valid_result.ma, np.mean(valid_result.label_pos_recall), np.mean(valid_result.label_neg_recall)),
'Acc: {:.4f}, Prec: {:.4f}, Rec: {:.4f}, F1: {:.4f}'.format(
valid_result.instance_acc, valid_result.instance_prec, valid_result.instance_recall,
valid_result.instance_f1))
# print label metrics ma
attr_name_list = return_attr_name_list(dataset)
for attr_name, _ma in zip(attr_name_list, valid_result.label_ma):
print(f'{attr_name}: {_ma}')
print(f'{time_str()}')
print('-' * 60)
cur_metric = valid_result.ma
if cur_metric > maximum:
maximum = cur_metric
best_epoch = i
save_ckpt(model, path, i, maximum)
result_list[i] = [train_result, valid_result]
torch.save(result_list, os.path.join(os.path.dirname(path), 'metric_log.pkl'))
return maximum, best_epoch
if __name__ == '__main__':
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
parser = argument_parser()
args = parser.parse_args()
main(args)