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?
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].
Returns. A Tensor which has the same shape as input , except along the given axis.
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] .
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.]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With