Reputation: 863
I have a 4-D tensor of shape [6,20,30,6]
and I would like to execute the keras/tensorflow equivalent of:
new = np.array([old[i,:,:,i] for i in range(6)])
Any help is appreciated!
Upvotes: 1
Views: 499
Reputation: 863
Thanks to @rvinas for his answer, I was able to cast this in pure keras.
def cc(x):
return K.backend.stack([x[:,i, :, :, i] for i in range(6)], axis=1)
Then in the keras model definition:
new=L.Lambda(lambda y: cc(y))(old)
Upvotes: 1
Reputation: 11895
You could expand the dimension of old
, use a comprehension list to select the desired slices and concatenate them along the expanded dimension. For example:
import tensorflow as tf
import numpy as np
tensor_shape = (6, 20, 30, 6)
old = np.arange(np.prod(tensor_shape)).reshape(tensor_shape)
new = np.array([old[i, :, :, i] for i in range(6)])
old_ = tf.placeholder(old.dtype, tensor_shape)
new_ = tf.concat([old[None, i, :, :, i] for i in range(6)], axis=0)
with tf.Session() as sess:
new_tf = sess.run(new_, feed_dict={old_: old})
assert (new == new_tf).all()
Upvotes: 1