TensorFlow中张量转置操作tf.transpose用法

一、环境

TensorFlow API r1.12

CUDA 9.2 V9.2.148

cudnn64_7.dll

Python 3.6.3

Windows 10

二、官方说明

对张量按照指定的排列维度进行转置

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

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值