简体   繁体   中英

Dot product with shapes (x) and (x, y)

I am really new to numpy, so I am having some troubles understanding the dot product.

I have this simple piece of code:

import numpy as np

A = np.ones((5))
B = np.ones((5,10))

A.dot(B)
# array([ 5.,  5.,  5.,  5.,  5.,  5.,  5.,  5.,  5.,  5.])

A.dot(B).shape
# (10,)

I cannot understand what is happening in this code. I am a little confused, because it seems that a shape of (10,) is not a column vector, because the transpose is the same.

Is A being broadcasted? I thought that A should be broadcasted to the shape of (5,5) , so it could be multiplied with B and thus returning an array of shape (5,10) . What am I getting wrong?

Numpy makes a difference between 1d arrays (something of shape (N,) ) and an 2d array (matrix) with one column (shape (N, 1) ) or one row (shape (1, N) aka column- or row-vectors.

>>> a = np.ones((5, 1))
>>> B = np.ones((5, 5))
>>> B.dot(a)
array([[ 5.],
       [ 5.],
       [ 5.],
       [ 5.],
       [ 5.]])

Or unsing python 3.5 with numpy 1.10:

>>> a = np.ones((5, 1))
>>> B = np.ones((5, 5))
>>> B @ a
array([[ 5.],
       [ 5.],
       [ 5.],
       [ 5.],
       [ 5.]])

If you have a 1d array, you can use np.newaxis to make it a row or column vector:

>>> a = np.ones(5)
>>> B = np.ones((5, 5))
>>> B @ a[:, np.newaxis]
array([[ 5.],
       [ 5.],
       [ 5.],
       [ 5.],
       [ 5.]])

Both new row and column:

>>> x = np.arange(5)
>>> B = x[:, np.newaxis] @ x[np.newaxis, :]
>>> B
array([[ 0,  0,  0,  0,  0],
       [ 0,  1,  2,  3,  4],
       [ 0,  2,  4,  6,  8],
       [ 0,  3,  6,  9, 12],
       [ 0,  4,  8, 12, 16]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM