1

I have two numy matrices :

  1. A with shape (N,M,d)
  2. B with shape (N,d)

So, I am trying to get a Matrix with shape (N,M,d) in such manner that I do element wise product between B and each element of A (which are M elements). I used numpy's einsum as follows :

product = np.einsum('ijk,ik->ijk', A, B) 

I GET THE GOOD shape but I suspect that the operation is wrong and that I am not doing element wise product as intended.

Is my use of einsum correct ?

3
  • You can test this in about 2 seconds with a pair of toy matrices. Voting to close because you didn't look at the data. Commented Apr 10, 2021 at 1:58
  • Also, use A * B[:, None, :] if you're not sure. Commented Apr 10, 2021 at 1:59
  • @MadPhysicist, made the same edit to my answer as well at the same time. Commented Apr 10, 2021 at 2:02

1 Answer 1

4

I am trying to get a Matrix with shape (N,M,d) in such manner that I do element wise product between B and each element of A (which are M elements).

The operation you are trying to perform is a broadcasted element wise product over axis = 1 of A (M size) -

C1 = A * B[:,None,:]

You can always do a quick test to check whether what you are expecting, as your result, is actually what you have implemented.

A = np.random.randint(0,5,(2,3,1)) # N,M,d
B = np.random.randint(0,5,(1,1))   # N,d

C2 = np.einsum('ijk,ik->ijk', A, B)
print(C2)
[[[4]
  [0]
  [8]]

 [[4]
  [4]
  [4]]]

To double check whether both operations are equal =

np.allclose(C1, C2)

##True

More details on how np.einsum works can be found here.

Sign up to request clarification or add additional context in comments.

6 Comments

Ok ! Thanks ! I am implementing an algorithm but the results are bit off so I suspected this operation. However, the fact that B have a shape (1,1) might be not be so representative in case the einsum does some kind of sum,.I will test with shape (2,2)
BTW, You dont need to use np.einsum here. I have updated my answer to use straighforward broadcasting.
Do mark the answer if it helped you and do upvote it if it’s well written to your liking. This encourages me to help solve your future questions :)
This is a new account on stackoverflow, I did upvote you it didn't get accounted ! Thanks very much
all good, you would need some reputation before that :) feel free to mark the answer as correct if it solved your problem. You can do that by clicking the tick mark right under the upvote and downvote buttons of the answer.
|

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.