1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【線形代数】行列の乗法(積) in Python

Last updated at Posted at 2021-10-12

機械学習では線形代数がよく使われています。
その中で、自分が間違えたことある行列の乗法について話したいと思います。

1. アダマール積 (Hadamard product)

また要素ごとの積 (element-wise product)と呼ばれています。
同じサイズの行列$A$と行列$B$のアダマール積は$A\odot B$と書きます。

A=\begin{bmatrix}
  3&4\\ 
  5&6
\end{bmatrix},  
B=\begin{bmatrix}
  1&2 \\ 
  3&4
\end{bmatrix}
A\odot B=
\begin{bmatrix}
  3*1&4*2 \\ 
  5*3&6*4
\end{bmatrix}=
\begin{bmatrix}
  3&8 \\ 
  15&24
\end{bmatrix}

numpy

import numpy as np

A = np.array([[3, 4], [5, 6]])
B = np.array([[1, 2], [3, 4]])

print(A * B)
"""
[[ 3  8]
 [15 24]]
"""

pytorch

import torch

A_pt = torch.tensor([[3, 4], [5, 6]])
B_pt = torch.tensor([[1, 2], [3, 4]])

print((A_pt * B_pt))
"""
tensor([[ 3,  8],
        [15, 24]])
"""

2. 通常の行列の積 (dot product)

サイズ$n×m$の行列$A$とサイズ$m×k$の行列$B$を計算する時に

  1. $A\cdot B$
  2. $\lt A, B\gt$
  3. $\sum_{i=1}^{n} a_ib_i$

などの書き方があります。

A=\begin{bmatrix}
  3&4 \\ 
  5&6
\end{bmatrix},  
B=\begin{bmatrix}
  1&2 \\ 
  3&4
\end{bmatrix}
A\cdot B=
\begin{bmatrix}
  3*1+4*3&3*2+4*4 \\ 
  5*1+6*3&5*2+6*4
\end{bmatrix}=
\begin{bmatrix}
  15&22 \\ 
  23&34
\end{bmatrix}

numpy

import numpy as np

A = np.array([[3, 4], [5, 6]])
B = np.array([[1, 2], [3, 4]])

print(np.dot(A, B))
"""
[[15 22]
 [23 34]]
"""

pytorch

import torch

A_pt = torch.tensor([[3, 4], [5, 6]])
B_pt = torch.tensor([[1, 2], [3, 4]])

# print(torch.mm(A_pt, B_pt))も一緒です
print(torch.matmul(A_pt, B_pt))
"""
tensor([[15, 22],
        [23, 34]])
"""

以上、簡単にメモしました。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?