-
Notifications
You must be signed in to change notification settings - Fork 45
/
main_3dpw_3d.py
283 lines (241 loc) · 10.4 KB
/
main_3dpw_3d.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
import os
import time
import torch
import torch.nn as nn
import torch.optim
from torch.utils.data import DataLoader
from torch.autograd import Variable
from torch.nn import functional
import numpy as np
from progress.bar import Bar
import pandas as pd
from utils import loss_funcs, utils as utils
from utils.opt import Options
from utils.pose3dpw3d import Pose3dPW3D
import utils.model as nnmodel
import utils.data_utils as data_utils
def main(opt):
start_epoch = 0
err_best = 10000
lr_now = opt.lr
is_cuda = torch.cuda.is_available()
# save option in log
script_name = os.path.basename(__file__).split('.')[0]
script_name = script_name + '_out_{:d}_dctn_{:d}'.format(opt.output_n, opt.dct_n)
# create model
print(">>> creating model")
input_n = opt.input_n
output_n = opt.output_n
dct_n = opt.dct_n
model = nnmodel.GCN(input_feature=dct_n, hidden_feature=opt.linear_size, p_dropout=opt.dropout,
num_stage=opt.num_stage, node_n=69)
if is_cuda:
model.cuda()
print(">>> total params: {:.2f}M".format(sum(p.numel() for p in model.parameters()) / 1000000.0))
optimizer = torch.optim.Adam(model.parameters(), lr=opt.lr)
if opt.is_load:
model_path_len = 'checkpoint/test/ckpt_main_last.pth.tar'
print(">>> loading ckpt len from '{}'".format(model_path_len))
if is_cuda:
ckpt = torch.load(model_path_len)
else:
ckpt = torch.load(model_path_len, map_location='cpu')
start_epoch = ckpt['epoch']
err_best = ckpt['err']
lr_now = ckpt['lr']
model.load_state_dict(ckpt['state_dict'])
optimizer.load_state_dict(ckpt['optimizer'])
print(">>> ckpt len loaded (epoch: {} | err: {})".format(start_epoch, err_best))
# data loading
print(">>> loading data")
train_dataset = Pose3dPW3D(path_to_data=opt.data_dir_3dpw, input_n=input_n, output_n=output_n, split=0,
dct_n=dct_n)
dim_used = train_dataset.dim_used
test_dataset = Pose3dPW3D(path_to_data=opt.data_dir_3dpw, input_n=input_n, output_n=output_n, split=1,
dct_n=dct_n)
val_dataset = Pose3dPW3D(path_to_data=opt.data_dir_3dpw, input_n=input_n, output_n=output_n, split=2,
dct_n=dct_n)
# load dadasets for training
train_loader = DataLoader(
dataset=train_dataset,
batch_size=opt.train_batch,
shuffle=True,
num_workers=opt.job,
pin_memory=True)
test_loader = DataLoader(
dataset=test_dataset,
batch_size=opt.test_batch,
shuffle=False,
num_workers=opt.job,
pin_memory=True)
val_loader = DataLoader(
dataset=val_dataset,
batch_size=opt.test_batch,
shuffle=False,
num_workers=opt.job,
pin_memory=True)
print(">>> data loaded !")
print(">>> train data {}".format(train_dataset.__len__()))
print(">>> test data {}".format(test_dataset.__len__()))
print(">>> validation data {}".format(val_dataset.__len__()))
for epoch in range(start_epoch, opt.epochs):
if (epoch + 1) % opt.lr_decay == 0:
lr_now = utils.lr_decay(optimizer, lr_now, opt.lr_gamma)
print('==========================')
print('>>> epoch: {} | lr: {:.5f}'.format(epoch + 1, lr_now))
ret_log = np.array([epoch + 1])
head = np.array(['epoch'])
# per epoch
lr_now, t_3d = train(train_loader, model,
optimizer,
lr_now=lr_now,
max_norm=opt.max_norm,
is_cuda=is_cuda,
dct_n=dct_n,
dim_used=dim_used)
ret_log = np.append(ret_log, [lr_now, t_3d * 1000])
head = np.append(head, ['lr', 't_3d'])
v_3d = val(val_loader, model,
is_cuda=is_cuda,
dct_n=dct_n,
dim_used=dim_used)
ret_log = np.append(ret_log, v_3d * 1000)
head = np.append(head, ['v_3d'])
test_3d = test(test_loader, model,
input_n=input_n,
output_n=output_n,
is_cuda=is_cuda,
dim_used=dim_used,
dct_n=dct_n)
ret_log = np.append(ret_log, test_3d * 1000)
if output_n == 15:
head = np.append(head, ['1003d', '2003d', '3003d', '4003d', '5003d'])
elif output_n == 30:
head = np.append(head, ['1003d', '2003d', '3003d', '4003d', '5003d', '6003d', '7003d', '8003d', '9003d',
'10003d'])
# update log file
df = pd.DataFrame(np.expand_dims(ret_log, axis=0))
if epoch == start_epoch:
df.to_csv(opt.ckpt + '/' + script_name + '.csv', header=head, index=False)
else:
with open(opt.ckpt + '/' + script_name + '.csv', 'a') as f:
df.to_csv(f, header=False, index=False)
# save ckpt
is_best = v_3d < err_best
err_best = min(v_3d, err_best)
file_name = ['ckpt_' + script_name + '_best.pth.tar', 'ckpt_' + script_name + '_last.pth.tar']
utils.save_ckpt({'epoch': epoch + 1,
'lr': lr_now,
'err': test_3d[0],
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict()},
ckpt_path=opt.ckpt,
is_best=is_best,
file_name=file_name)
def train(train_loader, model, optimizer, lr_now=None, max_norm=True, is_cuda=False, dct_n=15, dim_used=[]):
t_3d = utils.AccumLoss()
model.train()
st = time.time()
bar = Bar('>>>', fill='>', max=len(train_loader))
for i, (inputs, targets, all_seq) in enumerate(train_loader):
batch_size = inputs.shape[0]
if batch_size == 1:
break
bt = time.time()
if is_cuda:
inputs = Variable(inputs.cuda()).float()
# targets = Variable(targets.cuda(async=True)).float()
all_seq = Variable(all_seq.cuda(async=True)).float()
else:
inputs = Variable(inputs).float()
# targets = Variable(targets).float()
all_seq = Variable(all_seq).float()
outputs = model(inputs)
m_err = loss_funcs.mpjpe_error_3dpw(outputs, all_seq, dct_n, dim_used)
# calculate loss and backward
optimizer.zero_grad()
m_err.backward()
if max_norm:
nn.utils.clip_grad_norm(model.parameters(), max_norm=1)
optimizer.step()
n, seq_len, _ = all_seq.data.shape
t_3d.update(m_err.cpu().data.numpy()[0] * n * seq_len, n * seq_len)
bar.suffix = '{}/{}|batch time {:.4f}s|total time{:.2f}s'.format(i, len(train_loader), time.time() - bt,
time.time() - st)
bar.next()
bar.finish()
return lr_now, t_3d.avg
def test(train_loader, model, input_n=20, output_n=50, is_cuda=False, dim_used=[], dct_n=15):
N = 0
if output_n == 15:
eval_frame = [2, 5, 8, 11, 14]
elif output_n == 30:
eval_frame = [2, 5, 8, 11, 14, 17, 20, 23, 26, 29]
t_3d = np.zeros(len(eval_frame))
model.eval()
st = time.time()
bar = Bar('>>>', fill='>', max=len(train_loader))
for i, (inputs, targets, all_seq) in enumerate(train_loader):
bt = time.time()
if is_cuda:
inputs = Variable(inputs.cuda()).float()
# targets = Variable(targets.cuda(async=True)).float()
all_seq = Variable(all_seq.cuda(async=True)).float()
else:
inputs = Variable(inputs).float()
# targets = Variable(targets).float()
all_seq = Variable(all_seq).float()
outputs = model(inputs)
n, seq_len, dim_full_len = all_seq.data.shape
_, idct_m = data_utils.get_dct_matrix(seq_len)
idct_m = Variable(torch.from_numpy(idct_m)).float().cuda()
outputs_t = outputs.view(-1, dct_n).transpose(0, 1)
outputs_exp = torch.matmul(idct_m[:, 0:dct_n], outputs_t).transpose(0, 1).contiguous().view \
(-1, dim_full_len - 3, seq_len).transpose(1, 2)
pred_3d = all_seq.clone()
pred_3d[:, :, dim_used] = outputs_exp
pred_p3d = pred_3d.contiguous().view(n, seq_len, -1, 3)[:, input_n:, :, :]
targ_p3d = all_seq.contiguous().view(n, seq_len, -1, 3)[:, input_n:, :, :]
for k in np.arange(0, len(eval_frame)):
j = eval_frame[k]
t_3d[k] += torch.mean(torch.norm(
targ_p3d[:, j, :, :].contiguous().view(-1, 3) - pred_p3d[:, j, :, :].contiguous().view(-1, 3), 2,
1)).cpu().data.numpy()[0] * n
# update the training loss
N += n
bar.suffix = '{}/{}|batch time {:.4f}s|total time{:.2f}s'.format(i, len(train_loader), time.time() - bt,
time.time() - st)
bar.next()
bar.finish()
return t_3d / N
def val(train_loader, model, is_cuda=False, dim_used=[], dct_n=15):
t_3d = utils.AccumLoss()
model.eval()
st = time.time()
bar = Bar('>>>', fill='>', max=len(train_loader))
for i, (inputs, targets, all_seq) in enumerate(train_loader):
bt = time.time()
if is_cuda:
inputs = Variable(inputs.cuda()).float()
# targets = Variable(targets.cuda(async=True)).float()
all_seq = Variable(all_seq.cuda(async=True)).float()
else:
inputs = Variable(inputs).float()
# targets = Variable(targets).float()
all_seq = Variable(all_seq).float()
outputs = model(inputs)
m_err = loss_funcs.mpjpe_error_3dpw(outputs, all_seq, dct_n=dct_n, dim_used=dim_used)
n, seq_len, _ = all_seq.data.shape
# update the training loss
t_3d.update(m_err.cpu().data.numpy()[0] * n * seq_len, n * seq_len)
bar.suffix = '{}/{}|batch time {:.4f}s|total time{:.2f}s'.format(i, len(train_loader), time.time() - bt,
time.time() - st)
bar.next()
bar.finish()
return t_3d.avg
if __name__ == "__main__":
option = Options().parse()
main(option)