2

Suppose I have three arrays (that is, of type numpy.array):

>>> w.shape
(113,)
>>> X.shape
(113,1)
>>> Y.shape
(113,)

The numpy help pages suggest that on arrays every multiplication is element-wise. Since all above three vectors are of size 113 in the first dimension, I thought multiplication would in all cases give a 113 length vector, but it doesn't:

>>> (w * Y).shape     # expected
(113,)
>>> (w * X).shape     # ?!?!?!?!
(113,113)

Where does the 113 on the second axis come from? Doesn't look so element-wise to me.

2 Answers 2

3

When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when they are equal, or one of them is 1.

The smaller of two axes is stretched or “copied” to match the other.

Numpy's broadcasting rules are being applied here.

w      (1d array):       113
X      (2d array): 113 x   1   
Result (2d array): 113 x 113
Sign up to request clarification or add additional context in comments.

2 Comments

Aha, "starts with the trailing dimension"! Thanks.
If you want a (N,1) result for the multiplication of x (N,) with y (N,1), use x[:,None]*y to force broadcasting.
0

The easiest way to see what's going on is with an example:

w = array([5,6])
x = array([[1,2],[3,4]])
z = array([[5,6]])

w*x
# array([[ 5, 12],
#        [15, 24]])

w*z
# array([[25, 36]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.