Skip to content

Instantly share code, notes, and snippets.

@vahbuna
Last active January 14, 2025 12:13
Show Gist options
  • Save vahbuna/44a6028943edf47e9b832ccced1be458 to your computer and use it in GitHub Desktop.
Save vahbuna/44a6028943edf47e9b832ccced1be458 to your computer and use it in GitHub Desktop.
Numpy Einstein Summation

Einsum

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

B = np.array([[0, 1, 0],
              [1, 1, 0],
              [1, 1, 1]])
np.einsum('ij,jk->ijk', A, B) 
array([[[0, 1, 0],
        [1, 1, 0],
        [1, 1, 1]],

       [[0, 2, 0],
        [2, 2, 0],
        [2, 2, 2]],

       [[0, 5, 0],
        [5, 5, 0],
        [5, 5, 5]]])
np.einsum('ij,jk->ik', A, B) 
array([[ 2,  3,  1],
       [ 4,  6,  2],
       [10, 15,  5]])
np.einsum('ij,jk->ij', A, B) 
array([[ 1,  2,  3],
       [ 2,  4,  6],
       [ 5, 10, 15]])
np.einsum('ij,jk->jk', A, B) 
array([[0, 8, 0],
       [8, 8, 0],
       [8, 8, 8]])

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment