Search code examples
pythonnumpynumpy-einsumeinops

Performing simple custom operations with Einsum


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?


Solution

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

    should do the trick for you.

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