TensorFlow——多维矩阵的转置(transpose):
https://blog.youkuaiyun.com/qq_37174526/article/details/80905693
这一篇写得相当清楚。
我额外添加一些对参数perm的理解:
这是官方文档里的描述,简单的翻译:
转置矩阵a根据参数perm对矩阵维数进行调整。
返回的张量的维数i将对应于输入维数perm[i]
。如果没有指定perm,默认为(n-1…0),其中n是输入张量的秩。因此,默认情况下,这个操作对二维输入张量执行一个常规矩阵转置。如果共轭(conjugate)为true,a.dtype可以是complex64,也可以是complex128,然后对a的值进行共轭和转置。
在numpy转置中,@compatibility(numpy)是一种内存效率高的常量时间操作,因为它们只是用调整后的步长返回相同数据的新视图。张量流不支持大步,因此转置返回一个新的张量,其中的项被置换。@end_compatibility
perm[i]内放的是转置后的新张量的轴相对于旧张量的改变,也就是你想要的改变。
初始情况下,n维张量中轴的排列为[0,1,2,3,…,n-1]
例如:一个二维张量x,初始情况下轴的排列为(0,1)
[
[1, 2, 3],
[4, 5, 6]
]
perm=[1, 0]
,意味着新矩阵中 [轴0变为轴1,轴1变为轴0].
x = tf.constant([[1, 2, 3], [4, 5, 6]]) tf.transpose(x)
#[[1, 4]#[2, 5] # [3, 6]]
Equivalently(相当于):
tf.transpose(x, perm=[1, 0])
#[[1, 4]
# [2, 5] # [3, 6]]
我在实际中遇到的例子:
>>>X=tf.constant(housing_data_plus_bias,dtype=tf.float32,name="X")
>>>y=tf.constant(housing.target.reshape(-1,1),dtype=tf.float32,name="y")
>>>print(X.shape)
(20640, 9)
>>>XT=tf.transpose(X)#张量转置
>>>print(XT)
Tensor("transpose:0", shape=(9, 20640), dtype=float32)