Pytorch torch.mul() 和 torch.mm() 的区别
torch.mul()
矩阵点乘:要求进行运算的两矩阵维度相同。这里用3×3矩阵来举例说明。
A
=
[
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
]
B
=
[
b
11
b
12
b
13
b
21
b
22
b
23
b
31
b
32
b
33
]
A=\left[ \begin{matrix} a_{11} & a_{12} & a_{13}\\ a_{21} & a_{22} & a_{23}\\ a_{31} & a_{32} & a_{33}\end{matrix} \right] \\ B = \left[ \begin{matrix} b_{11} & b_{12} & b_{13}\\ b_{21} & b_{22} & b_{23}\\ b_{31} & b_{32} & b_{33}\end{matrix} \right]
A=⎣⎡a11a21a31a12a22a32a13a23a33⎦⎤B=⎣⎡b11b21b31b12b22b32b13b23b33⎦⎤
两者点乘的结果为
C
=
[
a
11
∗
b
11
a
12
∗
b
12
a
13
∗
b
13
a
21
∗
b
21
a
22
∗
b
22
a
23
∗
b
23
a
31
∗
b
31
a
32
∗
b
32
a
33
∗
b
33
]
C = \left[ \begin{matrix} a_{11}*b_{11} & a_{12}*b_{12} & a_{13}*b_{13}\\ a_{21}*b_{21} & a_{22}*b_{22} & a_{23}*b_{23}\\ a_{31}*b_{31} & a_{32}*b_{32} & a_{33}*b_{33}\end{matrix} \right]
C=⎣⎡a11∗b11a21∗b21a31∗b31a12∗b12a22∗b22a32∗b32a13∗b13a23∗b23a33∗b33⎦⎤
代码实现如下:
A = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
B = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
torch.mul(torch.tensor(A), torch.tensor(B))
结果如下:
torch.mm()
矩阵相乘:要求进行运算的两矩阵维度相同。这里用3×3矩阵来举例说明。
A
=
[
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
]
B
=
[
b
11
b
12
b
13
b
21
b
22
b
23
b
31
b
32
b
33
]
A=\left[ \begin{matrix} a_{11} & a_{12} & a_{13}\\ a_{21} & a_{22} & a_{23}\\ a_{31} & a_{32} & a_{33}\end{matrix} \right] \\ B = \left[ \begin{matrix} b_{11} & b_{12} & b_{13}\\ b_{21} & b_{22} & b_{23}\\ b_{31} & b_{32} & b_{33}\end{matrix} \right]
A=⎣⎡a11a21a31a12a22a32a13a23a33⎦⎤B=⎣⎡b11b21b31b12b22b32b13b23b33⎦⎤
两者相乘的结果为
C
=
[
c
11
c
12
c
13
c
21
c
22
c
23
c
31
c
32
c
33
]
C = \left[ \begin{matrix} c_{11} & c_{12} & c_{13}\\ c_{21} & c_{22} & c_{23}\\ c_{31} & c_{32} & c_{33}\end{matrix} \right]
C=⎣⎡c11c21c31c12c22c32c13c23c33⎦⎤
c i j = ∑ k = 1 3 a i k b k j c_{ij} = \sum_{k=1}^{3}a_{ik}b_{kj} cij=k=1∑3aikbkj
代码实现如下:
A = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
B = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
torch.mm(torch.tensor(A), torch.tensor(B))
结果如下: