-
Notifications
You must be signed in to change notification settings - Fork 62
/
sketch_rnn.py
420 lines (386 loc) · 15.6 KB
/
sketch_rnn.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import numpy as np
import matplotlib.pyplot as plt
import PIL
import torch
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
use_cuda = torch.cuda.is_available()
###################################### hyperparameters
class HParams():
def __init__(self):
self.data_location = 'cat.npz'
self.enc_hidden_size = 256
self.dec_hidden_size = 512
self.Nz = 128
self.M = 20
self.dropout = 0.9
self.batch_size = 100
self.eta_min = 0.01
self.R = 0.99995
self.KL_min = 0.2
self.wKL = 0.5
self.lr = 0.001
self.lr_decay = 0.9999
self.min_lr = 0.00001
self.grad_clip = 1.
self.temperature = 0.4
self.max_seq_length = 200
hp = HParams()
################################# load and prepare data
def max_size(data):
"""larger sequence length in the data set"""
sizes = [len(seq) for seq in data]
return max(sizes)
def purify(strokes):
"""removes to small or too long sequences + removes large gaps"""
data = []
for seq in strokes:
if seq.shape[0] <= hp.max_seq_length and seq.shape[0] > 10:
seq = np.minimum(seq, 1000)
seq = np.maximum(seq, -1000)
seq = np.array(seq, dtype=np.float32)
data.append(seq)
return data
def calculate_normalizing_scale_factor(strokes):
"""Calculate the normalizing factor explained in appendix of sketch-rnn."""
data = []
for i in range(len(strokes)):
for j in range(len(strokes[i])):
data.append(strokes[i][j, 0])
data.append(strokes[i][j, 1])
data = np.array(data)
return np.std(data)
def normalize(strokes):
"""Normalize entire dataset (delta_x, delta_y) by the scaling factor."""
data = []
scale_factor = calculate_normalizing_scale_factor(strokes)
for seq in strokes:
seq[:, 0:2] /= scale_factor
data.append(seq)
return data
dataset = np.load(hp.data_location, encoding='latin1')
data = dataset['train']
data = purify(data)
data = normalize(data)
Nmax = max_size(data)
############################## function to generate a batch:
def make_batch(batch_size):
batch_idx = np.random.choice(len(data),batch_size)
batch_sequences = [data[idx] for idx in batch_idx]
strokes = []
lengths = []
indice = 0
for seq in batch_sequences:
len_seq = len(seq[:,0])
new_seq = np.zeros((Nmax,5))
new_seq[:len_seq,:2] = seq[:,:2]
new_seq[:len_seq-1,2] = 1-seq[:-1,2]
new_seq[:len_seq,3] = seq[:,2]
new_seq[(len_seq-1):,4] = 1
new_seq[len_seq-1,2:4] = 0
lengths.append(len(seq[:,0]))
strokes.append(new_seq)
indice += 1
if use_cuda:
batch = Variable(torch.from_numpy(np.stack(strokes,1)).cuda().float())
else:
batch = Variable(torch.from_numpy(np.stack(strokes,1)).float())
return batch, lengths
################################ adaptive lr
def lr_decay(optimizer):
"""Decay learning rate by a factor of lr_decay"""
for param_group in optimizer.param_groups:
if param_group['lr']>hp.min_lr:
param_group['lr'] *= hp.lr_decay
return optimizer
################################# encoder and decoder modules
class EncoderRNN(nn.Module):
def __init__(self):
super(EncoderRNN, self).__init__()
# bidirectional lstm:
self.lstm = nn.LSTM(5, hp.enc_hidden_size, \
dropout=hp.dropout, bidirectional=True)
# create mu and sigma from lstm's last output:
self.fc_mu = nn.Linear(2*hp.enc_hidden_size, hp.Nz)
self.fc_sigma = nn.Linear(2*hp.enc_hidden_size, hp.Nz)
# active dropout:
self.train()
def forward(self, inputs, batch_size, hidden_cell=None):
if hidden_cell is None:
# then must init with zeros
if use_cuda:
hidden = torch.zeros(2, batch_size, hp.enc_hidden_size).cuda()
cell = torch.zeros(2, batch_size, hp.enc_hidden_size.cuda()
else:
hidden = torch.zeros(2, batch_size, hp.enc_hidden_size)
cell = torch.zeros(2, batch_size, hp.enc_hidden_size)
hidden_cell = (hidden, cell)
_, (hidden,cell) = self.lstm(inputs.float(), hidden_cell)
# hidden is (2, batch_size, hidden_size), we want (batch_size, 2*hidden_size):
hidden_forward, hidden_backward = torch.split(hidden,1,0)
hidden_cat = torch.cat([hidden_forward.squeeze(0), hidden_backward.squeeze(0)],1)
# mu and sigma:
mu = self.fc_mu(hidden_cat)
sigma_hat = self.fc_sigma(hidden_cat)
sigma = torch.exp(sigma_hat/2.)
# N ~ N(0,1)
z_size = mu.size()
if use_cuda:
N = torch.normal(torch.zeros(z_size),torch.ones(z_size)).cuda()
else:
N = torch.normal(torch.zeros(z_size),torch.ones(z_size))
z = mu + sigma*N
# mu and sigma_hat are needed for LKL loss
return z, mu, sigma_hat
class DecoderRNN(nn.Module):
def __init__(self):
super(DecoderRNN, self).__init__()
# to init hidden and cell from z:
self.fc_hc = nn.Linear(hp.Nz, 2*hp.dec_hidden_size)
# unidirectional lstm:
self.lstm = nn.LSTM(hp.Nz+5, hp.dec_hidden_size, dropout=hp.dropout)
# create proba distribution parameters from hiddens:
self.fc_params = nn.Linear(hp.dec_hidden_size,6*hp.M+3)
def forward(self, inputs, z, hidden_cell=None):
if hidden_cell is None:
# then we must init from z
hidden,cell = torch.split(F.tanh(self.fc_hc(z)),hp.dec_hidden_size,1)
hidden_cell = (hidden.unsqueeze(0).contiguous(), cell.unsqueeze(0).contiguous())
outputs,(hidden,cell) = self.lstm(inputs, hidden_cell)
# in training we feed the lstm with the whole input in one shot
# and use all outputs contained in 'outputs', while in generate
# mode we just feed with the last generated sample:
if self.training:
y = self.fc_params(outputs.view(-1, hp.dec_hidden_size))
else:
y = self.fc_params(hidden.view(-1, hp.dec_hidden_size))
# separate pen and mixture params:
params = torch.split(y,6,1)
params_mixture = torch.stack(params[:-1]) # trajectory
params_pen = params[-1] # pen up/down
# identify mixture params:
pi,mu_x,mu_y,sigma_x,sigma_y,rho_xy = torch.split(params_mixture,1,2)
# preprocess params::
if self.training:
len_out = Nmax+1
else:
len_out = 1
pi = F.softmax(pi.transpose(0,1).squeeze()).view(len_out,-1,hp.M)
sigma_x = torch.exp(sigma_x.transpose(0,1).squeeze()).view(len_out,-1,hp.M)
sigma_y = torch.exp(sigma_y.transpose(0,1).squeeze()).view(len_out,-1,hp.M)
rho_xy = torch.tanh(rho_xy.transpose(0,1).squeeze()).view(len_out,-1,hp.M)
mu_x = mu_x.transpose(0,1).squeeze().contiguous().view(len_out,-1,hp.M)
mu_y = mu_y.transpose(0,1).squeeze().contiguous().view(len_out,-1,hp.M)
q = F.softmax(params_pen).view(len_out,-1,3)
return pi,mu_x,mu_y,sigma_x,sigma_y,rho_xy,q,hidden,cell
class Model():
def __init__(self):
if use_cuda:
self.encoder = EncoderRNN().cuda()
self.decoder = DecoderRNN().cuda()
else:
self.encoder = EncoderRNN()
self.decoder = DecoderRNN()
self.encoder_optimizer = optim.Adam(self.encoder.parameters(), hp.lr)
self.decoder_optimizer = optim.Adam(self.decoder.parameters(), hp.lr)
self.eta_step = hp.eta_min
def make_target(self, batch, lengths):
if use_cuda:
eos = torch.stack([torch.Tensor([0,0,0,0,1])]*batch.size()[1]).cuda().unsqueeze(0)
else:
eos = torch.stack([torch.Tensor([0,0,0,0,1])]*batch.size()[1]).unsqueeze(0)
batch = torch.cat([batch, eos], 0)
mask = torch.zeros(Nmax+1, batch.size()[1])
for indice,length in enumerate(lengths):
mask[:length,indice] = 1
if use_cuda:
mask = mask.cuda()
dx = torch.stack([batch.data[:,:,0]]*hp.M,2)
dy = torch.stack([batch.data[:,:,1]]*hp.M,2)
p1 = batch.data[:,:,2]
p2 = batch.data[:,:,3]
p3 = batch.data[:,:,4]
p = torch.stack([p1,p2,p3],2)
return mask,dx,dy,p
def train(self, epoch):
self.encoder.train()
self.decoder.train()
batch, lengths = make_batch(hp.batch_size)
# encode:
z, self.mu, self.sigma = self.encoder(batch, hp.batch_size)
# create start of sequence:
if use_cuda:
sos = torch.stack([torch.Tensor([0,0,1,0,0])]*hp.batch_size).cuda().unsqueeze(0)
else:
sos = torch.stack([torch.Tensor([0,0,1,0,0])]*hp.batch_size).unsqueeze(0)
# had sos at the begining of the batch:
batch_init = torch.cat([sos, batch],0)
# expend z to be ready to concatenate with inputs:
z_stack = torch.stack([z]*(Nmax+1))
# inputs is concatenation of z and batch_inputs
inputs = torch.cat([batch_init, z_stack],2)
# decode:
self.pi, self.mu_x, self.mu_y, self.sigma_x, self.sigma_y, \
self.rho_xy, self.q, _, _ = self.decoder(inputs, z)
# prepare targets:
mask,dx,dy,p = self.make_target(batch, lengths)
# prepare optimizers:
self.encoder_optimizer.zero_grad()
self.decoder_optimizer.zero_grad()
# update eta for LKL:
self.eta_step = 1-(1-hp.eta_min)*hp.R
# compute losses:
LKL = self.kullback_leibler_loss()
LR = self.reconstruction_loss(mask,dx,dy,p,epoch)
loss = LR + LKL
# gradient step
loss.backward()
# gradient cliping
nn.utils.clip_grad_norm(self.encoder.parameters(), hp.grad_clip)
nn.utils.clip_grad_norm(self.decoder.parameters(), hp.grad_clip)
# optim step
self.encoder_optimizer.step()
self.decoder_optimizer.step()
# some print and save:
if epoch%1==0:
print('epoch',epoch,'loss',loss.data[0],'LR',LR.data[0],'LKL',LKL.data[0])
self.encoder_optimizer = lr_decay(self.encoder_optimizer)
self.decoder_optimizer = lr_decay(self.decoder_optimizer)
if epoch%100==0:
#self.save(epoch)
self.conditional_generation(epoch)
def bivariate_normal_pdf(self, dx, dy):
z_x = ((dx-self.mu_x)/self.sigma_x)**2
z_y = ((dy-self.mu_y)/self.sigma_y)**2
z_xy = (dx-self.mu_x)*(dy-self.mu_y)/(self.sigma_x*self.sigma_y)
z = z_x + z_y -2*self.rho_xy*z_xy
exp = torch.exp(-z/(2*(1-self.rho_xy**2)))
norm = 2*np.pi*self.sigma_x*self.sigma_y*torch.sqrt(1-self.rho_xy**2)
return exp/norm
def reconstruction_loss(self, mask, dx, dy, p, epoch):
pdf = self.bivariate_normal_pdf(dx, dy)
LS = -torch.sum(mask*torch.log(1e-5+torch.sum(self.pi * pdf, 2)))\
/float(Nmax*hp.batch_size)
LP = -torch.sum(p*torch.log(self.q))/float(Nmax*hp.batch_size)
return LS+LP
def kullback_leibler_loss(self):
LKL = -0.5*torch.sum(1+self.sigma-self.mu**2-torch.exp(self.sigma))\
/float(hp.Nz*hp.batch_size)
if use_cuda:
KL_min = Variable(torch.Tensor([hp.KL_min]).cuda()).detach()
else:
KL_min = Variable(torch.Tensor([hp.KL_min])).detach()
return hp.wKL*self.eta_step * torch.max(LKL,KL_min)
def save(self, epoch):
sel = np.random.rand()
torch.save(self.encoder.state_dict(), \
'encoderRNN_sel_%3f_epoch_%d.pth' % (sel,epoch))
torch.save(self.decoder.state_dict(), \
'decoderRNN_sel_%3f_epoch_%d.pth' % (sel,epoch))
def load(self, encoder_name, decoder_name):
saved_encoder = torch.load(encoder_name)
saved_decoder = torch.load(decoder_name)
self.encoder.load_state_dict(saved_encoder)
self.decoder.load_state_dict(saved_decoder)
def conditional_generation(self, epoch):
batch,lengths = make_batch(1)
# should remove dropouts:
self.encoder.train(False)
self.decoder.train(False)
# encode:
z, _, _ = self.encoder(batch, 1)
if use_cuda:
sos = Variable(torch.Tensor([0,0,1,0,0]).view(1,1,-1).cuda())
else:
sos = Variable(torch.Tensor([0,0,1,0,0]).view(1,1,-1))
s = sos
seq_x = []
seq_y = []
seq_z = []
hidden_cell = None
for i in range(Nmax):
input = torch.cat([s,z.unsqueeze(0)],2)
# decode:
self.pi, self.mu_x, self.mu_y, self.sigma_x, self.sigma_y, \
self.rho_xy, self.q, hidden, cell = \
self.decoder(input, z, hidden_cell)
hidden_cell = (hidden, cell)
# sample from parameters:
s, dx, dy, pen_down, eos = self.sample_next_state()
#------
seq_x.append(dx)
seq_y.append(dy)
seq_z.append(pen_down)
if eos:
print(i)
break
# visualize result:
x_sample = np.cumsum(seq_x, 0)
y_sample = np.cumsum(seq_y, 0)
z_sample = np.array(seq_z)
sequence = np.stack([x_sample,y_sample,z_sample]).T
make_image(sequence, epoch)
def sample_next_state(self):
def adjust_temp(pi_pdf):
pi_pdf = np.log(pi_pdf)/hp.temperature
pi_pdf -= pi_pdf.max()
pi_pdf = np.exp(pi_pdf)
pi_pdf /= pi_pdf.sum()
return pi_pdf
# get mixture indice:
pi = self.pi.data[0,0,:].cpu().numpy()
pi = adjust_temp(pi)
pi_idx = np.random.choice(hp.M, p=pi)
# get pen state:
q = self.q.data[0,0,:].cpu().numpy()
q = adjust_temp(q)
q_idx = np.random.choice(3, p=q)
# get mixture params:
mu_x = self.mu_x.data[0,0,pi_idx]
mu_y = self.mu_y.data[0,0,pi_idx]
sigma_x = self.sigma_x.data[0,0,pi_idx]
sigma_y = self.sigma_y.data[0,0,pi_idx]
rho_xy = self.rho_xy.data[0,0,pi_idx]
x,y = sample_bivariate_normal(mu_x,mu_y,sigma_x,sigma_y,rho_xy,greedy=False)
next_state = torch.zeros(5)
next_state[0] = x
next_state[1] = y
next_state[q_idx+2] = 1
if use_cuda:
return Variable(next_state.cuda()).view(1,1,-1),x,y,q_idx==1,q_idx==2
else:
return Variable(next_state).view(1,1,-1),x,y,q_idx==1,q_idx==2
def sample_bivariate_normal(mu_x,mu_y,sigma_x,sigma_y,rho_xy, greedy=False):
# inputs must be floats
if greedy:
return mu_x,mu_y
mean = [mu_x, mu_y]
sigma_x *= np.sqrt(hp.temperature)
sigma_y *= np.sqrt(hp.temperature)
cov = [[sigma_x * sigma_x, rho_xy * sigma_x * sigma_y],\
[rho_xy * sigma_x * sigma_y, sigma_y * sigma_y]]
x = np.random.multivariate_normal(mean, cov, 1)
return x[0][0], x[0][1]
def make_image(sequence, epoch, name='_output_'):
"""plot drawing with separated strokes"""
strokes = np.split(sequence, np.where(sequence[:,2]>0)[0]+1)
fig = plt.figure()
ax1 = fig.add_subplot(111)
for s in strokes:
plt.plot(s[:,0],-s[:,1])
canvas = plt.get_current_fig_manager().canvas
canvas.draw()
pil_image = PIL.Image.frombytes('RGB', canvas.get_width_height(),
canvas.tostring_rgb())
name = str(epoch)+name+'.jpg'
pil_image.save(name,"JPEG")
plt.close("all")
if __name__=="__main__":
model = Model()
for epoch in range(50001):
model.train(epoch)
'''
model.load('encoder.pth','decoder.pth')
model.conditional_generation(0)
#'''