einsum() (NumPy)

np.einsum() (Einstein summation) expresses sums of products over array indices using a compact subscript string. It can do dot products, matrix multiplication, transposes, traces, and custom contractions in one call.

NumPy

The subscript string labels the axes of each input and the output: 'ij,jk->ik' is matrix multiplication (sum over the shared index j), 'ii->' is the trace, 'ij->ji' is a transpose, and 'i,i->' is a dot product. Any index that appears on the input side but not the output side is summed over.

einsum's appeal is that it states exactly which axes pair up and which collapse, making complex tensor operations explicit and avoiding chains of reshapes, transposes, and matmuls. For many contractions it is also competitive in speed, sometimes faster, than the equivalent sequence of operations.

It has a learning curve, but once the notation clicks it becomes a precise, readable way to write operations that would otherwise be hard to express, which is why it is popular in deep-learning code.

Syntax

np.einsum('ij,jk->ik', A, B)

Examples

Python — 1*4 + 2*5 + 3*6 = 32, the dot product.

import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.einsum("i,i->", a, b))

Output:

32

Learn it in a lesson

See also

Back to the Dictionary