The *
operator depends on the data type. On Numpy arrays it does an element-wise multiplication (not the matrix multiplication); numpy.vdot()
does the "dot" scalar product of two vectors (which returns a simple scalar result)
>>> import numpy as np
>>> x = np.array([[1,2,3]])
>>> np.vdot(x, x)
14
>>> x * x
array([[1, 4, 9]])
To multiply 2 arrays as matrices properly, use numpy.dot
:
>>> np.dot(x, x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: objects are not aligned
>>> np.dot(x.T, x)
array([[ 1, 4, 9],
[ 4, 16, 36],
[ 9, 36, 81]])
>>> np.dot(x, x.T)
array([[98]])
Then there is numpy.matrix
, a specialization of array for which the *
means matrix multiplication, and **
means matrix power; so be sure to know what datatype you are operating on.
The upcoming Python 3.5 will have a new operator @
that can be used for matrix multiplication; then you could write x @ x.T
to replace the code in the last example.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…