einops.reduce函数

函数定义reduce(tensor: Tensor, pattern: str, reduction: Reduction, **axes_lengths: int)

介绍:该函数可以用非常直观的方式对张量进行一系列处理。

Parameters:
参数:
    tensor: 要处理的张量
    pattern:维度变换
    reduction: 要执行的操作,可以是('min', 'max', 'sum', 'mean', 'prod')
    axes_lengths: any additional specifications for dimensions

举例:

import torch
from einops import rearrange, reduce

a=torch.tensor([
    [[1,1,1],
    [2,2,2]],

    [[3,3,3],
    [4,4,4]]
    ],dtype=float)

1、张量创建好了,先尝试着任意做一个max操作。在此处t b c分别代表三个维度,转换为b c就意味着一个维度被抹消掉了,后面的max表示沿着t维度求最大值。

b=reduce(a, 't b c -> b c', 'max')
print(b)
结果:
tensor([[3., 3., 3.],
        [4., 4., 4.]], dtype=torch.float64)

再尝试这次抹消掉第三个维度

b=reduce(a, 't b c -> t b', 'max')

结果: 

tensor([[1., 2.],
        [3., 4.]], dtype=torch.float64)

可以看出来这次进行求最大值操作的是第三个维度,也就是最inside的维度。

2、再尝试求和操作

sum=reduce(a, 't b c -> t b', 'sum')
print(sum)
结果
tensor([[ 3.,  6.],
        [ 9., 12.]], dtype=torch.float64)

这次看的更清晰,依旧是第三个维度,最内层的列表进行了求和操作变为了一个常数。

类似的还可以进行('min', 'max', 'sum', 'mean', 'prod')(求最小值,求最大值,求和,求平均,求积)这一系列操作

3.保持维度不降的操作

reduce(a2, 'c h w ->  c () ()', 'max')
tensor([[[2.]],
        [[4.]]], dtype=torch.float64)
reduce(a2, 'h w c -> () () c', 'max')
tensor([[[4., 4., 4., 4.]]], dtype=torch.float64)

这后面是一些比较少用的操作

1.还可以用来做池化处理

a2=torch.tensor([
    [[1,1,1,1],
    [2,2,2,2]],
    [[3,3,3,3],
    [4,4,4,4]]
    ],dtype=float)
y1 = reduce(a2, 'b (h1 h2) (w1 w2) -> b h1 w1', 'max', h2=2, w2=2)
print(y1)
tensor([[[2., 2.]],
        [[4., 4.]]], dtype=torch.float64)

2.可以将channel维度中的size转化为h和w维度的size

y3 = rearrange(a2, ' h1 w1 (h2 w2 c)-> (h1 h2) (w1 w2) c', h2=2, w2=2)
print(y3)
tensor([[[1.],
         [1.],
         [2.],
         [2.]],
        [[1.],
         [1.],
         [2.],
         [2.]],
        [[3.],
         [3.],
         [4.],
         [4.]],
        [[3.],
         [3.],
         [4.],
         [4.]]], dtype=torch.float64)
print(y3.shape)
torch.Size([4, 4, 1])
print(a2,a2.shape)
tensor([[[1., 1., 1., 1.],
         [2., 2., 2., 2.]],
        [[3., 3., 3., 3.],
         [4., 4., 4., 4.]]], dtype=torch.float64) torch.Size([2, 2, 4])

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值