tensor的數學運算
& n b s p ;
基礎四則運算
a + b ——torch.add()
a - b ——torch.sub()
a * b ——torch.mul()
a / b ——torch.div()
效果一致
& n b s p ;
矩陣相乘
torch.mm:只適用於2D的矩陣相乘
torch.matmul推薦使用
@ (a@b)與matmul效果相同
a = torch.ones(2,2)
b = torch.ones(2,2)
print(torch.matmul(a,b))
#tensor([[2., 2.],
# [2., 2.]])
實例:
a = torch.rand(4,784)
x = torch.rand(4,784)
w = torch.rand(512,784)
(x @ w.t()).shape
#[4,512]
X有4張照片,每張照片都打平了,我們現在希望進行一個降維的過程:【4,784】——>【4,512】
所以我們在中間要構建一個w:【784,512】,通過x@w來實現降維
但是這里的w是按照pytorch的寫法:【channel_out(出去的維度),channel_in(進入的維度)】,所以要進行一個矩陣的轉置。
& n b s p ;
二維以上的矩陣轉置
保持前兩維不變,進行后兩維的運算
例子:
a = torch.rand(4,3,28,64)
b = torch.rand(4,3,64,32)
torch.matmul(a,b).shape
#[4,3,28,32]
運用broadcst規則:
a = torch.rand(4,3,28,64)
b = torch.rand(4,1,64,32)
torch.matmul(a,b).shape
#[4,3,28,32]
& n b s p ;
power函數以及sqrt函數
進行矩陣的平方運算以及開方運算
a = torch.full([2,2],3)
a.pow(2)
#[[9,9],
#[9,9]]
aa = a.pow(2)——aa = a**2
aa = a.sqrt(2)——aa = a**(0.5)
& n b s p ;
exp log函數
exp函數:求自然指數
log函數:求log(默認以e為底)
log2:以2為底
log10:以10為底
a = torch.exp(torch.ones(2,2))
#[[2.7183,2.7183],
#[2.7183,2.7183]]
torch.log(a)
#[[1,1],
#[1,1]]
& n b s p ;
近似值
floor()向下取整
ceil()向上取整
trunc()取整數部分
frac()取小數部分
round()四舍五入
例子:
a = torch.tensor(3.14)
print(a.trunc())
print(a.frac())
#tensor(3.)
#tensor(0.1400)
& n b s p ;
clamp函數
限制矩陣中的最大值與最小值
例子:將矩陣中所有小於10的都變為10
grad = torch.rand(2,3)*15
print(grad)
tensor([[13.3244, 11.6749, 14.0967],
[13.3109, 7.9303, 8.3319]])
temp = grad.clamp(10)
print(temp)
tensor([[13.3244, 11.6749, 14.0967],
[13.3109, 10.0000, 10.0000]])
grad.clamp(0,10)是將矩陣中的元素控制在(0,10)
用處:在進行訓練的時候通過這種方式來控制梯度的大小來防止梯度爆炸以及梯度消失