Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow: How to tile a tensor that duplicate in certain order? [duplicate]

For example, I have a tensor A = tf.Variable([a, b, c, d, e]) and through tf.tile(), it can give a tensor like [a, b, c, d, e, a, b, c, d, e]

But I want to reform A into something like: [a, a, b, b, c, c, d, d, e], where the elements are duplicated at the original place.

What is the most efficient way (less operations) to achieve that (through different-able ops)?

like image 533
Nathan Explosion Avatar asked Aug 13 '18 12:08

Nathan Explosion


People also ask

How do you stack the same tensor multiple times?

You can achieve that using tf. tile. You pass it a list of length equal to the number of dimensions in the tensor to be replicated. Each value in this list corresponds to how many times you want to replicate along the specific dimension.

How do you duplicate tensor in TensorFlow?

clone() function is used to create a copy of a tensor. The tf. clone() function creates a new tensor of the same shape and value of another tensor.

How do you split a tensor in keras?

Use Lambda to split a tensor of shape (64,16,16) into (64,1,1,256) and then subset any indexes you need.

How does TF tile work?

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


1 Answers

You can do it by adding a dimension, tiling along that dimension, and removing it:

import tensorflow as tf

A = tf.constant([1, 2, 3, 4, 5])

B = tf.expand_dims(A, axis=-1)
C = tf.tile(B, multiples=[1,2])
D = tf.reshape(C, shape=[-1])

with tf.Session() as sess:
    print('A:\n{}'.format(A.eval()))
    print('B:\n{}'.format(B.eval()))
    print('C:\n{}'.format(C.eval()))
    print('D:\n{}'.format(D.eval()))

gives

A:
[1 2 3 4 5]
B: # Add inner dimension
[[1]
 [2]
 [3]
 [4]
 [5]]
C: # Tile along inner dimension
[[1 1]
 [2 2]
 [3 3]
 [4 4]
 [5 5]]
D: # Remove innermost dimension
[1 1 2 2 3 3 4 4 5 5]

Edit: as pointed out in the comments, using tf.stack allows to specify the additional dimension on the go:

F = tf.stack([A, A], axis=1)
F = tf.reshape(F, shape=[-1])

with tf.Session() as sess:
    print(F.eval())

[1 1 2 2 3 3 4 4 5 5]
like image 155
sdcbr Avatar answered Sep 22 '22 02:09

sdcbr