一、环境
TensorFlow API r1.12
CUDA 9.2 V9.2.148
Python 3.6.3
二、官方说明
对张量按照指定的排列维度进行转置
tf.transpose(
a,
perm=None,
name='transpose',
conjugate=False
)
输入:
(1)a:输入张量
(2)perm:输入张量要进行转置操作的维度的排列方式
(3)name:可选参数,转置操作的名称
(4)conjugate:可选参数,布尔类型,如果设置为True,则数学意义上等同于tf.conj(tf.transpose(input))
输出:
(1)按照指定维度排列方式转置后的张量
三、实例
(1)不设置perm参数值时,perm默认为(n-1, n-2, ..., 2, 1, 0),其中n为输入张量的阶(rank)
>>> x = tf.constant([[1,2,3],[4,5,6]])
>>> with tf.Session() as sess:
... print(sess.run(tf.transpose(x)))
... print(sess.run(tf.shape(tf.transpose(x))))
...
[[1 4]
[2 5]
[3 6]]
...
[3 2]
(2)上例中等同实例(张量x的阶为2,因此perm默认为(2-1,0))
>>> x = tf.constant([[1,2,3],[4,5,6]])
>>> with tf.Session() as sess:
... print(sess.run(tf.transpose(x,[1,0])))
... print(sess.run(tf.shape(tf.transpose(x))))
...
[[1 4]
[2 5]
[3 6]]
...
[3 2]
(3)输入张量为复数的情况,参数conjugate=True时,进行共轭转置操作
>>> real = [[1.0,2.0,3.0],[4.0,5.0,6.0]]
>>> imag = [[1.0,2.0,3.0],[4.0,5.0,6.0]]
>>> complex = tf.complex(real,imag)
>>> with tf.Session() as sess:
... print(sess.run(complex))
... print(sess.run(tf.shape(complex)))
... print(sess.run(tf.transpose(complex)))
... print(sess.run(tf.shape(tf.transpose(complex))))
... print(sess.run(tf.transpose(complex,conjugate=True)))
... print(sess.run(tf.shape(tf.transpose(complex,conjugate=True))))
...
[[1.+1.j 2.+2.j 3.+3.j]
[4.+4.j 5.+5.j 6.+6.j]]
...
[2 3]
...
[[1.+1.j 4.+4.j]
[2.+2.j 5.+5.j]
[3.+3.j 6.+6.j]]
...
[3 2]
...
[[1.-1.j 4.-4.j]
[2.-2.j 5.-5.j]
[3.-3.j 6.-6.j]]
...
[3 2]
...
(4)输入张量的维度大于2时,参数perm起作用更大
直观来讲,这里的参数perm=[0,2,1],控制将原来的维度[0,1,2]后面两列置换位置
>>> x = tf.constant([[[ 1, 2, 3],
... [ 4, 5, 6]],
... [[ 7, 8, 9],
... [10, 11, 12]]])
>>> with tf.Session() as sess:
... print(sess.run(tf.transpose(x,[0,2,1])))
...
[[[ 1 4]
[ 2 5]
[ 3 6]]
[[ 7 10]
[ 8 11]
[ 9 12]]]