Element-wise Operation是多个 tensor 间的操作,Reduction Operation 是一个tensor内部的操作。
Reduction Operation
Reduction Operation的返回值总是使 tensor 的元素数量变小。
t = torch.tensor([
[0, 1, 0],
[2, 0, 2],
[0, 3, 3]
], dtype=torch.float32)
t.sum() #-> tensor(8.)
#返回元素个数
t.numel() #-> 9
t.sum().numel() #-> 1
t.sum().num() < t.numel() #-> True
一些Reduction Operation 函数:
t.sum() #-> tensor(8.)
#所有元素的乘积
t.prod() #-> tensor(0.)
t.mean() #-> tensor(0.8889)
t.std() #-> tensor(1.1667)
问题来了,Reduction Operation 总是返回一个数吗?
Reduction Operation 的 dim 参数
不是的,传入dim
参数,情况就变了
t = torch.tensor([
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
], dtype=torch.float32)
#沿着第0个axis进行运算
t.sum(dim=0) #-> tensor([6., 6., 6., 6.])
#沿着第1个axis进行运算
t.sum(dim=1) #-> tensor([4., 8., 12.])
举个**argmax()**的例, argmax()返回最大值的序号。
t = torch.tensor([
[1, 0, 0, 2],
[0, 3, 3, 0],
[4, 0, 0, 5],
])
t.max(dim=0) #-> (tesnor([4., 3., 3., 5.]), tensor([2, 1, 1, 2]))
t.argmax(dim=0) #-> tensor([2, 1, 1, 2])
t.max(dim=1) #-> (tesnor([2., 3., 5.]), tensor([3, 1, 3]))
t.argmax(dim=1) #-> tensor([3, 1, 3))