最近发现一个在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)也能得到对应维度的结果,但并不是

想要的正确结果

相关文章:

  • 2022-12-23
  • 2022-03-08
  • 2022-12-23
  • 2022-12-23
  • 2021-05-24
  • 2021-05-12
  • 2021-10-13
  • 2021-09-27
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-01-18
  • 2021-11-26
  • 2022-12-23
  • 2021-08-26
  • 2022-12-23
相关资源
相似解决方案