【杂烩】einops张量操作

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

安装:

pip install einops
 
 

基础用法

einops的强项是把张量的维度操作具象化,让开发者“想出即写出”。举个例子:


 
 
  1. from einops import rearrange
  2. # rearrange elements according to the pattern
  3. output_tensor = rearrange(input_tensor, 'h w c -> c h w')

用'h w c -> c h w'就完成了维度调换,这个功能与pytorch中的permute相似。但是,einops的rearrange玩法可以更高级:


 
 
  1. from einops import rearrange
  2. import torch
  3. a = torch.randn( 3, 9, 9) # [3, 9, 9]
  4. output = rearrange(a, 'c (r p) w -> c r p w', p= 3)
  5. print(output.shape) # [3, 3, 3, 9]

这就是高级用法了,把中间维度看作r×p,然后给出p的数值,这样系统会自动把中间那个维度拆解成3×3。这样就完成了[3, 9, 9] -> [3, 3, 3, 9]的维度转换。

这个功能就不是pytorch的内置功能可比的。

除此之外,还有reducerepeat,也是很好用。


 
 
  1. from einops import repeat
  2. import torch
  3. a = torch.randn( 9, 9) # [9, 9]
  4. output_tensor = repeat(a, 'h w -> c h w', c= 3) # [3, 9, 9]

指定c,就可以指定复制的层数了。

再看reduce


 
 
  1. from einops import reduce
  2. import torch
  3. a = torch.randn( 9, 9) # [9, 9]
  4. output_tensor = reduce(a, 'b c (h h2) (w w2) -> b h w c', 'mean', h2= 2, w2= 2)

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


高级用法 

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


 
 
  1. # example given for pytorch, but code in other frameworks is almost identical
  2. from torch.nn import Sequential, Conv2d, MaxPool2d, Linear, ReLU
  3. from einops.layers.torch import Rearrange
  4. model = Sequential(
  5. Conv2d( 3, 6, kernel_size= 5),
  6. MaxPool2d(kernel_size= 2),
  7. Conv2d( 6, 16, kernel_size= 5),
  8. MaxPool2d(kernel_size= 2),
  9. # flattening
  10. Rearrange( 'b c h w -> b (c h w)'),
  11. Linear( 16* 5* 5, 120),
  12. ReLU(),
  13. Linear( 120, 10),
  14. )

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

一个字,绝。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值