How does np.einsum
work?
Given arrays A
and B
, their matrix multiplication followed by transpose is computed using (A @ B).T
, or equivalently, using:
np.einsum("ij, jk -> ki", A, B)
arraysmultidimensional arraynumpynumpy-einsumpython
How does np.einsum
work?
Given arrays A
and B
, their matrix multiplication followed by transpose is computed using (A @ B).T
, or equivalently, using:
np.einsum("ij, jk -> ki", A, B)
Best Answer
(Note: this answer is based on a short blog post about
einsum
I wrote a while ago.)What does
einsum
do?Imagine that we have two multi-dimensional arrays,
A
andB
. Now let's suppose we want to...A
withB
in a particular way to create new array of products; and then maybeThere's a good chance that
einsum
will help us do this faster and more memory-efficiently than combinations of the NumPy functions likemultiply
,sum
andtranspose
will allow.How does
einsum
work?Here's a simple (but not completely trivial) example. Take the following two arrays:
We will multiply
A
andB
element-wise and then sum along the rows of the new array. In "normal" NumPy we'd write:So here, the indexing operation on
A
lines up the first axes of the two arrays so that the multiplication can be broadcast. The rows of the array of products are then summed to return the answer.Now if we wanted to use
einsum
instead, we could write:The signature string
'i,ij->i'
is the key here and needs a little bit of explaining. You can think of it in two halves. On the left-hand side (left of the->
) we've labelled the two input arrays. To the right of->
, we've labelled the array we want to end up with.Here is what happens next:
A
has one axis; we've labelled iti
. AndB
has two axes; we've labelled axis 0 asi
and axis 1 asj
.By repeating the label
i
in both input arrays, we are tellingeinsum
that these two axes should be multiplied together. In other words, we're multiplying arrayA
with each column of arrayB
, just likeA[:, np.newaxis] * B
does.Notice that
j
does not appear as a label in our desired output; we've just usedi
(we want to end up with a 1D array). By omitting the label, we're tellingeinsum
to sum along this axis. In other words, we're summing the rows of the products, just like.sum(axis=1)
does.That's basically all you need to know to use
einsum
. It helps to play about a little; if we leave both labels in the output,'i,ij->ij'
, we get back a 2D array of products (same asA[:, np.newaxis] * B
). If we say no output labels,'i,ij->
, we get back a single number (same as doing(A[:, np.newaxis] * B).sum()
).The great thing about
einsum
however, is that it does not build a temporary array of products first; it just sums the products as it goes. This can lead to big savings in memory use.A slightly bigger example
To explain the dot product, here are two new arrays:
We will compute the dot product using
np.einsum('ij,jk->ik', A, B)
. Here's a picture showing the labelling of theA
andB
and the output array that we get from the function:You can see that label
j
is repeated - this means we're multiplying the rows ofA
with the columns ofB
. Furthermore, the labelj
is not included in the output - we're summing these products. Labelsi
andk
are kept for the output, so we get back a 2D array.It might be even clearer to compare this result with the array where the label
j
is not summed. Below, on the left you can see the 3D array that results from writingnp.einsum('ij,jk->ijk', A, B)
(i.e. we've kept labelj
):Summing axis
j
gives the expected dot product, shown on the right.Some exercises
To get more of a feel for
einsum
, it can be useful to implement familiar NumPy array operations using the subscript notation. Anything that involves combinations of multiplying and summing axes can be written usingeinsum
.Let A and B be two 1D arrays with the same length. For example,
A = np.arange(10)
andB = np.arange(5, 15)
.The sum of
A
can be written:Element-wise multiplication,
A * B
, can be written:The inner product or dot product,
np.inner(A, B)
ornp.dot(A, B)
, can be written:The outer product,
np.outer(A, B)
, can be written:For 2D arrays,
C
andD
, provided that the axes are compatible lengths (both the same length or one of them of has length 1), here are a few examples:The trace of
C
(sum of main diagonal),np.trace(C)
, can be written:Element-wise multiplication of
C
and the transpose ofD
,C * D.T
, can be written:Multiplying each element of
C
by the arrayD
(to make a 4D array),C[:, :, None, None] * D
, can be written: