Pytorch閱讀文檔之dot,mm,matmul函數

Pytorch閱讀文檔之dot,mm,matmul函數

torch.dot()

torch.dot(input, tensor) → Tensor
#計算兩個張量的點積(內積)
#官方提示:不能進行廣播(broadcast).
#example
>>> torch.dot(torch.tensor([2, 3]), torch.tensor([2, 1])) #即對應位置相乘再相加
tensor(7)
>>> torch.dot(torch.rand(2, 3), torch.rand(2, 2))
#報錯,只允許一維的tensor
RuntimeError: 1D tensors expected, got 2D, 2D tensors at /Users/distiller/project/conda/conda-bld/pytorch_1570710797334/work/aten/src/TH/generic/THTensorEvenMoreMath.cpp:774

torch.mm

torch.mm(input, mat2, out=None) → Tensor
#對矩陣imput和mat2執行矩陣乘法。 如果input爲(n x m)張量,則mat2爲(m x p)張量,out將爲(n x p)張量。
#官方提示此功能不廣播。有關廣播的矩陣乘法,請參見torch.matmul()。
#example
>>> mat1 = torch.randn(2, 3)
>>> mat2 = torch.randn(3, 3)
>>> torch.mm(mat1, mat2)
tensor([[ 0.4851,  0.5037, -0.3633],
        [-0.0760, -3.6705,  2.4784]])

torch.matmul()

torch.matmul(input, other, out=None) → Tensor
#兩個張量的矩陣乘積。行爲取決於張量的維數,如下所示:
#1. 如果兩個張量都是一維的,則返回點積(標量)。
>>> # vector x vector
>>> tensor1 = torch.randn(3)
>>> tensor2 = torch.randn(3)
>>> torch.matmul(tensor1, tensor2).size()
torch.Size([])
#2. 如果兩個參數都是二維的,則返回矩陣矩陣乘積。
# matrix x matrix
>>> tensor1 = torch.randn(3, 4)
>>> tensor2 = torch.randn(4, 5)
>>> torch.matmul(tensor1, tensor2).size()
torch.Size([3, 5])
#3. 如果第一個參數是一維的,而第二個參數是二維的,則爲了矩陣乘法,會將1附加到其維數上。矩陣相乘後,將刪除前置尺寸。
# 也就是讓tensor2變成矩陣表示,1x3的矩陣和 3x4的矩陣,得到1x4的矩陣,然後刪除1
>>> tensor1 = torch.randn(3, 4)
>>> tensor2 = torch.randn(3)
>>> torch.matmul(tensor2, tensor1).size()
torch.Size([4])
#4. 如果第一個參數爲二維,第二個參數爲一維,則返回矩陣向量乘積。
# matrix x vector
>>> tensor1 = torch.randn(3, 4)
>>> tensor2 = torch.randn(4)
>>> torch.matmul(tensor1, tensor2).size()
torch.Size([3])
#5. 如果兩個自變量至少爲一維且至少一個自變量爲N維(其中N> 2),則返回批處理矩陣乘法。如果第一個參數是一維的,則在其維數之前添加一個1,以實現批量矩陣乘法並在其後刪除。如果第二個參數爲一維,則將1附加到其維上,以實現成批矩陣倍數的目的,然後將其刪除。非矩陣(即批量)維度可以被廣播(因此必須是可廣播的)。例如,如果input爲(jx1xnxm)張量,而other爲(k×m×p)張量,out將是(j×k×n×p)張量。
>>> # batched matrix x broadcasted vector
>>> tensor1 = torch.randn(10, 3, 4)
>>> tensor2 = torch.randn(4)
>>> torch.matmul(tensor1, tensor2).size()
torch.Size([10, 3])
>>> # batched matrix x batched matrix
>>> tensor1 = torch.randn(10, 3, 4)
>>> tensor2 = torch.randn(10, 4, 5)
>>> torch.matmul(tensor1, tensor2).size()
torch.Size([10, 3, 5])
>>> # batched matrix x broadcasted matrix
>>> tensor1 = torch.randn(10, 3, 4)
>>> tensor2 = torch.randn(4, 5)
>>> torch.matmul(tensor1, tensor2).size()
torch.Size([10, 3, 5])
>>> tensor1 = torch.randn(10, 1, 3, 4)
>>> tensor2 = torch.randn(2, 4, 5)
>>> torch.matmul(tensor1, tensor2).size()
torch.Size([10, 2, 3, 5])
發佈了79 篇原創文章 · 獲贊 26 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章