-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtrain.py
206 lines (189 loc) · 7.38 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
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
import os
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import seq2seq
def plot(data):
framerate = 60
points = 2000
skip = int(len(data) / points)
duration = len(data) / float(framerate)
data_skipped = data.transpose(1, 0, 2)[:, ::skip, :]
plt.figure(figsize=(16, 10), facecolor='white')
for i, joint in enumerate(data_skipped):
plt.gca().set_prop_cycle(None)
plt.plot(np.linspace(0, duration, len(joint)), i + joint, lw=1)
plt.ylim([0, data_skipped.shape[0]])
plt.xlim([0, duration])
plt.ylabel('Joint')
plt.xlabel('Seconds')
plt.show()
def fixed_generator(data, hop_length, sequence_length, batch_size=50):
idxs = np.arange(0, len(data) - sequence_length, hop_length)
n_batches = len(idxs)
for batch_i in range(n_batches):
this_idxs = idxs[batch_i * batch_size:(batch_i + 1) * batch_size]
source = [data[i:i + sequence_length, :] for i in this_idxs]
target = [
data[i + sequence_length:i + sequence_length * 2, :]
for i in this_idxs
]
yield np.array(
source, dtype=np.float32), np.array(
target, dtype=np.float32)
def batch_generator(data, sequence_length, batch_size=50):
idxs = np.random.permutation(np.arange(len(data) - sequence_length * 2))
n_batches = len(idxs) // (batch_size * sequence_length)
for batch_i in range(n_batches):
this_idxs = idxs[batch_i * batch_size:(batch_i + 1) * batch_size]
source = [data[i:i + sequence_length, :] for i in this_idxs]
target = [
data[i + sequence_length:i + sequence_length * 2, :]
for i in this_idxs
]
yield np.array(
source, dtype=np.float32), np.array(
target, dtype=np.float32)
def train(data,
data_mean,
data_std,
n_epochs=1000,
batch_size=100,
sequence_length=240,
ckpt_path='./',
model_name='seq2seq.ckpt',
restore_name=None,
**kwargs):
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
net = seq2seq.create_model(
batch_size=batch_size, sequence_length=sequence_length, **kwargs)
learning_rate = tf.placeholder(tf.float32, name='learning_rate')
opt = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(
net['loss'])
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
sess.run(init_op)
saver = tf.train.Saver()
if restore_name:
saver.restore(sess, restore_name)
current_learning_rate = 0.0001
for epoch_i in range(n_epochs):
total, total_mse, total_mdn = 0.0, 0.0, 0.0
for it_i, (source, target) in enumerate(
batch_generator(
data,
sequence_length=sequence_length,
batch_size=batch_size)):
mse_loss, mdn_loss, _ = sess.run(
[net['mse_loss'], net['mdn_loss'], opt],
feed_dict={
learning_rate: current_learning_rate,
net['keep_prob']: 0.8,
net['source']: source,
net['target']: target
})
total += mse_loss + mdn_loss
total_mdn += mdn_loss
total_mse += mse_loss
print(
'{}: mdn: {}, mse: {}, total: {}'.format(
it_i, mdn_loss, mse_loss, mdn_loss + mse_loss),
end='\r')
current_learning_rate = max(0.0001, current_learning_rate * 0.99)
print('iteration: {}, learning rate: {}'.format(it_i,
current_learning_rate))
print('\n-- epoch {}: mdn: {}, mse: {}, total: {} --\n'.format(
epoch_i, total_mdn / (it_i + 1), total_mse / (it_i + 1),
total / (it_i + 1)))
saver.save(
sess, os.path.join(ckpt_path, model_name), global_step=epoch_i)
sess.close()
def infer(source,
target,
data_mean,
data_std,
batch_size,
sequence_length,
ckpt_path='./',
model_name='seq2seq.ckpt',
**kwargs):
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
with tf.Graph().as_default() as g, tf.Session(config=config) as sess:
net = seq2seq.create_model(
batch_size=batch_size, sequence_length=sequence_length, **kwargs)
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
sess.run(init_op)
saver = tf.train.Saver()
saver.restore(sess, os.path.join(ckpt_path, model_name))
recon, enc = sess.run(
[net['decoding'], net['encoding']],
feed_dict={
net['source']: source,
net['keep_prob']: 1.0
})
src = (source * data_std) + data_mean
tgt = (target * data_std) + data_mean
res = np.minimum(1.0, np.maximum(0.0, (recon[1] * data_std) + data_mean))
fig, axs = plt.subplots(1, 3, sharey=True)
axs[0].plot(src.reshape(-1, src.shape[-1]))
axs[0].set_title('Source')
axs[1].plot(tgt.reshape(-1, tgt.shape[-1]))
axs[1].set_title('Target (Original)')
axs[2].plot(res.reshape(-1, res.shape[-1]))
axs[2].set_title('Target (Synthesis Sampling)')
return {
'source': src,
'target': tgt,
'encoding': enc,
'prediction': res
}
# def feedback(source,
# target,
# data_mean,
# data_std,
# batch_size,
# sequence_length,
# ckpt_path='./',
# model_name='seq2seq.ckpt',
# **kwargs):
# config = tf.ConfigProto()
# config.gpu_options.allow_growth = True
# with tf.Graph().as_default() as g, tf.Session(config=config) as sess:
# net = seq2seq.create_model(
# batch_size=batch_size, sequence_length=sequence_length, **kwargs)
#
# init_op = tf.group(tf.global_variables_initializer(),
# tf.local_variables_initializer())
# sess.run(init_op)
# saver = tf.train.Saver()
# saver.restore(sess, os.path.join(ckpt_path, model_name))
# recon, enc = sess.run(
# [net['decoding'], net['encoding']],
# feed_dict={
# net['source']: source,
# net['keep_prob']: 1.0
# })
# src = (source * data_std) + data_mean
# tgt = (target * data_std) + data_mean
# res = np.minimum(1.0, np.maximum(0.0, (recon[1] * data_std) + data_mean))
# fig, axs = plt.subplots(1, 3, sharey=True)
# axs[0].plot(src.reshape(-1, src.shape[-1]))
# axs[0].set_title('Source')
# axs[1].plot(tgt.reshape(-1, tgt.shape[-1]))
# axs[1].set_title('Target (Original)')
# axs[2].plot(res.reshape(-1, res.shape[-1]))
# axs[2].set_title('Target (Synthesis Sampling)')
# np.save('source.npy', src)
# np.save('target.npy', tgt)
# np.save('encoding.npy', enc)
# np.save('prediction.npy', res)
# return {
# 'source': src,
# 'target': tgt,
# 'encoding': enc,
# 'prediction': res
# }