Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy - multiple 3d array with a 2d array

I'm trying the following:

Given a matrix A (x, y ,3) and another matrix B (3, 3), I would like to return a (x, y, 3) matrix in which the 3rd dimension of A is multiplied by the values of B (similar when an RGB image is transformed into gray, only that those "RGB" values are multiplied by a matrix and not scalars)...

Here's what I've tried:

np.multiply(B, A)
np.einsum('ijk,jl->ilk', B, A)
np.einsum('ijk,jl->ilk', A, B)

All of them failed with dimensions not aligned.

What am I missing?

like image 339
DanielY Avatar asked Mar 08 '23 18:03

DanielY


1 Answers

You can use np.tensordot -

np.tensordot(A,B,axes=((2),(1)))

Related post to understand tensordot.

einsum equivalent would be -

np.einsum('ijk,lk->ijl', A, B)

We can also use A.dot(B.T), but that would be looping under the hoods. So, might not be the most preferred one, but it's a compact solution,

like image 139
Divakar Avatar answered Mar 20 '23 22:03

Divakar