from einops import rearrangex = np.random.randn(2, 32, 32, 3) # NHWC# 转置:NHWC -> NCHWy = rearrange(x, 'b h w c -> b c h w') # (2, 3, 32, 32)# 展平y = rearrange(x, 'b h w c -> b (h w) c') # (2, 1024, 3)# 分解y = rearrange(x, 'b (h1 h2) w c -> b h1 h2 w c', h1=2) # (2, 2, 16, 32, 3)# 图像补丁(ViT)y = rearrange(x, 'b (h p1) (w p2) c -> b (h w) (p1 p2 c)', p1=8, p2=8)# (2, 16, 192): 16个补丁,每补丁 8x8x3=192维
reduce:聚合维度
from einops import reduce# 全局平均池化y = reduce(x, 'b h w c -> b c', 'mean') # (2, 3)# 2x2 最大池化y = reduce(x, 'b (h h2) (w w2) c -> b h w c', 'max', h2=2, w2=2) # (2, 16, 16, 3)# 批次求和y = reduce(x, 'b h w c -> h w c', 'sum') # (32, 32, 3)
repeat:重复张量
from einops import repeat# 新维度重复y = repeat(x, 'b h w c -> g b h w c', g=3) # (3, 2, 32, 32, 3)# 沿现有维度重复y = repeat(x, 'b h w c -> b h w (c repeat)', repeat=2) # (2, 32, 32, 6)# 类似 tiley = repeat(x, 'b h w c -> b (h rh) (w rw) c', rh=2, rw=3) # (2, 64, 96, 3)