函数定义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])