NumPy行列の乗算
NumPyの行列乗算は、次の3つの方法で行うことができます。
- multiply(): 要素ごとの行列の掛け算。
- matmul(): 二つの配列の行列積。
- ドット(): 2つの配列のドット積。
1. NumPy行列の要素ごとの乗算
要素ごとの行列乗算が必要な場合は、multiply() 関数を使用できます。
import numpy as np
arr1 = np.array([[1, 2],
[3, 4]])
arr2 = np.array([[5, 6],
[7, 8]])
arr_result = np.multiply(arr1, arr2)
print(arr_result)
出力 :
[[ 5 12]
[21 32]]
下の画像は、結果行列を得るために行われた乗算操作を示しています。
2. 2つのNumPy配列の行列積
2つの配列の行列積が欲しい場合は、matmul()関数を使用してください。
import numpy as np
arr1 = np.array([[1, 2],
[3, 4]])
arr2 = np.array([[5, 6],
[7, 8]])
arr_result = np.matmul(arr1, arr2)
print(f'Matrix Product of arr1 and arr2 is:\n{arr_result}')
arr_result = np.matmul(arr2, arr1)
print(f'Matrix Product of arr2 and arr1 is:\n{arr_result}')
出力 :
Matrix Product of arr1 and arr2 is:
[[19 22]
[43 50]]
Matrix Product of arr2 and arr1 is:
[[23 34]
[31 46]]
下の図は、結果配列の各インデックスに対する行列積演算を説明しています。簡単にするために、最初の配列から行を取り、第二の配列から列を取り出します。それから、対応する要素を掛け合わせて、それらを足して行列積の値を求めます。
二つの配列の行列積は引数の位置によって異なります。したがって、matmul(A, B)はmatmul(B, A)とは異なるかもしれません。
3. 2つのNumPy配列のドット積
numpyのdot()関数は、2つの配列のドット積を返します。その結果は、1次元および2次元配列に対してmatmul()関数と同じです。
import numpy as np
arr1 = np.array([[1, 2],
[3, 4]])
arr2 = np.array([[5, 6],
[7, 8]])
arr_result = np.dot(arr1, arr2)
print(f'Dot Product of arr1 and arr2 is:\n{arr_result}')
arr_result = np.dot(arr2, arr1)
print(f'Dot Product of arr2 and arr1 is:\n{arr_result}')
arr_result = np.dot([1, 2], [5, 6])
print(f'Dot Product of two 1-D arrays is:\n{arr_result}')
出力 :
Dot Product of arr1 and arr2 is:
[[19 22]
[43 50]]
Dot Product of arr2 and arr1 is:
[[23 34]
[31 46]]
Dot Product of two 1-D arrays is:
17
おすすめの読書:
- numpy.square()
- NumPy sqrt() – 行列要素の平方根
- Python NumPy チュートリアル
参考文献
- numpyのmatmul()
- numpy multiply()


