二维矩阵的转置很简单,元素的i,j坐标交换就行。多为矩阵的转换复杂,遵循什么规律呢?
先看看代码:
import tensorflow as tf
import numpy as np
print("二维矩阵的转置\n")
t=[[1,2,3],[4,5,6]]
t1=tf.transpose(t)
t2=tf.transpose(t,[0,1])#[0,1]是正常的坐标轴排列顺序,运行结果不转置
t3=tf.transpose(t,[1,0])
sess=tf.Session()
print("Default Transepose is:\n",sess.run(t1),"\n[0,1] Tranpose is:\n",sess.run(t2),"\n[1,0] Tranpose is:\n",sess.run(t3))
print("三维矩阵的转置")
t=[[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]#这个三维矩阵有两张表格,每个表格都是2行3列
print("先测试不带perm参数的默认转置和参数顺序为不转置的正常坐标轴顺序[0,1,2]转置结果")
t1=tf.transpose(t)
t2=tf.transpose(t,[0,1,2])
print(sess.run(t1))
print(sess.run(t2))
代码输出如下:
二维矩阵的转置
Default Transepose is:
[[1 4]
[2 5]
[3 6]]
[0,1] Tranpose is:
[[1 2 3]
[4 5 6]]
[1,0] Tranpose is:
[[1 4]
[2 5]
[3 6]]
三维矩阵的转置
先测试不带perm参数的默认转置和参数顺序为不转置的正常坐标轴顺序[0,1,2]转置结果
[[[ 1 7]
[ 4 10]]
[[ 2 8]
[ 5 11]]
[[ 3 9]
[ 6 12]]]
这里分析一下元素的坐标在转换前和转换后的变化:
1:(0,0,0)==>(0,0,0)
2:(0,0,1)==>(1,0,0)
3:(0,0,2)==>(2,0,0)
4:(0,1,0)==>(0,1,0)
5:(0,1,1)==>(1,1,0)
6:(0,1,2)==>(2,1,0)
7:(1,0,0)==>(0,0,1)
8:(1,0,1)==>(1,0,1)
9:(1,0,2)==>(2,0,1)
10:(1,1,0)==>(0,1,1)
11:(1,1,1)==>(1,1,1)
12:(1,1,2)==>(2,1,1)
从结果看出,元素的转置结果是下表数组以中心位置,对称交换,和二维矩阵原理相同。所以,默认不带参数的三维矩阵转换,其实默认的转换perm是(2,1,0),可以代码验证
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
Comments
Post a Comment