Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replicate a row tensor using tf.tile?

Tags:

tensorflow

I have a tensor which is simply a vector, vector = [0.5 0.4] and tf.shape indicates that it has shape=(1,), I would like to replicate the vector m times and have the shape of [m, 2], so for m = 2, matrix = [[0.5 0.4], [0.5 0.4]]. How do I achieve that using tf.tile?

like image 330
Yang Avatar asked Jul 26 '17 00:07

Yang


People also ask

What does TF tile do?

The tf. tile() function is used to create a Tensor by repeating the number of times given by reps. Note: This function creates a new tensor by replicating the input reps times. For example, tiling [1, 2, 3, 4] by [3] produces [1, 2, 3, 4,1, 2, 3, 4,1, 2, 3, 4].

What does TF repeat do?

Returns. A Tensor which has the same shape as input , except along the given axis.

How do you transpose in Tensorflow?

transpose(x, perm=[1, 0]) . As above, simply calling tf. transpose will default to perm=[2,1,0] . To take the transpose of the matrices in dimension-0 (such as when you are transposing matrices where 0 is the batch dimension), you would set perm=[0,2,1] .


Video Answer


2 Answers

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)]
like image 189
amo-ej1 Avatar answered Sep 25 '22 00:09

amo-ej1


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.]]
like image 34
vijay m Avatar answered Sep 26 '22 00:09

vijay m