Paul
Paul

Reputation: 273

numpy array multiplication issue

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.

Upvotes: 2

Views: 145

Answers (2)

Andy Hayden
Andy Hayden

Reputation: 375915

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]])

Upvotes: 0

Anirudh Ramanathan
Anirudh Ramanathan

Reputation: 46788

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

Upvotes: 3

Related Questions