-
Notifications
You must be signed in to change notification settings - Fork 1
/
train_graph_time.py
212 lines (165 loc) · 8.31 KB
/
train_graph_time.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
from tqdm import tqdm
from utils.utils1 import *
import data.common.eval_cal as eval_cal
import torch
def step(split, opt, actions, dataLoader, model, criterion, optimizer=None):
# Initialize some definitions
num_data_all = 0
loss_all_sum = {'loss_gt':AccumLoss(), 'loss_diff':AccumLoss(), 'loss_sum':AccumLoss()}
mean_error = {'xyz': 0.0, 'post': 0.0}
error_sum = AccumLoss()
if opt.dataset=='h36m' and (opt.keypoints=='gt' or opt.keypoints=='hrn'):
limb_center = [2, 5, 11, 14]
limb_terminal = [3, 6, 12, 15]
action_error_sum = define_error_list(actions)
action_error_sum_post_out = define_error_list(actions)
joints_left =[4, 5, 6, 10, 11, 12]
joints_right = [1, 2, 3, 13, 14, 15]
elif opt.dataset == 'h36m':
limb_center = [2, 5, 11, 14] if opt.keypoints.startswith('sh') else [2, 5, 12, 15]
limb_terminal = [3, 6, 12, 15] if opt.keypoints.startswith('sh') else [3,6,13,16]
action_error_sum = define_error_list(actions)
action_error_sum_post_out = define_error_list(actions)
joints_left =[4, 5, 6, 10, 11, 12] if opt.keypoints.startswith('sh') else [4,5,6,11,12,13]
joints_right = [1, 2, 3, 13, 14, 15] if opt.keypoints.startswith('sh') else [1, 2, 3, 14, 15, 16]
criterion_mse = criterion['MSE']
# Add sparsity constaint
criterion_L1 = criterion['L1']
gsnet_gcn = model['gsnet_gcn']
model_post_refine = model['post_refine']
if split == 'train':
gsnet_gcn.train()
if opt.out_all:
out_all_frame = True
else:
out_all_frame = False
else:
gsnet_gcn.eval()
out_all_frame = False
torch.cuda.synchronize()
# Load data
for i, data in enumerate(tqdm(dataLoader, 0)):
if split == 'train':
if optimizer is None:
print("error! No Optimizer")
else:
optimizer_all = optimizer
# Load and process data
batch_cam, gt_3D, input_2D, action, subject, scale , bb_box, cam_ind = data
[input_2D, gt_3D, batch_cam, scale, bb_box] = get_varialbe (split,[input_2D, gt_3D, batch_cam, scale, bb_box])
N = input_2D.size(0)
num_data_all += N
out_target = gt_3D.clone().view(N, -1, opt.n_joints, opt.out_channels)
out_target[:, :, 0] = 0
gt_3D = gt_3D.view(N, -1, opt.n_joints, opt.out_channels).type(torch.cuda.FloatTensor)
if out_target.size(1) > 1:
out_target_single = out_target[:,opt.pad].unsqueeze(1)
gt_3D_single = gt_3D[:, opt.pad].unsqueeze(1)
else:
out_target_single = out_target
gt_3D_single = gt_3D
# Start forward process
if opt.test_augmentation and split =='test':
input_2D, output_3D = input_augmentation(input_2D, gsnet_gcn, joints_left, joints_right)
else:
input_2D = input_2D.view(N, -1, opt.n_joints,opt.in_channels, 1).permute(0, 3, 1, 2, 4).type(torch.cuda.FloatTensor) # N, C, T, J, M
output_3D = gsnet_gcn(input_2D)
output_3D = output_3D.permute(0, 2, 3, 4, 1).contiguous().view(N, -1, opt.n_joints, opt.out_channels)
output_3D = output_3D * scale.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).repeat(1, output_3D.size(1),opt.n_joints, opt.out_channels)
if output_3D.size(1) > 1:
output_3D_single = output_3D[:, opt.pad].unsqueeze(1)
else:
output_3D_single = output_3D
if split == 'train':
pred_out = output_3D # N, T, V, 3
elif split == 'test':
pred_out = output_3D_single
# From uvd get xyz
input_2D = input_2D.permute(0, 2, 3, 1, 4).view(N, -1, opt.n_joints ,2)
if opt.crop_uv:
pred_uv = back_to_ori_uv(input_2D, bb_box)
else:
pred_uv = input_2D
uvd = torch.cat((pred_uv[:, opt.pad, :, :].unsqueeze(1), output_3D_single[:, :, :, 2].unsqueeze(-1)), -1)
xyz = get_uvd2xyz(uvd, gt_3D_single, batch_cam)
xyz[:, :, 0, :] = 0
if opt.post_refine:
post_out = model_post_refine(output_3D_single, xyz)
loss_sym = eval_cal.sym_penalty(opt.dataset, opt.keypoints, post_out)
loss_post_refine = eval_cal.mpjpe(post_out, out_target_single) + 0.01*loss_sym
else:
loss_post_refine = 0
# Calculate loss
# Modified for add sparsity constaint
loss_gt = (1-opt.norm) * criterion_mse(pred_out, out_target) + opt.norm*criterion_L1(pred_out, out_target)
if opt.sym_penalty:
loss_gt += 0.01 * eval_cal.sym_penalty(opt.dataset, opt.keypoints, pred_out)
if opt.pad == 0 or split == 'test':
loss_diff = torch.zeros(1).cuda()
else:
weight_diff = 4 * torch.ones(output_3D[:, :-1, :].size()).cuda()
weight_diff[:, :, limb_center] = 2.5
weight_diff[:, :, limb_terminal] = 1
diff = (output_3D[:,1:] - output_3D[:,:-1]) * weight_diff
loss_diff = criterion_mse(diff, Variable(torch.zeros(diff.size()), requires_grad=False).cuda())
loss = loss_gt + opt.co_diff * loss_diff + loss_post_refine
loss_all_sum['loss_gt'].update(loss_gt.detach().cpu().numpy() * N, N)
loss_all_sum['loss_diff'].update(loss_diff.detach().cpu().numpy() * N, N)
loss_all_sum['loss_sum'].update(loss.detach().cpu().numpy() * N, N)
# Train backpropogation
if split == 'train':
optimizer_all.zero_grad()
loss.backward()
optimizer_all.step()
#pred_out[:,:,0,:] = 0
joint_error = eval_cal.mpjpe(pred_out,out_target).item()
error_sum.update(joint_error*N, N)
elif split == 'test':
#pred_out[:, :, 0, :] = 0
pred_out[:, :, :, :] -= pred_out[:, :, :1, :]
action_error_sum = eval_cal.test_calculation(pred_out, out_target, action, action_error_sum,
opt.dataset, show_protocol2=opt.show_protocol2)
if opt.post_refine:
#post_out[:, :, 0, :] = 0
post_out[:, :, :, :] -= post_out[:, :, :1, :]
action_error_sum_post_out = eval_cal.test_calculation(post_out, out_target, action, action_error_sum_post_out, opt.dataset,
show_protocol2=opt.show_protocol2)
if split == 'train':
mean_error['xyz'] = error_sum.avg
print('Loss gt each frame of 1 sample: %f mm' % (loss_all_sum['loss_gt'].avg))
print('Loss diff of 1 sample: %f' % (loss_all_sum['loss_diff'].avg))
print('Loss of 1 sample: %f' % (loss_all_sum['loss_sum'].avg))
print('Mean joint error: %f' % (mean_error['xyz']*1000))
elif split == 'test':
if not opt.post_refine:
mean_error_all = print_error(opt.dataset, action_error_sum, opt.show_protocol2)
mean_error['xyz'] = mean_error_all
elif opt.post_refine:
print('-----Post out-----')
mean_error_all = print_error(opt.dataset, action_error_sum_post_out, opt.show_protocol2)
mean_error['post'] = mean_error_all
return mean_error
def train(opt, actions, train_loader,model, criterion, optimizer):
return step('train', opt,actions, train_loader, model, criterion, optimizer)
def val( opt, actions,val_loader, model, criterion):
return step('test', opt,actions, val_loader, model, criterion)
def input_augmentation(input_2D, gsnet_gcn, joints_left, joints_right):
"""
For calculating augmentation results
:param input_2D:
:param gsnet_gcn:
:param joints_left: joint index of left part
:param joints_right: joint index of right part
:return:
"""
N, _, T, J, C = input_2D.shape
input_2D_flip = input_2D[:, 1].view(N, T, J, C, 1).permute(0, 3, 1, 2, 4) #N, C, T, J , M
input_2D_non_flip = input_2D[:, 0].view(N, T, J, C, 1).permute(0, 3, 1, 2, 4) #N, C, T, J , M
# flip and reverse to original xyz
output_3D_flip = gsnet_gcn(input_2D_flip)
output_3D_flip[:, 0] *= -1
output_3D_flip[:, :, :, joints_left + joints_right] = output_3D_flip[:, :, :, joints_right + joints_left]
output_3D_non_flip = gsnet_gcn(input_2D_non_flip)
output_3D = (output_3D_non_flip + output_3D_flip) / 2
input_2D = input_2D_non_flip
return input_2D, output_3D