Ashwin Raju
Ashwin Raju

Reputation: 153

How to create a new array of tensors from old one

I have a tensor [a, b, c, d, e, f, g, h, i] with dimension 9 X 1536. I need to create a new tensor which is like [(a,b), (a,c), (a,d), (a,e),(a,f),(a,g), (a,h), (a,i)] with dimension [8 x 2 x 1536]. How can I do it with tensorflow ? I tried like this

x = tf.zeros((9x1536)) 
x_new = tf.stack([(x[0],x[1]),
                  (x[0], x[2]),
                  (x[0], x[3]),
                  (x[0], x[4]),
                  (x[0], x[5]),
                  (x[0], x[6]),
                  (x[0], x[7]),
                  (x[0], x[8])])

This seems to work but I would like to know if there is a better solution or approach which can be used instead of this

Upvotes: 1

Views: 569

Answers (1)

GPhilo
GPhilo

Reputation: 19123

You can obtain the desired output with a combination of tf.concat, tf.tile and tf.expand_dims:

import tensorflow as tf
import numpy as np

_in = tf.constant(np.random.randint(0,10,(9,1536)))

tile_shape = [(_in.shape[0]-1).value] + [1]*len(_in.shape[1:].as_list())

_out = tf.concat([
    tf.expand_dims(
        tf.tile(
            [_in[0]],
            tile_shape
        )
        ,
        1),
    tf.expand_dims(_in[1:], 1)
    ],
    1
    )

tf.tile repeats the first element of _in creating a tensor of length len(_in)-1 (I compute separately the shape of the tile because we want to tile only on the first dimension).

tf.expand_dims adds a dimension we can then concat on

Finally, tf.concat stitches together the two tensors giving the desired result.

EDIT: Rewrote to fit the OP's actual use-case with multidimensional tensors.

Upvotes: 1

Related Questions