Part-1#
Welcome to einops#
- We don’t write
- We write comprehensible code
y = einops.rearrange(x, "b c h w -> b h w c")
einops supports widely used tensor packages viz.
numpy, pytorch, tensorflow, chainer, gluon
and extends them.
What’s in this tutorial?#
- Fundamentals: reordering, composition, and decomposition of tensors.
- Operations:
rearrange, reduce, repeat - How much can you do with a single operation?
Preparations#
import numpy
from utils import display_np_arrays_as_images
display_np_arrays_as_images()
Load a batch of images#
## there are 6 images of shape 96x96
## with 3 color channels packed as tensors
images = np.load("./resources/test_images.npy", allow_pickle=False)
print(images.shape) ## (6, 96, 96, 3)
Composition of axes#
from einops import rearrange
## composing the first two axes together
## i.e. 6 images of shape (96, 96, 3) are rearranged
## into a single image of shape (6*96, 96, 3)
rearrange(images, "b h w c -> (b h) w c").shape ## (576, 96, 3)
Decomposition of axes#
## decomposition is the reverse of composition
rearrange(images, "b h w c -> b h w c").shape ## (6, 96, 96, 3)
Order of axes matters#
## moving color channel to the 2nd position
rearrange(images, "b h w c -> b c h w").shape ## (6, 3, 96, 96)