在numpy.linalg模块中,这个矩阵/向量点乘法怎么可能?

时间:2014-01-12 13:45:45

标签: python numpy scipy

以下代码......

>>> A
array([[1, 2],
       [3, 4]])
>>> b
array([5, 6])
>>> A.dot(b)   # <------- this is not possible in math
array([17, 39]) # <------ and the result should be 2x1 matrix instead of 1x2 matrix.
>>> A.dot(b.T) # <------- this is a bit better
array([17, 39]) # <------ but the result is still not well formed. 
>>> 

2 个答案:

答案 0 :(得分:3)

如果您使用np.ndarray来存储数据而不是matrix,那么numpy总是打算将数据存储在最小维度中(不记得文档所说的位置) 。这就是b.T没有改变的原因:

In [136]: b
Out[136]: array([5, 6])

In [137]: b.T
Out[137]: array([5, 6])

In [138]: b.T.shape
Out[138]: (2,)

In [139]: b.shape
Out[139]: (2,)

如果您希望b.shape成为(2,1),请使用np.newaxisNone对其进行切片:

In [140]: bb=b[:,None]

In [141]: bb
Out[141]: 
array([[5],
       [6]])

In [142]: bb.shape
Out[142]: (2, 1)

然后一切看起来都是正确的:

In [143]: a.dot(bb)
Out[143]: 
array([[17],
       [39]])

In [144]: a.dot(bb).shape
Out[144]: (2, 1)

此链接可能有所帮助:python-numpy-transpose

答案 1 :(得分:1)

您需要使用numpy.matrix才能获得正确的矩阵数学行为:

In [2]: import numpy

In [3]: A = numpy.matrix('[1 2; 3 4]')

In [4]: A
Out[4]: 
matrix([[1, 2],
        [3, 4]])

In [5]: b = numpy.matrix('[5 6]')

In [6]: b
Out[6]: matrix([[5, 6]])

In [7]: A.dot(b)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-2a3d67ed3e0f> in <module>()
----> 1 A.dot(b)

ValueError: objects are not aligned

In [8]: A.dot(b.transpose())
Out[8]: 
matrix([[17],
        [39]])

您还将获得numpy.matrix的重载乘法运算符:

In [9]: A * b
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-9-e4962082e335> in <module>()
----> 1 A * b

/usr/lib64/python2.7/site-packages/numpy/matrixlib/defmatrix.pyc in __mul__(self, other)
    339         if isinstance(other, (N.ndarray, list, tuple)) :
    340             # This promotes 1-D vectors to row vectors
--> 341             return N.dot(self, asmatrix(other))
    342         if isscalar(other) or not hasattr(other, '__rmul__') :
    343             return N.dot(self, other)

ValueError: objects are not aligned

In [10]: A * b.transpose()
Out[10]: 
matrix([[17],
        [39]])

另请参阅:http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html#numpy.matrix