-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathtrain_net.py
405 lines (316 loc) · 14.7 KB
/
train_net.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import torch
import torch.optim as optim
import time
import random
import os
import sys
from config import *
from volleyball import *
from collective import *
from dataset import *
from gcn_model import *
from base_model import *
from utils import *
def set_bn_eval(m):
classname = m.__class__.__name__
if classname.find('BatchNorm') != -1:
m.eval()
def adjust_lr(optimizer, new_lr):
print('change learning rate:',new_lr)
for param_group in optimizer.param_groups:
param_group['lr'] = new_lr
def train_net(cfg):
"""
training gcn net
"""
os.environ['CUDA_VISIBLE_DEVICES']=cfg.device_list
# Show config parameters
cfg.init_config()
show_config(cfg)
# Reading dataset
training_set,validation_set=return_dataset(cfg)
params = {
'batch_size': cfg.batch_size,
'shuffle': True,
'num_workers': 4
}
training_loader=data.DataLoader(training_set,**params)
params['batch_size']=cfg.test_batch_size
validation_loader=data.DataLoader(validation_set,**params)
# Set random seed
np.random.seed(cfg.train_random_seed)
torch.manual_seed(cfg.train_random_seed)
random.seed(cfg.train_random_seed)
# Set data position
if cfg.use_gpu and torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
# Build model and optimizer
basenet_list={'volleyball':Basenet_volleyball, 'collective':Basenet_collective}
gcnnet_list={'volleyball':GCNnet_volleyball, 'collective':GCNnet_collective}
if cfg.training_stage==1:
Basenet=basenet_list[cfg.dataset_name]
model=Basenet(cfg)
elif cfg.training_stage==2:
GCNnet=gcnnet_list[cfg.dataset_name]
model=GCNnet(cfg)
# Load backbone
model.loadmodel(cfg.stage1_model_path)
else:
assert(False)
if cfg.use_multi_gpu:
model=nn.DataParallel(model)
model=model.to(device=device)
model.train()
model.apply(set_bn_eval)
optimizer=optim.Adam(filter(lambda p: p.requires_grad, model.parameters()),lr=cfg.train_learning_rate,weight_decay=cfg.weight_decay)
train_list={'volleyball':train_volleyball, 'collective':train_collective}
test_list={'volleyball':test_volleyball, 'collective':test_collective}
train=train_list[cfg.dataset_name]
test=test_list[cfg.dataset_name]
if cfg.test_before_train:
test_info=test(validation_loader, model, device, 0, cfg)
print(test_info)
# Training iteration
best_result={'epoch':0, 'activities_acc':0}
start_epoch=1
for epoch in range(start_epoch, start_epoch+cfg.max_epoch):
if epoch in cfg.lr_plan:
adjust_lr(optimizer, cfg.lr_plan[epoch])
# One epoch of forward and backward
train_info=train(training_loader, model, device, optimizer, epoch, cfg)
show_epoch_info('Train', cfg.log_path, train_info)
# Test
if epoch % cfg.test_interval_epoch == 0:
test_info=test(validation_loader, model, device, epoch, cfg)
show_epoch_info('Test', cfg.log_path, test_info)
if test_info['activities_acc']>best_result['activities_acc']:
best_result=test_info
print_log(cfg.log_path,
'Best group activity accuracy: %.2f%% at epoch #%d.'%(best_result['activities_acc'], best_result['epoch']))
# Save model
if cfg.training_stage==2:
state = {
'epoch': epoch,
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict(),
}
filepath=cfg.result_path+'/stage%d_epoch%d_%.2f%%.pth'%(cfg.training_stage,epoch,test_info['activities_acc'])
torch.save(state, filepath)
print('model saved to:',filepath)
elif cfg.training_stage==1:
for m in model.modules():
if isinstance(m, Basenet):
filepath=cfg.result_path+'/stage%d_epoch%d_%.2f%%.pth'%(cfg.training_stage,epoch,test_info['activities_acc'])
m.savemodel(filepath)
# print('model saved to:',filepath)
else:
assert False
def train_volleyball(data_loader, model, device, optimizer, epoch, cfg):
actions_meter=AverageMeter()
activities_meter=AverageMeter()
loss_meter=AverageMeter()
epoch_timer=Timer()
for batch_data in data_loader:
model.train()
model.apply(set_bn_eval)
# prepare batch data
batch_data=[b.to(device=device) for b in batch_data]
batch_size=batch_data[0].shape[0]
num_frames=batch_data[0].shape[1]
actions_in=batch_data[2].reshape((batch_size,num_frames,cfg.num_boxes))
activities_in=batch_data[3].reshape((batch_size,num_frames))
actions_in=actions_in[:,0,:].reshape((batch_size*cfg.num_boxes,))
activities_in=activities_in[:,0].reshape((batch_size,))
# forward
actions_scores,activities_scores=model((batch_data[0],batch_data[1]))
# Predict actions
actions_weights=torch.tensor(cfg.actions_weights).to(device=device)
actions_loss=F.cross_entropy(actions_scores,actions_in,weight=actions_weights)
actions_labels=torch.argmax(actions_scores,dim=1)
actions_correct=torch.sum(torch.eq(actions_labels.int(),actions_in.int()).float())
# Predict activities
activities_loss=F.cross_entropy(activities_scores,activities_in)
activities_labels=torch.argmax(activities_scores,dim=1)
activities_correct=torch.sum(torch.eq(activities_labels.int(),activities_in.int()).float())
# Get accuracy
actions_accuracy=actions_correct.item()/actions_scores.shape[0]
activities_accuracy=activities_correct.item()/activities_scores.shape[0]
actions_meter.update(actions_accuracy, actions_scores.shape[0])
activities_meter.update(activities_accuracy, activities_scores.shape[0])
# Total loss
total_loss=activities_loss+cfg.actions_loss_weight*actions_loss
loss_meter.update(total_loss.item(), batch_size)
# Optim
optimizer.zero_grad()
total_loss.backward()
optimizer.step()
train_info={
'time':epoch_timer.timeit(),
'epoch':epoch,
'loss':loss_meter.avg,
'activities_acc':activities_meter.avg*100,
'actions_acc':actions_meter.avg*100
}
return train_info
def test_volleyball(data_loader, model, device, epoch, cfg):
model.eval()
actions_meter=AverageMeter()
activities_meter=AverageMeter()
loss_meter=AverageMeter()
epoch_timer=Timer()
with torch.no_grad():
for batch_data_test in data_loader:
# prepare batch data
batch_data_test=[b.to(device=device) for b in batch_data_test]
batch_size=batch_data_test[0].shape[0]
num_frames=batch_data_test[0].shape[1]
actions_in=batch_data_test[2].reshape((batch_size,num_frames,cfg.num_boxes))
activities_in=batch_data_test[3].reshape((batch_size,num_frames))
# forward
actions_scores,activities_scores=model((batch_data_test[0],batch_data_test[1]))
# Predict actions
actions_in=actions_in[:,0,:].reshape((batch_size*cfg.num_boxes,))
activities_in=activities_in[:,0].reshape((batch_size,))
actions_weights=torch.tensor(cfg.actions_weights).to(device=device)
actions_loss=F.cross_entropy(actions_scores,actions_in,weight=actions_weights)
actions_labels=torch.argmax(actions_scores,dim=1)
# Predict activities
activities_loss=F.cross_entropy(activities_scores,activities_in)
activities_labels=torch.argmax(activities_scores,dim=1)
actions_correct=torch.sum(torch.eq(actions_labels.int(),actions_in.int()).float())
activities_correct=torch.sum(torch.eq(activities_labels.int(),activities_in.int()).float())
# Get accuracy
actions_accuracy=actions_correct.item()/actions_scores.shape[0]
activities_accuracy=activities_correct.item()/activities_scores.shape[0]
actions_meter.update(actions_accuracy, actions_scores.shape[0])
activities_meter.update(activities_accuracy, activities_scores.shape[0])
# Total loss
total_loss=activities_loss+cfg.actions_loss_weight*actions_loss
loss_meter.update(total_loss.item(), batch_size)
test_info={
'time':epoch_timer.timeit(),
'epoch':epoch,
'loss':loss_meter.avg,
'activities_acc':activities_meter.avg*100,
'actions_acc':actions_meter.avg*100
}
return test_info
def train_collective(data_loader, model, device, optimizer, epoch, cfg):
actions_meter=AverageMeter()
activities_meter=AverageMeter()
loss_meter=AverageMeter()
epoch_timer=Timer()
for batch_data in data_loader:
model.train()
model.apply(set_bn_eval)
# prepare batch data
batch_data=[b.to(device=device) for b in batch_data]
batch_size=batch_data[0].shape[0]
num_frames=batch_data[0].shape[1]
# forward
actions_scores,activities_scores=model((batch_data[0],batch_data[1],batch_data[4]))
actions_in=batch_data[2].reshape((batch_size,num_frames,cfg.num_boxes))
activities_in=batch_data[3].reshape((batch_size,num_frames))
bboxes_num=batch_data[4].reshape(batch_size,num_frames)
actions_in_nopad=[]
if cfg.training_stage==1:
actions_in=actions_in.reshape((batch_size*num_frames,cfg.num_boxes,))
bboxes_num=bboxes_num.reshape(batch_size*num_frames,)
for bt in range(batch_size*num_frames):
N=bboxes_num[bt]
actions_in_nopad.append(actions_in[bt,:N])
else:
for b in range(batch_size):
N=bboxes_num[b][0]
actions_in_nopad.append(actions_in[b][0][:N])
actions_in=torch.cat(actions_in_nopad,dim=0).reshape(-1,) #ALL_N,
if cfg.training_stage==1:
activities_in=activities_in.reshape(-1,)
else:
activities_in=activities_in[:,0].reshape(batch_size,)
# Predict actions
actions_loss=F.cross_entropy(actions_scores,actions_in,weight=None)
actions_labels=torch.argmax(actions_scores,dim=1) #B*T*N,
actions_correct=torch.sum(torch.eq(actions_labels.int(),actions_in.int()).float())
# Predict activities
activities_loss=F.cross_entropy(activities_scores,activities_in)
activities_labels=torch.argmax(activities_scores,dim=1) #B*T,
activities_correct=torch.sum(torch.eq(activities_labels.int(),activities_in.int()).float())
# Get accuracy
actions_accuracy=actions_correct.item()/actions_scores.shape[0]
activities_accuracy=activities_correct.item()/activities_scores.shape[0]
actions_meter.update(actions_accuracy, actions_scores.shape[0])
activities_meter.update(activities_accuracy, activities_scores.shape[0])
# Total loss
total_loss=activities_loss+cfg.actions_loss_weight*actions_loss
loss_meter.update(total_loss.item(), batch_size)
# Optim
optimizer.zero_grad()
total_loss.backward()
optimizer.step()
train_info={
'time':epoch_timer.timeit(),
'epoch':epoch,
'loss':loss_meter.avg,
'activities_acc':activities_meter.avg*100,
'actions_acc':actions_meter.avg*100
}
return train_info
def test_collective(data_loader, model, device, epoch, cfg):
model.eval()
actions_meter=AverageMeter()
activities_meter=AverageMeter()
loss_meter=AverageMeter()
epoch_timer=Timer()
with torch.no_grad():
for batch_data in data_loader:
# prepare batch data
batch_data=[b.to(device=device) for b in batch_data]
batch_size=batch_data[0].shape[0]
num_frames=batch_data[0].shape[1]
actions_in=batch_data[2].reshape((batch_size,num_frames,cfg.num_boxes))
activities_in=batch_data[3].reshape((batch_size,num_frames))
bboxes_num=batch_data[4].reshape(batch_size,num_frames)
# forward
actions_scores,activities_scores=model((batch_data[0],batch_data[1],batch_data[4]))
actions_in_nopad=[]
if cfg.training_stage==1:
actions_in=actions_in.reshape((batch_size*num_frames,cfg.num_boxes,))
bboxes_num=bboxes_num.reshape(batch_size*num_frames,)
for bt in range(batch_size*num_frames):
N=bboxes_num[bt]
actions_in_nopad.append(actions_in[bt,:N])
else:
for b in range(batch_size):
N=bboxes_num[b][0]
actions_in_nopad.append(actions_in[b][0][:N])
actions_in=torch.cat(actions_in_nopad,dim=0).reshape(-1,) #ALL_N,
if cfg.training_stage==1:
activities_in=activities_in.reshape(-1,)
else:
activities_in=activities_in[:,0].reshape(batch_size,)
actions_loss=F.cross_entropy(actions_scores,actions_in)
actions_labels=torch.argmax(actions_scores,dim=1) #ALL_N,
actions_correct=torch.sum(torch.eq(actions_labels.int(),actions_in.int()).float())
# Predict activities
activities_loss=F.cross_entropy(activities_scores,activities_in)
activities_labels=torch.argmax(activities_scores,dim=1) #B,
activities_correct=torch.sum(torch.eq(activities_labels.int(),activities_in.int()).float())
# Get accuracy
actions_accuracy=actions_correct.item()/actions_scores.shape[0]
activities_accuracy=activities_correct.item()/activities_scores.shape[0]
actions_meter.update(actions_accuracy, actions_scores.shape[0])
activities_meter.update(activities_accuracy, activities_scores.shape[0])
# Total loss
total_loss=activities_loss+cfg.actions_loss_weight*actions_loss
loss_meter.update(total_loss.item(), batch_size)
test_info={
'time':epoch_timer.timeit(),
'epoch':epoch,
'loss':loss_meter.avg,
'activities_acc':activities_meter.avg*100,
'actions_acc':actions_meter.avg*100
}
return test_info