-
Notifications
You must be signed in to change notification settings - Fork 1
/
lds_imitator.py
364 lines (251 loc) · 12.3 KB
/
lds_imitator.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
import tensorflow as tf
import os
import numpy as np
def affine_layer(inputs,activation=None,name=""):
input_size = int(inputs.shape[-1])
k = tf.get_variable('affine_k_{}'.format(name), [input_size],initializer=tf.initializers.constant(1.0))
d = tf.get_variable("affine_d_{}".format(name), [input_size],initializer=tf.initializers.constant(0.0))
y = inputs*k + d
if(not activation is None):
y = activation(y)
return y
class LDS_Cell(tf.nn.rnn_cell.RNNCell):
def __init__(self, num_units,cell_clip=-1):
self._num_units = num_units
self._num_unfolds = 6
self._delta_t = 1.0/self._num_unfolds
self.cell_clip = cell_clip
def _dense(self,units,inputs,activation,name,bias_initializer=tf.constant_initializer(0.0)):
input_size = int(inputs.shape[-1])
W = tf.get_variable('W_{}'.format(name), [input_size, units])
b = tf.get_variable("bias_{}".format(name), [units],initializer=bias_initializer)
y = tf.matmul(inputs,W) + b
if(not activation is None):
y = activation(y)
return y
def linear(self,units,inputs,name=""):
input_size = int(inputs.shape[-1])
W = tf.get_variable('W_linear'+name, [input_size, units],initializer=tf.truncated_normal_initializer(stddev=0.01))
y = tf.matmul(inputs,W)
return y,W
@property
def state_size(self):
return self._num_units
@property
def output_size(self):
return self._num_units
def build(self,input_shape):
pass
def __call__(self, inputs, state, scope=None):
self._input_size = int(inputs.shape[-1])
with tf.variable_scope(scope or type(self).__name__):
with tf.variable_scope("RNN",reuse=tf.AUTO_REUSE): # Reset gate and update gate.
for i in range(self._num_unfolds):
state_f_prime,self.W = self.linear(inputs=state,units=self._num_units)
in_f_prime,b = self.linear(inputs=inputs,units=self._num_units,name="inputs")
f_prime = state_f_prime + in_f_prime
# df/dt
# If we solve this ODE with explicit euler we get
# f(t+deltaT) = f(t) + deltaT * df/dt
state = state + self._delta_t * f_prime
return state,state
class LDS_Imitator:
def __init__(self,num_units,clip_value,lidar_size,state_size):
self.lidar_size = lidar_size
self.state_size = state_size
self.num_units = num_units
self.x_lidar = tf.placeholder(tf.float32, shape=[None, None, self.lidar_size],name='lidar')
self.x_state = tf.placeholder(tf.float32, shape=[None, None, self.state_size],name='state')
self.target_y = tf.placeholder(tf.float32, shape=[None,None,1])
head = tf.reshape(self.x_lidar,[-1,self.lidar_size,1])
head = tf.keras.layers.Conv1D(12,5,strides=3,activation="relu")(head)
head = tf.keras.layers.Conv1D(16,5,strides=3,activation="relu")(head)
head = tf.keras.layers.Conv1D(24,5,strides=2,activation="relu")(head)
head = tf.keras.layers.Conv1D(1,1,strides=1,activation=None)(head)
head = tf.keras.layers.Flatten()(head)
head = tf.reshape(head,shape=[tf.shape(self.x_lidar)[0],tf.shape(self.x_lidar)[1],head.shape[-1]])
estim_in = self.x_state
estim_in = tf.clip_by_value(estim_in,-1.0,1.0)
head = tf.concat([head,estim_in],axis=-1)
print("head shape: ",str(head.shape))
head = affine_layer(head,name="input")
self.init_state = tf.placeholder(tf.float32,[None,self.num_units],name="initial_state")
self.fused_cell = LDS_Cell(self.num_units,cell_clip=clip_value)
cell_out,self.final_state = tf.nn.dynamic_rnn(self.fused_cell,head,initial_state = self.init_state,time_major=True)
cell_out = tf.reshape(cell_out,[-1,self.num_units])
cell_out = affine_layer(cell_out)
y = tf.keras.layers.Dense(1,activation=None,name="ct_out")(cell_out)
# Reshape back to sequenced batch form
self.y = tf.reshape(y,shape=[tf.shape(self.x_state)[0],tf.shape(self.x_state)[1],1])
#Output
tf.identity(self.y,name='prediction')
tf.identity(self.final_state,name='final_state')
self.add_stablity_optimization()
self.loss = tf.reduce_mean(tf.square(tf.subtract(self.target_y, self.y))) + 0.0*self.surrogate_loss
# Loss, error and training algorithm
self.mean_abs_error = tf.reduce_mean(tf.abs(tf.subtract(self.y, self.target_y)))
optimizer = tf.train.AdamOptimizer(0.0001)
self.train_step = optimizer.minimize(self.loss)
def zero_state(self,batch_size):
return np.zeros([batch_size,self.num_units],dtype=np.float32)
def share_sess(self, sess):
self.sess = sess
def is_stable(self):
A = self.sess.run(self.fused_cell.W)
e,v = np.linalg.eig(A)
stable = True
for i in range(e.shape[0]):
r = np.real(e[i])
if(r > 0.0):
stable = False
return stable
def add_stablity_optimization(self):
diag_part = tf.diag_part(self.fused_cell.W)
row_reduced = tf.reduce_sum(tf.abs(self.fused_cell.W),axis=1)
abs_diag = tf.abs(diag_part)
# Summation trick to avoid summing over the diagonal
R = row_reduced-abs_diag
# Upper bound on lambda on real axis
lambda_ub = diag_part + R
self.surrogate_loss = tf.reduce_sum(tf.nn.relu(lambda_ub))
optimizer = tf.train.AdamOptimizer(0.0001)
self.opt_stability = optimizer.minimize(self.surrogate_loss)
def predict_step(self, x_state, x_lidar,init_state=None):
if(init_state is None):
init_state = self.zero_state(1)
# Reshape sequence into a batch of 1 sequence
x_state = x_state.reshape([1,1,self.state_size])
x_lidar = x_lidar.reshape([1,1,self.lidar_size])
feed_dict = {
self.x_state: x_state,
self.x_lidar: x_lidar,
self.init_state: init_state}
prediction,next_state = self.sess.run([self.y,self.final_state], feed_dict=feed_dict)
return float(prediction.flatten()),next_state
def evaluate(self, batch_x_state, batch_x_lidar,batch_y):
feed_dict = {
self.x_state: batch_x_state,
self.x_lidar: batch_x_lidar,
self.target_y: batch_y,
self.init_state:self.zero_state(batch_x_state.shape[1])
}
loss,mae = self.sess.run([self.loss,self.mean_abs_error], feed_dict=feed_dict)
return loss,mae
def train_iter(self, batch_x_state, batch_x_lidar,batch_y):
feed_dict = {
self.x_state: batch_x_state,
self.x_lidar: batch_x_lidar,
self.target_y: batch_y,
self.init_state:self.zero_state(batch_x_state.shape[1])
}
(_,loss,mae) = self.sess.run([self.train_step, self.loss,self.mean_abs_error], feed_dict=feed_dict)
return loss,mae
def create_checkpoint(self, path, name='model'):
if not os.path.exists(path):
os.makedirs(path)
checkpoint_path = os.path.join(path, '-'+name)
self.saver = tf.train.Saver()
filename = self.saver.save(self.sess, checkpoint_path)
w_path = os.path.join(path,"w.csv")
A = self.sess.run(self.fused_cell.W)
np.savetxt(w_path,A)
e,v = np.linalg.eig(A)
w_info = os.path.join(path,"eigen.txt")
with open(w_info,"w") as f:
f.write("Eigenvalues: "+str(e))
def restore_from_checkpoint(self, path):
self.saver = tf.train.Saver()
self.saver.restore(self.sess, os.path.join(path,'-model'))
class LDS_Cheetah:
def __init__(self,num_units,clip_value,obs_size,action_size):
self.obs_size = obs_size
self.action_size = action_size
self.num_units = num_units
self.x_obs = tf.placeholder(tf.float32, shape=[None, None, self.obs_size],name='state')
self.target_y = tf.placeholder(tf.float32, shape=[None,None,self.action_size])
head = tf.reshape(self.x_obs,[-1,self.obs_size])
head = tf.keras.layers.Dense(128,activation="relu")(head)
head = tf.keras.layers.Dense(128,activation=None)(head)
head = tf.reshape(head,shape=[tf.shape(self.x_obs)[0],tf.shape(self.x_obs)[1],head.shape[-1]])
self.init_state = tf.placeholder(tf.float32,[None,self.num_units],name="initial_state")
self.fused_cell = LDS_Cell(self.num_units,cell_clip=clip_value)
cell_out,self.final_state = tf.nn.dynamic_rnn(self.fused_cell,head,initial_state = self.init_state,time_major=True)
cell_out = tf.reshape(cell_out,[-1,self.num_units])
y = tf.keras.layers.Dense(self.action_size,activation=None,name="ct_out")(cell_out)
# Reshape back to sequenced batch form
self.y = tf.reshape(y,shape=[tf.shape(self.x_obs)[0],tf.shape(self.x_obs)[1],self.action_size])
#Output
tf.identity(self.y,name='prediction')
tf.identity(self.final_state,name='final_state')
self.loss = tf.reduce_mean(tf.reduce_sum(tf.square(tf.subtract(self.target_y, self.y)),axis=-1))
self.add_stablity_optimization()
# Loss, error and training algorithm
self.mean_abs_error = tf.reduce_mean(tf.abs(tf.subtract(self.y, self.target_y)))
optimizer = tf.train.AdamOptimizer(0.0001)
self.train_step = optimizer.minimize(self.loss)
def zero_state(self,batch_size):
return np.zeros([batch_size,self.num_units],dtype=np.float32)
def share_sess(self, sess):
self.sess = sess
def is_stable(self):
A = self.sess.run(self.fused_cell.W)
e,v = np.linalg.eig(A)
stable = True
for i in range(e.shape[0]):
r = np.real(e[i])
if(r > 0.0):
stable = False
return stable
def add_stablity_optimization(self):
diag_part = tf.diag_part(self.fused_cell.W)
row_reduced = tf.reduce_sum(tf.abs(self.fused_cell.W),axis=1)
abs_diag = tf.abs(diag_part)
# Summation trick to avoid summing over the diagonal
R = row_reduced-abs_diag
# Upper bound on lambda on real axis
lambda_ub = diag_part + R + 0.00000001
self.surrogate_loss = tf.reduce_sum(tf.nn.relu(lambda_ub))
optimizer = tf.train.AdamOptimizer(0.0001)
self.opt_stability = optimizer.minimize(self.surrogate_loss)
def predict_step(self, x_obs,init_state=None):
if(init_state is None):
init_state = self.zero_state(1)
# Reshape sequence into a batch of 1 sequence
x_obs = x_obs.reshape([1,1,self.obs_size])
feed_dict = {
self.x_obs: x_obs,
self.init_state: init_state}
prediction,next_state = self.sess.run([self.y,self.final_state], feed_dict=feed_dict)
return prediction.flatten(),next_state
def evaluate(self, batch_x_obs, batch_action):
feed_dict = {
self.x_obs: batch_x_obs,
self.target_y: batch_action,
self.init_state:self.zero_state(batch_x_obs.shape[1])
}
loss,mae = self.sess.run([self.loss,self.mean_abs_error], feed_dict=feed_dict)
return loss,mae
def train_iter(self, batch_x_obs, batch_action):
feed_dict = {
self.x_obs: batch_x_obs,
self.target_y: batch_action,
self.init_state:self.zero_state(batch_x_obs.shape[1])
}
(_,loss,mae) = self.sess.run([self.train_step, self.loss,self.mean_abs_error], feed_dict=feed_dict)
return loss,mae
def create_checkpoint(self, path, name='model'):
if not os.path.exists(path):
os.makedirs(path)
checkpoint_path = os.path.join(path, '-'+name)
self.saver = tf.train.Saver()
filename = self.saver.save(self.sess, checkpoint_path)
w_path = os.path.join(path,"w.csv")
A = self.sess.run(self.fused_cell.W)
np.savetxt(w_path,A)
e,v = np.linalg.eig(A)
w_info = os.path.join(path,"eigen.txt")
with open(w_info,"w") as f:
f.write("Eigenvalues: "+str(e))
def restore_from_checkpoint(self, path):
self.saver = tf.train.Saver()
self.saver.restore(self.sess, os.path.join(path,'-model'))