Tensorflow: Merge two 2-D tensors according to even and odd indices
To interleave two matrices vertically, you do not big guns such as gather
or map_fn
. You can simply interleave them as follows:
tf.reshape(
tf.stack([even_new, odd_new], axis=1),
[-1, tf.shape(even_new)[1]])
EDIT
To interleave them horizontally:
tf.reshape(
tf.concat([even_new[...,tf.newaxis], odd_new[...,tf.newaxis]], axis=-1),
[tf.shape(even_new)[0],-1])
The idea is to use stack to interleave them in memory. The dimension where the stack occurs gives the granularity of the interleaving. If we stack at axis=0
, then the interleaving occurs at each element, mixing columns. If we stack at axis=1
, entire input rows remain contiguous, interleaving occurs between rows.
you can use tf.dynamic_stitch
, that takes as first argument a list of tensors of indices for each tensor to interleave and as second argument a list of tensors to interleave. The tensors will be interleaved along the first dimension so we need to transpose them and then transpose back. Here is the code:
even_new = tf.transpose(even_new,perm=[1,0])
odd_new = tf.transpose(odd_new,perm=[1,0])
even_pos = tf.convert_to_tensor(list(range(0,256,2)),dtype=tf.int32)
odd_pos = tf.convert_to_tensor(list(range(1,256,2)),dtype=tf.int32)
interleaved = tf.dynamic_stitch([even_pos,odd_pos],[even_new,odd_new])
interleaved = tf.transpose(interleaved,perm=[1,0])