Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.dot how to calculate 1-D array with 2-D array

The numpy.dot docstring says:

For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of a and the second-to-last of b

But it doesn't illustrate how numpy.dot calculate 1-D array with 2-D array.So how does Numpy handle 1-D array(vector) with 2-D array(matrix)?

I have make some test:

In [27]: a
Out[27]: 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

In [28]: b
Out[28]: array([0, 1, 2])

In [29]: np.dot(a,b)
Out[29]: array([ 5, 14, 23])

In [30]: np.dot(a, b.reshape(-1,1))
Out[30]: 
array([[ 5],
       [14],
       [23]])

In [31]: np.dot(a, b.reshape(-1,1)).ravel() # same as np.dot(a,b)
Out[31]: array([ 5, 14, 23])

In [32]: np.dot(b,a)
Out[32]: array([15, 18, 21])

In [33]: np.dot(b.reshape(1,-1), a)
Out[33]: array([[15, 18, 21]])

In [34]: np.dot(b.reshape(1,-1), a).ravel() # same as np.dot(b,a)
Out[34]: array([15, 18, 21])

The above tests indecate that numpy.dot can handle 1-D array with 2-D array. Is it right?

like image 763
Honghe.Wu Avatar asked Nov 21 '13 12:11

Honghe.Wu


2 Answers

A 1-d array and a 2-d array are handled as a matrix-vector (or vector-matrix) product. The implementation in fact uses the BLAS *gemv functions to handle this case for floating-point inputs.

like image 76
Fred Foo Avatar answered Sep 29 '22 12:09

Fred Foo


There's only one case not explicitly described in the documentation, but kind of hinted, which is how to apply to a 2D and a 1D inputs the rule:

it is a sum product over the last axis of a and the second-to-last of b

In your case, when you do np.dot(a, b), there is no "second-to-last" axis of b. What numpy does then, is to settle for the last. So it does the sum product of every row of a with b, as your test readily shows.

All of your other examples fit into the above rule.

like image 23
Jaime Avatar answered Sep 29 '22 10:09

Jaime