Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I swap tensor's axes in TensorFlow?

I have a tensor of shape (30, 116, 10), and I want to swap the first two dimensions, so that I have a tensor of shape (116, 30, 10)

I saw that numpy as such a function implemented (np.swapaxes) and I searched for something similar in tensorflow but I found nothing.

Do you have any idea?

like image 635
Alexis Rosuel Avatar asked Jul 05 '16 20:07

Alexis Rosuel


People also ask

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

How do I change the value of a tensor in Tensorflow?

Yet, it seems not possible in the current version of Tensorflow. An alternative way is changing tensor to ndarray for the process, and then use tf. convert_to_tensor to change back. The key is how to change tensor to ndarray .


2 Answers

tf.transpose provides the same functionality as np.swapaxes, although in a more generalized form. In your case, you can do tf.transpose(orig_tensor, [1, 0, 2]) which would be equivalent to np.swapaxes(orig_np_array, 0, 1).

like image 143
keveman Avatar answered Sep 29 '22 10:09

keveman


It is possible to use tf.einsum to swap axes if the number of input dimensions is unknown. For example:

  • tf.einsum("ij...->ji...", input) will swap the first two dimensions of input;
  • tf.einsum("...ij->...ji", input) will swap the last two dimensions;
  • tf.einsum("aij...->aji...", input) will swap the second and the third dimension;
  • tf.einsum("ijk...->kij...", input) will permute the first three dimensions;

and so on.

like image 42
ltskv Avatar answered Sep 29 '22 10:09

ltskv