Multiply a 3D array using Numpy's einsum

An acquaintance asked me how to easily multiply a 3D array, and when I looked it up, there was an einsum in the Numpy library that used Einstein's notation, so I tried it because it seems to be easy to do. ..

First, create two 1x2x5 3D matrices and a 2x3x5 3D matrix.

A = 
\left(
\begin{matrix}
a_0 & a_1
\end{matrix}
\right)
, a_0 = 
\left[
\begin{matrix}
0 & 1 & 1 & 0 & 0
\end{matrix}
\right]
, a_1 = 
\left[
\begin{matrix}
0 & 1 & 0 & 0 & 1
\end{matrix}
\right]
W = 
\left(
\begin{matrix}
w_0 & w_1 & w_2 \\
w_3 & w_4 & w_5
\end{matrix}
\right)
, w_0 = 
\left[
\begin{matrix}
0 & 1 & 2 & 3 & 4
\end{matrix}
\right]
, w_1 = 
\left[
\begin{matrix}
5 & 6 & 7 & 8 & 9
\end{matrix}
\right]
...

If you create this using numpy,

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

W = np.arange(30).reshape(2,3,5)

You can do it with.

The shape of the matrix of A (1, 2, 5) is represented by Einstein's reduction symbol (i, j, k). Similarly, the shape of the W matrix (2, 3, 5) is represented by (j, l, k).

Multiplying these two matrices should result in a matrix of (1,3,5), so the formula using einsum looks like this.

R = np.einsum("ijk,jlk -> ilk",A,W)

print(R)
print(R.shape)

When executed, R becomes like this.

[[[ 0 17  2  0 19]
  [ 0 27  7  0 24]
  [ 0 37 12  0 29]]]

(1,3,5)

The result is a 1x3x5 3D matrix.

Reference (English):

Recommended Posts

Multiply a 3D array using Numpy's einsum
Instantly create a diagram of 2D data using python's matplotlib
Detect "temperature (using A / D converter)" using python on Raspberry Pi 3!