以下為部分逐元素操作代碼實例。
import torcht = torch.randn(1, 3)
t1 = torch.randn(3, 1)
t2 = torch.randn(1, 3)#t+0.1*(t1/t2)
torch.addcdiv(t, 0.1, t1, t2)#計算sigmoid
torch.sigmoid(t)#將t限制在[0,1]之間
torch.clamp(t,0,1)#t+2進行就地運算
t.add_(2)
歸并操作一般涉及一個dim參數,指定沿哪個維進行歸并。另一個參數是keepdim,說明輸出結果中是否保留維度1,缺省情況是False,即不保留。以下為歸并操作的部分代碼
import torch#生成一個含6個數的向量
a=torch.linspace(0,10,6)#使用view方法,把a變為2x3矩陣
a=a.view((2,3))#沿y軸方向累加,即dim=0
b=a.sum(dim=0) #b的形狀為[3]#沿y軸方向累加,即dim=0,并保留含1的維度
b=a.sum(dim=0,keepdim=True) #b的形狀為[1,3]
機器學習和深度學習中存在大量的矩陣運算,常用的算法有兩種:一種是逐元素乘法,另外一種是點積乘法
1)Torch的dot與Numpy的dot有點不同,Torch中的dot是對兩個為1D張量進行點積運算,Numpy中的dot無此限制。
2)mm是對2D的矩陣進行點積,bmm對含batch的3D進行點積運算。
3)轉置運算會導致存儲空間不連續,需要調用contiguous方法轉為連續。
torch.dot
、torch.mm
和 torch.bmm
1. 使用?torch.dot
torch.dot
計算兩個一維張量(向量)的點積。
import torcha = torch.tensor([2, 3])
b = torch.tensor([3, 4])result_dot = torch.dot(a, b) # 運行結果為 2*3 + 3*4 = 6 + 12 = 18
print("Dot product result:", result_dot)
解釋: 點積是對應元素相乘后的和,即 2×3+3×4=6+12=182×3+3×4=6+12=18。
2. 使用?torch.mm
torch.mm
執行兩個二維張量(矩陣)之間的矩陣乘法。
x = torch.randint(10, (2, 3)) # 創建一個形狀為 (2, 3) 的隨機整數張量
y = torch.randint(6, (3, 4)) # 創建一個形狀為 (3, 4) 的隨機整數張量result_mm = torch.mm(x, y) # 形狀為 (2, 4) 的結果張量
print("Matrix multiplication result:\n", result_mm)
解釋: torch.mm
對兩個二維張量執行標準的矩陣乘法。給定 XX 是 2×32×3 的矩陣,YY 是 3×43×4 的矩陣,則結果是一個 2×42×4 的矩陣。
示例輸出
x = tensor([[7, 8, 9],[5, 6, 7]])
y = tensor([[4, 3, 2, 1],[0, 1, 2, 3],[4, 3, 2, 1]])
tensor([[64, 54, 44, 34],[48, 40, 32, 24]])
3. 使用?torch.bmm
torch.bmm
執行批量矩陣乘法,適用于三維張量,其中每個二維子張量(切片)都進行矩陣乘法。
x = torch.randint(10, (2, 2, 3)) # 創建一個形狀為 (2, 2, 3) 的隨機整數張量
y = torch.randint(6, (2, 3, 4)) # 創建一個形狀為 (2, 3, 4) 的隨機整數張量result_bmm = torch.bmm(x, y) # 形狀為 (2, 2, 4) 的結果張量
print("Batch matrix multiplication result:\n", result_bmm)
解釋: torch.bmm
針對三維張量中的每一對二維子張量執行矩陣乘法。對于形狀為 (batch_size, m, n)
和 (batch_size, n, p)
的輸入張量,輸出將是形狀為 (batch_size, m, p)
的張量。
示例輸出
假設 x
和 y
分別是:
x = tensor([[[7, 8, 9],[5, 6, 7]],[[1, 2, 3],[4, 5, 6]]])y = tensor([[[4, 3, 2, 1],[0, 1, 2, 3],[4, 3, 2, 1]],[[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]]])
則 result_bmm
可能是:
tensor([[[64, 54, 44, 34],[48, 40, 32, 24]],[[38, 44, 50, 56],[86, 98, 110, 122]]])
總結
torch.dot
:用于計算兩個一維張量的點積。torch.mm
:用于計算兩個二維張量的標準矩陣乘法。torch.bmm
:用于計算兩個三維張量中對應的二維子張量之間的批量矩陣乘法。