replicate a row tensor using tf.tile?

Take the following, vec is a vector, multiply is your m, the number of times to repeat the vector. tf.tile is performed on the vector and then using tf.reshape it is reshaped into the desired structure.

import tensorflow as tf

vec = tf.constant([1, 2, 3, 4])
multiply = tf.constant([3])

matrix = tf.reshape(tf.tile(vec, multiply), [ multiply[0], tf.shape(vec)[0]])
with tf.Session() as sess:
    print(sess.run([matrix]))

This results in:

[array([[1, 2, 3, 4],
       [1, 2, 3, 4],
       [1, 2, 3, 4]], dtype=int32)]

The same can be achieved by multiplying a ones matrix with vec and let broadcasting do the trick:

tf.ones([m, 1]) * vec

vec = tf.constant([1., 2., 3., 4.])
m = 3
matrix = tf.ones([m, 1]) * vec

with tf.Session() as sess:
   print(sess.run([matrix]))

#Output: [[1., 2., 3., 4.],
#         [1., 2., 3., 4.],
#         [1., 2., 3., 4.]]

replicating / duplicating a tensor (be it a 1D vector, 2D matrix, or any dimension) can be done by creating a list of copies of this tensor (with pure python), and then using tf.stack - having both steps in one (short) line. Here is an example of duplicating a 2D Tensor:

import tensorflow as tf
tf.enable_eager_execution()

a = tf.constant([[1,2,3],[4,5,6]])  # shape=(2,3)
a_stack = tf.stack([a] * 4)  # shape=(4,2,3)

print(a)
print(a_stack)

"[a]*4" creates a list containing four copies of the same tensor (this is pure python). tf.stack then stack them one after the other, on the first axis (axis=0)

In graph mode:

import tensorflow as tf

a = tf.constant([[1,2,3],[4,5,6]])  # shape=(2,3)
a_stack = tf.stack([a] * 4)  # shape=(4,2,3)

sess = tf.Session()
print('original tensor:')
print(sess.run(a))
print('stacked tensor:')
print(sess.run(a_stack))

Tags:

Tensorflow