My current tensor has shape of (3, 2), e.g.,
[[ 1. 2.]
[ 2. 1.]
[-2. -1.]]
I would like to expand to a shape of (1, 3, 2) with each second dimension a replica of the entire tensor, e.g.,
[[[ 1. 2.]
[ 2. 1.]
[ -2. -1.]]
[[ 1. 2.]
[ 2. 1.]
[ -2. -1.]]
[[ 1. 2.]
[ 2. 1.]
[ -2. -1.]]]
I tried the folllowing code but it only replicate each row instead.
tiled_vecs = tf.tile(tf.expand_dims(input_vecs, 1), [1, 3, 1])
Results in
[[[ 1. 2.]
[ 1. 2.]
[ 1. 2.]]
[[ 2. 1.]
[ 2. 1.]
[ 2. 1.]]
[[-2. -1.]
[-2. -1.]
[-2. -1.]]]
This should work,
tf.ones([tf.shape(A)[0], 1, 1]) * A
# Achieved by creating a 3d matrix as shown below
# and multiplying it with A, which is `broadcast` to obtain the desired result.
[[[1.]],
[[1.]], * A
[[1.]]]
Code Sample:
#input
A = tf.constant([[ 1., 2.], [ 2. , 1.],[-2., -1.]])
B = tf.ones([tf.shape(A)[0], 1, 1]) * A
#output
array([[[ 1., 2.],
[ 2., 1.],
[-2., -1.]],
[[ 1., 2.],
[ 2., 1.],
[-2., -1.]],
[[ 1., 2.],
[ 2., 1.],
[-2., -1.]]], dtype=float32)
Also using tf.tile
, we can obtain the same:
tf.tile(tf.expand_dims(A,0), [tf.shape(A)[0], 1, 1])
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