Home > Software design >  With Tensorflow, How to combine two arrays/tensors with interchanging index from each array?
With Tensorflow, How to combine two arrays/tensors with interchanging index from each array?

Time:05-05

Suppose I have the 2 arrays below:

 a = tf.constant([1,2,3])
 b = tf.constant([10,20,30])

How can we concatenate them using Tensorflow's methods, such that the new array is created by doing intervals of taking 1 number from each array one at a time? (Is there already a function that can do this?)

For example, the desired result for the 2 arrays is:

[1,10,2,20,3,30]

Methods with tf.concat just puts array b after array a.

CodePudding user response:

a = tf.constant([1,2,3])
b = tf.constant([10,20,30])
c = tf.stack([a,b]) #combine a,b as a matrix
d = tf.transpose(c) #transpose matrix to get the right order
e = tf.reshape(d, [-1]) #reshape to 1-d tensor

CodePudding user response:

You could also try using tf.tensor_scatter_nd_update:

import tensorflow as tf

a = tf.constant([1,2,3])
b = tf.constant([10,20,30])
shape = tf.shape(a)[0]   tf.shape(b)[0]

c = tf.tensor_scatter_nd_update(tf.zeros(shape, dtype=tf.int32), 
                            tf.expand_dims(tf.concat([tf.range(start=0, limit=shape, delta=2), tf.range(start=1, limit=shape, delta=2) ], axis=0), axis=-1), 
                            tf.concat([a, b], axis=0))

# tf.Tensor([ 1 10  2 20  3 30], shape=(6,), dtype=int32)
  • Related