torch维度求和实际问题


#导入torch
import torch
#创建一个维度为3的tensor
c = torch.rand(3,2,3)

print(c)
print(c.shape)
print(torch.sum(c,dim=0))
print(torch.sum(c,dim=2))
print(torch.sum(c,dim=2))

运行结果:

tensor([[[0.7302, 0.3020, 0.8474],
         [0.9546, 0.9532, 0.7384]],

        [[0.9916, 0.6270, 0.4345],
         [0.3405, 0.5390, 0.9705]],

        [[0.9224, 0.5279, 0.2834],
         [0.0918, 0.5866, 0.5977]]])
torch.Size([3, 2, 3])
tensor([[2.6443, 1.4569, 1.5653],
        [1.3870, 2.0788, 2.3066]])
tensor([[1.8796, 2.6462],
        [2.0532, 1.8500],
        [1.7337, 1.2761]])
tensor([[1.8796, 2.6462],
        [2.0532, 1.8500],
        [1.7337, 1.2761]])

第0维求和的时候第一个数为什么加起来不对啊,不应该是2.6442

你要知道,这里的float是torch默认的float32,并不是显示的4位,后面还有很多位呢,4舍五入很正常。