最近發現一個在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)也能得到對應維度的結果,但並不是
想要的正確結果