torch中的tensor求和

最近发现一个在torch中容易混淆的问题:

import numpy as np
import torch

x1 = torch.tensor([[1,2,3],[0,1,2]])
x2 = torch.tensor([[2,3,4],[2,4,1]])
x11 = np.array([[1,2,3], [0,1,2]])
x22 = np.array([[2,3,4],[2,4,1]])

print(x1+x2)
print(x11+x22)
>>>
tensor([[3, 5, 7],
        [2, 5, 3]])
[[3 5 7]
 [2 5 3]]


print(sum(x1,x2))
print(sum(x11,x22))
>>>
tensor([[3, 6, 9],
        [3, 7, 6]])
[[3 6 9]
 [3 7 6]]


print(sum([x1,x2]))
print(sum([x11,x22]))
>>>tensor([[3, 5, 7],
        [2, 5, 3]])
[[3 5 7]
 [2 5 3]]

print(torch.add(x1,x2))
>>>
tensor([[3, 5, 7],
        [2, 5, 3]])

也就是说,假如需要把两个或多个tensor逐元素求和,则需要使用python自带的sum函数,但一定要注意要把这些tensor变成列表,否则直接用sum(a,b)也能得到对应维度的结果,但并不是

想要的正确结果

posted @ 2020-10-28 10:46  嶙羽  阅读(5398)  评论(0编辑  收藏  举报