LoginSignup
1
0

More than 3 years have passed since last update.

【Python】行列演算

Last updated at Posted at 2020-04-22

機械学習を理解する過程で使った行列演算をまとめる。
随時更新します。

足し算

各要素ごとに和を取る。Pythonでは + 演算子で計算できる。

\begin{pmatrix}
1 & 2 \\
3 & 4
\end{pmatrix}
+
\begin{pmatrix}
5 & 6 \\
7 & 8
\end{pmatrix}
=
\begin{pmatrix}
6 & 8 \\
10 & 12
\end{pmatrix}
import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])

print(a+b)
[[ 6  8]
 [10 12]]

引き算

各要素ごとに差を取る。Pythonでは - 演算子で計算できる。

\begin{pmatrix}
1 & 2 \\
3 & 4
\end{pmatrix}
-
\begin{pmatrix}
5 & 6 \\
7 & 8
\end{pmatrix}
=
\begin{pmatrix}
-4 & -4 \\
-4 & -4
\end{pmatrix}
import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])

print(a-b)
[[-4 -4]
 [-4 -4]]

アダマール積(シューア積)

各要素ごとに積を取る。Pythonでは * 演算子で計算できる。

\begin{pmatrix}
1 & 2 \\
3 & 4
\end{pmatrix}
\odot
\begin{pmatrix}
5 & 6 \\
7 & 8
\end{pmatrix}
=
\begin{pmatrix}
5 & 12 \\
21 & 32
\end{pmatrix}
import numpy as np

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

print(A*B)
[[ 5 12]
 [21 32]]

対応する行と列の各要素を掛け合わせた和を取る。Pythonではdot関数で計算できる。
ただし、dot関数は内積を求める関数です。
引数に行列をとったときは結果として行列の積を得ます。

\begin{pmatrix}
1 & 2 \\
3 & 4
\end{pmatrix}
\begin{pmatrix}
5 & 6 \\
7 & 8
\end{pmatrix}
=
\begin{pmatrix}
19 & 22 \\
43 & 50
\end{pmatrix}
import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])

print(np.dot(a, b))
[[19 22]
 [43 50]]
1
0
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
0