Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using tf.tile to replicate a tensor N times

Tags:

tensorflow

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.]]]
like image 460
Yang Avatar asked Jul 10 '17 17:07

Yang


1 Answers

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])

like image 62
vijay m Avatar answered Oct 02 '22 00:10

vijay m