-
Notifications
You must be signed in to change notification settings - Fork 3
/
optimize.py
176 lines (129 loc) · 6.93 KB
/
optimize.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
''' Version 1.000
Code provided by Daniel Jiwoong Im
Permission is granted for anyone to copy, use, modify, or distribute this
program and accompanying programs and documents for any purpose, provided
this copyright notice is retained and prominently displayed, along with
a note saying that the original programs are available from our
web page.
The programs and documents are distributed without any warranty, express or
implied. As the programs were written for research purposes only, they have
not been tested to the degree that would be advisable in any important
application. All use of these programs is entirely at the user's own risk.'''
'''Demo of Denoising Criterion for Variational Auto-encoding Framework.
For more information, see :http://arxiv.org/abs/1511.06406
'''
import os, sys
import numpy as np
import pylab
import cPickle
import theano
import theano.tensor as T
import theano.tensor.signal.conv
from theano.tensor.shared_randomstreams import RandomStreams
import theano.sandbox.rng_mrg as RNG_MRG
rng = np.random.RandomState(1234)
MRG = RNG_MRG.MRG_RandomStreams(rng.randint(2 ** 30))
class Optimize():
def __init__(self, opt_params):
self.batch_sz, self.epsilon, self.momentum, self.num_epoch, \
self.N, self.Nv, self.Nt, self.corrupt_in, self.ntype = opt_params
def MGD(self, model, train_set, valid_set, test_set, binaryF, CrossEntropyF):
update_grads = []; updates_mom = []; deltaWs = {}
mom = T.scalar('mom'); i = T.iscalar('i'); lr = T.fscalar('lr');
X = T.matrix('X')
X.tag.test_value = np.zeros((100, 560), dtype=theano.config.floatX)
cost = model.cost(X, binaryF=binaryF, CrossEntropyF=CrossEntropyF, corrupt_in=self.corrupt_in, ntype=self.ntype)
cost_test = model.cost(X, binaryF=binaryF, CrossEntropyF=CrossEntropyF, M=1, L=1)
gparams = T.grad(cost, model.params)
#gparams = self.clip_gradient(model.params, gparams)
#Update momentum
for param in model.params:
init = np.zeros(param.get_value(borrow=True).shape,
dtype=theano.config.floatX)
deltaWs[param] = theano.shared(init)
for param in model.params:
updates_mom.append((param, param + deltaWs[param] * \
T.cast(mom, dtype=theano.config.floatX)))
for param, gparam in zip(model.params, gparams):
deltaV = T.cast(mom, dtype=theano.config.floatX)\
* deltaWs[param] - gparam * T.cast(lr, dtype=theano.config.floatX) #new momentum
update_grads.append((deltaWs[param], deltaV))
new_param = param + deltaV
update_grads.append((param, new_param))
update_momentum = theano.function([theano.Param(mom,default=self.momentum)],\
[], updates=updates_mom)
train_update = theano.function([i, theano.Param(lr,default=self.epsilon),\
theano.Param(mom,default=self.momentum)], outputs=cost, updates=update_grads,\
givens={ X:train_set[0][i*self.batch_sz:(i+1)*self.batch_sz]})
get_valid_cost = theano.function([i], outputs=cost_test,\
givens={ X:valid_set[0][i*self.batch_sz:(i+1)*self.batch_sz]})
get_test_cost = theano.function([i], outputs=cost_test,\
givens={ X:test_set[0][i*self.batch_sz:(i+1)*self.batch_sz]})
return train_update, update_momentum, get_valid_cost, get_test_cost
def ADAM(self, model, train_set, valid_set, test_set, binaryF, CrossEntropyF,\
beta1 = 0.1,beta2 = 0.001,epsilon = 1e-8, l = 1e-8):
i = T.iscalar('i'); lr = T.fscalar('lr');
X = T.matrix('X');
X.tag.test_value = np.zeros((100, 560), dtype=theano.config.floatX)
cost = model.cost(X, binaryF=binaryF, CrossEntropyF=CrossEntropyF, corrupt_in=self.corrupt_in, ntype=self.ntype)
cost_test = model.cost(X, binaryF=binaryF, CrossEntropyF=CrossEntropyF)
gparams = T.grad(cost, model.params)
gparams = self.clip_gradient(model.params, gparams)
'''ADAM Code from
https://github.com/danfischetti/deep-recurrent-attentive-writer/blob/master/DRAW/adam.py
'''
self.m = [theano.shared(name = 'm', \
value = np.zeros(param.get_value().shape,dtype=theano.config.floatX)) for param in model.params]
self.v = [theano.shared(name = 'v', \
value = np.zeros(param.get_value().shape,dtype=theano.config.floatX)) for param in model.params]
self.t = theano.shared(name = 't',value = np.asarray(1).astype(theano.config.floatX))
updates = [(self.t,self.t+1)]
for param, gparam,m,v in zip(model.params, gparams, self.m, self.v):
b1_t = 1-(1-beta1)*(l**(self.t-1))
m_t = b1_t*gparam + (1-b1_t)*m
updates.append((m,m_t))
v_t = beta2*(gparam**2)+(1-beta2)*v
updates.append((v,v_t))
m_t_bias = m_t/(1-(1-beta1)**self.t)
v_t_bias = v_t/(1-(1-beta2)**self.t)
new_param = param - lr*m_t_bias/(T.sqrt(v_t_bias)+epsilon)
updates.append((param, new_param))
#import ipdb; ipdb.set_trace()
train_update = theano.function([i, theano.Param(lr,default=self.epsilon)],\
outputs=cost, updates=updates,\
givens={ X:train_set[0][i*self.batch_sz:(i+1)*self.batch_sz]})
get_valid_cost = theano.function([i], outputs=cost_test,\
givens={ X:valid_set[0][i*self.batch_sz:(i+1)*self.batch_sz]})
get_test_cost = theano.function([i], outputs=cost_test,\
givens={ X:test_set[0][i*self.batch_sz:(i+1)*self.batch_sz]})
return train_update, get_valid_cost, get_test_cost
def clip_gradient(self, params, gparams, scalar=5, check_nanF=True):
"""
Sequence to sequence
"""
num_params = len(gparams)
g_norm = 0.
for i in xrange(num_params):
gparam = gparams[i]
g_norm += (gparam**2).sum()
if check_nanF:
not_finite = T.or_(T.isnan(g_norm), T.isinf(g_norm))
g_norm = T.sqrt(g_norm)
scalar = scalar / T.maximum(scalar, g_norm)
if check_nanF:
for i in xrange(num_params):
param = params[i]
gparams[i] = T.switch(not_finite, 0.1 * param, gparams[i] * scalar)
else:
for i in xrange(num_params):
gparams[i] = gparams[i] * scalar
return gparams
def get_recon(self, model, valid_set, binaryF):
i = T.iscalar('i');
X = T.fmatrix('X')
reconX = model.get_recon_X(X, binaryF=binaryF)
get_recon = theano.function([i], reconX, givens={ X:valid_set[0][:i]})
return get_recon
def get_samples(self, model, binaryF):
i = T.iscalar('i');
return theano.function([i], model.get_sample(i, binaryF))