网络编程
位置:首页>> 网络编程>> Python编程>> 支持PyTorch的einops张量操作神器用法示例详解

支持PyTorch的einops张量操作神器用法示例详解

作者:木盏  发布时间:2023-10-17 23:13:06 

标签:PyTorch,einops,张量操作

今天做visual transformer研究的时候,发现了einops这么个神兵利器,决定大肆安利一波。

先看链接:https://github.com/arogozhnikov/einops

安装:


pip install einops

基础用法

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)

这里的'mean'指定池化方式。 相信你看得懂,不懂可留言提问~

高级用法 

einops也可以嵌套在pytorch的layer里,请看:


# example given for pytorch, but code in other frameworks is almost identical  
from torch.nn import Sequential, Conv2d, MaxPool2d, Linear, ReLU
from einops.layers.torch import Rearrange

model = Sequential(
   Conv2d(3, 6, kernel_size=5),
   MaxPool2d(kernel_size=2),
   Conv2d(6, 16, kernel_size=5),
   MaxPool2d(kernel_size=2),
   # flattening
   Rearrange('b c h w -> b (c h w)'),  
   Linear(16*5*5, 120),
   ReLU(),
   Linear(120, 10),
)

这里的Rearrange是nn.module的子类,直接可以当作网络层放到模型里~

一个字,绝。

来源:https://blog.csdn.net/leviopku/article/details/116204922

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com