https://github.com/arogozhnikov/einops
安装:
pip install einops
from einops import rearrange
# rearrange elements according to the pattern
output_tensor = rearrange(input_tensor, 'h w c -> c h w')
用'h w c -> c h w'就完成了维度调换,这个功能与pytorch中的permute相似。但是,einops的rearrange玩法可以更高级:
from einops import rearrange
import torch
a = torch.randn(3, 9, 9) # [3, 9, 9]
output = rearrange(a, 'c (r p) w -> c r p w', p=3)
print(output.shape) # [3, 3, 3, 9]
这就是高级用法了,把中间维度看作r×p,然后给出p的数值,这样系统会自动把中间那个维度拆解成3×3。这样就完成了[3, 9, 9] -> [3, 3, 3, 9]的维度转换。
这个功能就不是pytorch的内置功能可比的。
除此之外,还有reduce和repeat,也是很好用。
from einops import repeat
import torch
a = torch.randn(9, 9) # [9, 9]
output_tensor = repeat(a, 'h w -> c h w', c=3) # [3, 9, 9]
指定c,就可以指定复制的层数了。
再看reduce:
from einops import reduce
import torch
a = torch.randn(9, 9) # [9, 9]
output_tensor = reduce(a, 'b c (h h2) (w w2) -> b h w c', 'mean', h2=2, w2=2)