torch.sum(input, dim, out=None) → Tensor
- input (Tensor) – 输入张量
- dim (int) – 缩减的维度
- out (Tensor, optional) – 结果张量
代码:
import torch
x = torch.randn(4, 5)
print(x)
print(x.sum(0)) #按列求和
print(x.sum(1)) #按行求和
print(torch.sum(x)) #按列求和
print(torch.sum(x, 0))#按列求和
print(torch.sum(x, 1))#按行求和
运行结果:
tensor([[ 0.2210, 1.8035, 0.7671, -0.1836, -0.2794],
[-0.7922, -1.0881, -2.0180, 1.0981, 0.2320],
[-0.4681, 0.1820, 0.0502, 0.0067, 1.3218],
[ 0.4785, 1.0799, 1.6197, 0.6642, 0.6915]])
tensor([-0.5608, 1.9773, 0.4190, 1.5854, 1.9660])
tensor([ 2.3287, -2.5682, 1.0926, 4.5338])
tensor(5.3868)
tensor([-0.5608, 1.9773, 0.4190, 1.5854, 1.9660])
tensor([ 2.3287, -2.5682, 1.0926, 4.5338])