0

I'm experimenting with np.einsum and I was wondering if there's a way to prove Associativity just using np.einsum.

Here's the data:

A = np.array([[1, 1, 1],
              [2, 2, 2],
              [5, 5, 5]])

B = np.array([[0, 1, 0],
              [1, 1, 0],
              [1, 1, 1]])

C = np.array([[ 6,  4,  2],
              [-2,  0,  2],
              [ 3,  2,  1]])

Here's what I have tried:

D = np.einsum('il, lj', A, B).dot(C)

E = A.dot(np.einsum('il, lj', B, C))

(D == E).all() # True

Is it possible (and best?) to compute D and E respectively in one np.einsum operation? A lot of the examples I can find use two matrices, but I know it's possible to multiply multiple matrices together using np.einsum from this post np.einsum performance of 4 matrix multiplications, I just can't seem to figure out how that post relates to what I want to achieve. Thanks:)

Martin H
  • 155
  • 2
  • 3
  • 14
  • 2
    With `einsum` you will write `np.einsum("il, lj, jk", A, B, C)` for both `D` and `E`, and letting numpy choose the path of computation, so not sure how you'll ends up "proving" associativity. – paime Jul 21 '22 at 16:09
  • 1
    OK, maybe it's just not possible to stipulate the order of operations, in terms of which matrices are computed first. – Martin H Jul 21 '22 at 16:13
  • 3
    Yes it is, see [`numpy.einsum_path`](https://numpy.org/doc/stable/reference/generated/numpy.einsum_path.html#numpy.einsum_path), but then why not just using `dot`? – paime Jul 21 '22 at 16:35
  • That's a good question, I guess dot is sufficient, I was just interested in what np.einsum was capable of. OK, great I will checkout np.einsum_path. – Martin H Jul 21 '22 at 16:52
  • 2
    You can nest ensums, same as if you did dots: `np.einsum('il,lj', np.einsum('il, lj', A, B),C)`. Or with the matmul operator `A@B@C` with optional (). `allclose` is a better way of comparing results, especially if using floats. – hpaulj Jul 21 '22 at 17:16
  • allclose is proving to be the best solution. – Martin H Dec 26 '22 at 18:40

0 Answers0