NumPyでmatrixなら行列の積を*演算子で書けるしPython3.5以上なら@演算子で書ける
Pythonの数値計算ライブラリであるNumPyについて、2014年くらいからちゃんと調査せずに使っていたが、@
演算子で行列の積を計算できることを知って色々調べてみた。
そもそも、影響を受けてるはずのMATLABでも*
演算子は行列の積だし、C++のEigenでも*
演算子は行列の積なのに、何故NumPyだけ*
演算子が要素積なんだろう。
なお、NumPyのmatrixについて紹介するが、公式ドキュメントには以下のように書かれており、基本的には使うべきでないかもしれない。
It is no longer recommended to use this class, even for linear algebra. Instead use regular arrays. The class may be removed in the future.
numpy.matrix — NumPy v1.16 Manual
普通の積はnp.dot()
import numpy as np X = np.array([[0, 1], [2, 3]]) print(type(X)) # <class 'numpy.ndarray'> print(np.dot(X, X)) # [[ 2 3] # [ 6 11]] # メソッドでも可能 print(X.dot(X)) # [[ 2 3] # [ 6 11]]
matrixなら*
演算子で書ける
X_mat = np.matrix([[0, 1], [2, 3]]) print(type(X_mat)) # <class 'numpy.matrixlib.defmatrix.matrix'> print(X_mat * X_mat) # [[ 2 3] # [ 6 11]] # もちろんnp.dot()の可能 print(np.dot(X_mat, X_mat)) # [[ 2 3] # [ 6 11]]
Python3.5以上なら@
演算子で書ける
X = np.array([[0, 1], [2, 3]]) print(X @ X) # [[ 2 3] # [ 6 11]] X_mat = np.matrix([[0, 1], [2, 3]]) print(X_mat @ X_mat) # [[ 2 3] # [ 6 11]]