1

I am new to Einsum and wanted a particular case - using einsum for multiplying all elements of a matrix with each other; say given a 2D matrix:-

np.random.rand((16,2))

Multiplying elements across an axis obtaining (16,) and then multiplying those with each other again to obtain (1,) a scalar. This is something like:-

[[1, 2],  ==> [2, 12] ==> 24
 [3, 4]]

I tried using stuff like:-

...("ij->")

But that's definitely not what I want, as its not multiplication

How can we write such simple operations with einsum? can einsum not handle every single operation, but is optimized for a few hard cases?

neel g
  • 1,138
  • 1
  • 11
  • 25
  • 2
    `einsum` is primarily a matrix multiplication tool. That is, it performs the typical `sum-of-products`, with a lot of control over which axes are summed and which pass through. It is not a general purpose multiplier. It can sum within one array, but the multiplication is between arrays. – hpaulj Dec 16 '21 at 21:31
  • 'ij->i' is a summation over the `j`, 2nd axis. – hpaulj Dec 16 '21 at 21:33
  • I'm trying to understand what your goal is here. If we had the example matrix [[1,2],[3,4]], then what should the result of this operation be? – Ben Grossmann Dec 16 '21 at 21:35
  • @BenGrossmann Something like, `[[1*2],[3*4]]` ==> `[[2],[12]]` ==> `12*2 = 24` Which would be the final result - just multiplication instead of addition. I have edited my question to include the same – neel g Dec 16 '21 at 22:17
  • 1
    As mentioned above `einsum` performs *sum-of-producs*. If I understood you correctly a simple `.prod()` operation on the numpy array would do the job. The order of the axis doesn't even matter here. – Tinu Dec 16 '21 at 22:35
  • Indeed, I agree its a much simpler and readable way; however, the entire point of this post was do arbitrary ops with `einsum` instead since I would love to gain a mastery of it for future use. I was surprised that there is no way to accomplish this - so perhaps `einsum` is not as versatile a tool as I thought. – neel g Dec 16 '21 at 23:21

1 Answers1

1
einops.reduce(x, 'i j -> i', 'prod')

should do the trick for you.

As @neel-g pointed, einsum is sum-of-products by definition.

Alleo
  • 7,891
  • 2
  • 40
  • 30
  • that's brilliant - is there some detailed documentation (apart from the repo) that explains all these ops in-depth? because I don't see any good resources (like a cheatsheet) for beginners to start adopting einops :) and posting a S.O question every time I want to accomplish something seems like a bad idea – neel g Jan 04 '22 at 02:03
  • I think tutorial in the repository is a way to start. No, there is no cheatsheet AFAIK. – Alleo Jan 04 '22 at 18:29