To replace np.matmul (or the @ operator) with np.einsum, you can use Einstein summation notation to explicitly define the tensor operations. This approach offers greater flexibility and clarity, especially for higher-dimensional arrays or custom axis interactions.
Key Concepts
Einstein Notation: Repeated indices in the input imply summation (contraction).
Matrix Multiplication: Multiply rows of the first matrix with columns of the second, summing over the shared dimension.
Einsum Syntax: 'input_indices->output_indices' where inputs are separated by commas.
Basic 2D Matrix Multiplication
For two 2D arrays A (shape m×n) and B (shape n×p), the result C (shape m×p) is computed as:
Cij=k∑Aik
This translates directly to:
python
np.einsum('ik,kj->ij', A, B)
Batched Matrix Multiplication
When working with batched matrices (e.g., A: shape b×m×n, B: shape b×n×), the batch dimension is preserved:
Cbij=k∑A
Use:
python
np.einsum('bij,bjk->bik', A, B)
Transposed Matrix Multiplication
If you want to compute AT⋅B (where A is n×m, B is ), you can write:
python
np.einsum('ki,kj->ij', A, B)
Here, ki corresponds to AT (since the first dimension becomes the second).
For A⋅BT (with A: m×n, B: ):
python
np.einsum('ik,jk->ij', A, B)
Higher-Dimensional Tensors
For more complex shapes like A: (a,b,m,n) and B: (a,b,, the matrix multiplication on the last two dimensions becomes:
python
np.einsum('abik,abkj->abij', A, B)
This computes:
Cabij=k∑A
Preserving batch dimensions a and b.
Broadcasting with Ellipsis (...)
If arrays have variable leading dimensions (e.g., batched tensors), use ... to represent arbitrary leading dimensions:
python
np.einsum('...ik,...kj->...ij', A, B)
This works for arrays with shapes like (...,m,n) and (...,n,p), producing (...,m.
Summary of Einsum vs. Matmul
Operation
Einsum Notation
Matmul Equivalent
2D Matrix Multiplication
'ik,kj->ij'
A @ B
Batched Matrix Multiplication
'bij,bjk->bik'
A @ B
Transpose Multiplication
'ki,kj->ij'
A.T @ B
Outer Product
'i,j->ij'
np.outer(u, v)
Higher-Dimensional Matmul
'abik,abkj->abij'
A @ B
Broadcasted Matmul
'...ik,...kj->...ij'
A @ B
Advantages of Einsum
Flexibility: Control over axis contraction and output shape.
Clarity: Explicitly shows which axes are involved in the computation.
Avoids Reshaping: Directly handles higher-dimensional arrays without reshaping or transposing.
Performance Considerations
While einsum is powerful, matmul may be faster for large matrices due to optimized BLAS integration. Always benchmark for performance-critical applications.
Example Code
python
import numpy as np
# 2D matrix multiplication
A = np.random.rand(3, 4)
B = np.random.rand(4, 5)
C = np.einsum('ik,kj->ij', A, B)
# Batched matrix multiplication
A_batch = np.random.rand(2, 3, 4)
B_batch = np.random.rand(2, 4, 5)
C_batch = np.einsum('bij,bjk->bik', A_batch, B_batch)
# Transposed multiplication
A_transposed = np.random.rand(4, 3) # A is 4x3, so A.T is 3x4
B_regular = np.random.rand(4, 5)
C_transposed = np.einsum('ki,kj->ij', A_transposed, B_regular)
# Higher-dimensional matrix multiplication
A_higher = np.random.rand(2, 3, 4, 5)
B_higher = np.random.rand(2, 3, 5, 6)
C_higher = np.einsum('abik,abkj->abij', A_higher, B_higher)
By mastering np.einsum, you gain a versatile tool for tensor operations, making complex matrix manipulations more intuitive and explicit.