1

我正在尝试在 numpy 中对两个向量进行矩阵乘法,这将产生一个数组。

例子

In [108]: b = array([[1],[2],[3],[4]])
In [109]: a =array([1,2,3])
In [111]: b.shape
Out[111]: (4, 1)
In [112]: a.shape
Out[112]: (3,)
In [113]: b.dot(a)
ValueError: objects are not aligned

从形状可以看出,数组 a 实际上不是矩阵。问题是这样定义的a

In [114]: a =array([[1,2,3]])    
In [115]: a.shape
Out[115]: (1, 3)    
In [116]: b.dot(a)
Out[116]: 
array([[ 1,  2,  3],
       [ 2,  4,  6],
       [ 3,  6,  9],
       [ 4,  8, 12]])

将向量作为矩阵的字段或列获取时如何获得相同的结果?

In [137]: mat = array([[ 1,  2,  3],
       [ 2,  4,  6],
       [ 3,  6,  9],
       [ 4,  8, 12]])

In [138]: x = mat[:,0]      #[1,2,3,4]
In [139]: y = mat[0,:]      #[1,2,3]
In [140]: x.dot(y)
ValueError: objects are not aligned
4

3 回答 3

6

您正在计算两个向量的外积。您可以为此使用该功能numpy.outer

In [18]: a 
Out[18]: array([1, 2, 3])

In [19]: b
Out[19]: array([10, 20, 30, 40])

In [20]: numpy.outer(b, a)
Out[20]: 
array([[ 10,  20,  30],
       [ 20,  40,  60],
       [ 30,  60,  90],
       [ 40,  80, 120]])
于 2013-04-29T19:51:20.940 回答
4

使用 2d 数组而不是 1d 向量并使用*...

In [8]: #your code from above

In [9]: y = mat[0:1,:]

In [10]: y
Out[10]: array([[1, 2, 3]])

In [11]: x = mat[:,0:1]

In [12]: x
Out[12]: 
array([[1],
       [2],
       [3],
       [4]])

In [13]: x*y
Out[13]: 
array([[ 1,  2,  3],
       [ 2,  4,  6],
       [ 3,  6,  9],
       [ 4,  8, 12]])
于 2013-04-29T09:08:05.317 回答
1

It's the similar catch as in the basic example.

Both x and y aren't perceived as matrices but as single dimensional arrays.

In [143]: x.shape
Out[143]: (4,)

In [144]: y.shape
Out[144]: (3,)

We have to add the second dimension to them, which will be 1.

In [171]: x = array([x]).transpose()
In [172]: x.shape
Out[172]: (4, 1)
In [173]: y = array([y])
In [174]: y.shape
Out[174]: (1, 3)
In [175]: x.dot(y)
Out[175]: 
array([[ 1,  2,  3],
       [ 2,  4,  6],
       [ 3,  6,  9],
       [ 4,  8, 12]])
于 2013-04-29T09:07:42.280 回答