Maurizio Serra
Maurizio Serra

Reputation: 123

Multiplication between arrays of different shape in numpy

I am new on Python and I don't know exactly how to perform multiplication between arrays of different shape. I have two different arrays w and b such that:

W.shape = [32, 5, 20]
b.shape = [5,]

and I want to multiply

W[:, i, :]*b[i]

for each i from 0 to 4. How can I do that? Thanks in advance.

Upvotes: 1

Views: 59

Answers (2)

Daniel F
Daniel F

Reputation: 14399

What you want to do is called Broadcasting. In numpy, you can multiply this way, but only if the shapes match according to some restrictions:

Starting from the right, every component of each arrays' shape must be the equal, 1, or not exist

so right now you have:

W.shape = (32, 5, 20)
b.shape =        (5,)

since 20 and 5 don't match, they cant' be broadcast.

If you were to have:

W.shape = (32, 5, 20)
b.shape =     (5, 1 )

20 would match with 1 (1 is always ok) and the 5's would match, and you can then multiply them.

To get b's shape to (5, 1), you can either do .reshape(5, 1) (or, more robustly, .reshape(-1, 1)) or fancy index with [:, None]

Thus either of these work:

W * b[:,None] #yatu's answer
W * b.reshape(-1, 1)

Upvotes: 1

yatu
yatu

Reputation: 88226

You could add a new axis to b so it is multiplied accross W's inner arrays' rows, i.e the second axis:

W * b[:,None]

Upvotes: 2

Related Questions