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