Swap rows and columns of a 2-D tensor
Matrix manipulation
TensorFlow · Function
Transposes a Tensor by permuting its dimensions. By default, it reverses all dimensions; for complex64 or complex128 inputs, conjugate=True also applies complex conjugation.
The operation returns a tensor whose dimension at position i comes from the input dimension indexed by perm[i]. Without perm, TensorFlow reverses every dimension; conjugate=True additionally conjugates complex64 or complex128 values while transposing them.
tf.transpose(a, perm=None, conjugate=False, name='transpose')| Name | Type | Description |
|---|---|---|
a | Tensor | A Tensor. |
perm | Tensor or sequence of integers, default None | A vector that specifies a permutation of the dimensions of a. |
conjugate | bool, default False | If True, conjugates complex64 or complex128 values while transposing. |
name | string, default 'transpose' | Optional name for the operation. |
A transposed Tensor.
import tensorflow as tf
x = tf.constant([[1, 2, 3], [4, 5, 6]])
y = tf.transpose(x)
print(y.numpy())Reverses the two dimensions of a 2-D tensor, changing its shape from (2, 3) to (3, 2).
Matrix manipulation
Batch data layouts
Complex linear algebra
tf.transpose reorders tensor dimensions according to perm. Output dimension i corresponds to input dimension perm[i]; if perm is omitted, dimensions are reversed.
Follow-up: How would you transpose only the last two dimensions of a rank-3 tensor? Use perm=[0, 2, 1], preserving dimension 0 while swapping dimensions 1 and 2.
For a rank-n tensor, omitting perm uses the order (n-1,...,0). Thus a rank-2 matrix is transposed from shape (rows, columns) to (columns, rows).
Follow-up: What is the default permutation for a rank-4 tensor? It is [3, 2, 1, 0].
conjugate=True applies complex conjugation as part of the transpose when the input dtype is complex64 or complex128. For non-complex inputs, it does not add a meaningful conjugation step.
Follow-up: How can the same result be expressed explicitly? Apply tf.transpose first and then tf.math.conj to the result.
tf.math.conjtf.reshapetf.image.transpose