高维矩阵指维度≥3的矩阵,或者叫张量。高维矩阵的乘法本质上还是二维矩阵之间的乘法,即把最后两个维度看成矩阵,执行二维矩阵乘法。
范例1:M1的shape为 (c,n,s), M2的shape为(c,s,m)时,M3的shape为(c,n,m)。
结果shape的计算过程:M1的后两维shape为(n,s), M2的后两维shape为(s,m),类似于二维矩阵乘法所得结果的M3后两维shape为(n,m), 高维度的尺寸取c。Python范例代码如下:
import numpy as np
M1 = np.array([[j*4+i for i in range(2)] for j in range(3)])
M1_3D = np.array([M1,M1,M1,M1])
M2 = np.ones((2,3))
M2_3D = np.array([M2,M2,M2,M2])
M3_3D = np.matmul(M1_3D,M2_3D)
print(f"M1_3D shape:{M1_3D.shape}, M2_3D shape:{M2_3D.shape}, M3_3D shape:{M3_3D.shape}")
M1_3D shape:(4, 3, 2), M2_3D shape:(4, 2, 3), M3_3D shape:(4, 3, 3)
范例2:M1的shape为 (n,c,h,s), M2的shape为(1,1,s,w)时,M3的shape为(n,c,h,w)。
结果M3的shape的计算过程:M1的后两维shape为(h,s), M2的后两维shape为(s,w),类似于二维矩阵乘法所得结果的M3后两维shape为(h,w), 高维度的尺寸取(n,c)和(1,1)中尺寸较大值(n,c)。Python范例代码如下:
import numpy as np
M1 = np.array([[j*4+i for i in range(2)] for j in range(3)])
M1_4D = np.array([M1,M1,M1,M1,M1,M1]).reshape(2,3,3,2)
M2_4D = np.ones((1,1,2,3))
M3_4D = np.matmul(M1_4D,M2_4D)
print(f"M1_4D shape:{M1_4D.shape}, M2_4D shape:{M2_4D.shape}, M3_4D shape:{M3_4D.shape}")
M1_4D shape:(2, 3, 3, 2), M2_4D shape:(1, 1, 2, 3), M3_4D shape:(2, 3, 3, 3)
网友评论