einops基础使用
einops是一个用于操作张量的库,它的出现可以替代我们平时使用的reshape、view、transpose和permute等操作
einops支持numpy、pytorch、tensorflow等
y = x.transpose(0, 2, 3, 1) 等同
y = rearrange(x, ‘b c h w -> b h w c’)
官方文档
import sys
sys.path.append("/content/docs")
import numpy
from utils import display_np_arrays_as_images
display_np_arrays_as_images()
ims = numpy.load('/content/docs/resources/test_images.npy', allow_pickle=False)
# 6张3通道96*96的彩色图
print(ims.shape, ims.dtype)
ims[0]
rearrange 重新排列
1.对图像高宽进行转换
rearrange(ims[0], 'h w c -> w h c')
2.将批次和高度组合到一个新的高度维度
rearrange(ims,'b h w c ->(b h) w c')
rearrange(ims, 'b h w c -> h (b w) c')
rearrange(ims,'b h w c ->(b w) h c')
rearrange(ims, 'b h w c -> h (b w) c').shape
合并成一维
rearrange(ims, 'b h w c -> (b h w c)').shape
分解维度
# 指定一个维度,剩下一个维度可以自己算出
rearrange(ims, '(b1 b2) h w c -> b1 b2 h w c ', b1=2).shape
先分解维度,再合并维度
rearrange(ims, '(b1 b2) h w c -> (b1 h) (b2 w) c ', b1=2)
rearrange(ims, '(b1 b2) h w c -> (b2 h) (b1 w) c ', b1=2)
rearrange(ims, 'b h (w w2) c -> (h w2) (b w) c', w2=2)
Reduce
合并第一个维度(以均值合并)
reduce(ims, 'b h w c -> h w c', 'mean')
轴操作
ims.mean(axis=0)
除了均值mean, 还有 min, max, sum, prod操作
reduce(ims, 'b h w c -> h w', 'min')
缩小图为原来是1/4
reduce(ims, 'b (h h2) (w w2) c -> h (b w) c', 'mean', h2=2, w2=2)
Stack and concatenate
# 转list
x = list(ims)
print(type(x), 'with', len(x), 'tensors of shape', x[0].shape)
# that's how we can stack inputs
# "list axis" becomes first ("b" in this case), and we left it there
rearrange(x, 'b h w c -> b h w c').shape
rearrange(x, 'b h w c -> h w c b').shape
numpy.array_equal(rearrange(x, 'b h w c -> h w c b'), numpy.stack(x, axis=3))
rearrange(x, 'b h w c -> h (b w) c').shape
numpy.array_equal(rearrange(x, 'b h w c -> h (b w) c'), numpy.concatenate(x, axis=1))
Repeat
repeat(ims[0], 'h w c -> h new_axis w c', new_axis=5).shape
# shortcut
repeat(ims[0], 'h w c -> h 5 w c').shape
repeat(ims[0], 'h w c -> h (repeat w) c', repeat=3)
repeat(ims[0], 'h w c -> (2 h) (2 w) c')
(repeat w)换成 (w repeat)就是对原图进行拉伸
repeat(ims[0], 'h w c -> h (w repeat) c', repeat=3)