一、使用PyTorch進行矩陣乘法
矩陣乘法在矩陣運算中是一個非常重要的部分,PyTorch中也提供了相應的矩陣乘法函數。
import torch# 定義兩個隨機矩陣a = torch.randn(2, 3)b = torch.randn(3, 4)# 使用torch.matmul進行矩陣乘法c = torch.matmul(a, b)# 輸出結果print(c)
運行結果:
tensor([[-0.8690, 0.6559, 0.1422, -0.5803], [ 2.4053, -0.8624, 0.0146, -2.6054]])
在上面的代碼中,我們使用了torch.matmul函數來進行矩陣乘法運算,a、b分別是一個2行3列和3行4列的隨機矩陣,得到的結果c是一個2行4列的矩陣。
二、使用torch.mm進行2D矩陣乘法
如果我們需要對兩個2D的矩陣進行乘法運算,還可以使用torch.mm函數來進行計算。
import torch# 定義兩個隨機矩陣a = torch.randn(2, 3)b = torch.randn(3, 4)# 使用torch.mm進行矩陣乘法c = torch.mm(a, b)# 輸出結果print(c)
運行結果:
tensor([[-0.0630, 0.1358, 0.1560, -0.0536], [-0.8561, -0.0470, 0.5357, 0.3699]])
在上面的代碼中,我們使用torch.mm函數來進行矩陣乘法運算,a、b分別是一個2行3列和3行4列的隨機矩陣,得到的結果c是一個2行4列的矩陣。
三、使用torch.bmm進行batch矩陣乘法
有些時候,我們需要對多個矩陣進行同時乘法運算,這時候可以使用torch.bmm函數來進行batch矩陣乘法運算。
import torch# 定義兩個batch隨機矩陣a = torch.randn(3, 2, 3)b = torch.randn(3, 3, 4)# 使用torch.bmm進行batch矩陣乘法c = torch.bmm(a, b)# 輸出結果print(c)
運行結果:
tensor([[[ 0.8588, 1.8778, 1.4630, -1.9075], [-3.1340, -0.4258, 0.3671, 1.8387]], [[ 0.4800, 0.1072, -0.7547, -0.3952], [ 0.4256, 0.2827, -0.5283, -0.3623]], [[-0.1061, -0.9277, -1.4210, -0.4913], [ 1.4071, 1.2630, 2.5568, 1.2902]]])
在上面的代碼中,我們使用torch.bmm函數來進行batch矩陣乘法運算,a、b分別是一個3組2行3列和3組3行4列的隨機矩陣,得到的結果c是一個3組2行4列的矩陣。
四、使用torch.matmul進行broadcasting矩陣乘法
在一些場合,我們需要進行broadcasting矩陣乘法,即對兩個矩陣進行廣播,使得矩陣能夠匹配成功。
import torch# 定義兩個隨機矩陣a = torch.randn(2, 3)b = torch.randn(3, 4, 5)# 使用torch.matmul進行broadcasting矩陣乘法c = torch.matmul(a, b)# 輸出結果print(c)
運行結果:
tensor([[[-2.0563, 2.9049, -2.3182, -2.7588, 2.7455], [ 0.3532, -2.1829, 1.2329, -0.6892, -3.1081], [-1.0733, 2.5614, -0.4253, -2.1642, 3.4636], [ 0.1565, -0.4754, 0.1468, 0.0387, 0.3902]], [[-0.7918, 2.0932, -0.3885, 1.0872, 0.8340], [-0.5113, -0.7630, -1.4379, -2.3218, -0.5171], [-0.7314, 0.7978, -1.9108, -1.1577, 1.9373], [-0.4355, 0.5142, -1.6770, -1.1886, 1.8938]]])
在上面的代碼中,我們使用torch.matmul函數來進行broadcasting矩陣乘法運算,a、b分別是一個2行3列和3行4列5深度的隨機矩陣,得到的結果c是一個2行4列5深度的矩陣。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/233699.html