從零開始深度學(xué)習(xí)Pytorch筆記(6)——張量的數(shù)學(xué)運算


前文傳送門:
從零開始深度學(xué)習(xí)Pytorch筆記(1)——安裝Pytorch
從零開始深度學(xué)習(xí)Pytorch筆記(2)——張量的創(chuàng)建(上)
從零開始深度學(xué)習(xí)Pytorch筆記(3)——張量的創(chuàng)建(下)
從零開始深度學(xué)習(xí)Pytorch筆記(4)——張量的拼接與切分
從零開始深度學(xué)習(xí)Pytorch筆記(5)——張量的索引與變換
在該系列的上一篇,我們介紹了更多Pytorch中的張量的索引與變換,本文研究張量的數(shù)學(xué)運算。
張量的加減乘除運算
使用torch.add()張量相加
torch.add(input,?other,?out=None)
參數(shù):
input:張量
other:另一個張量或者數(shù)值
以下是張量加上20(對應(yīng)位置都加上20)
a?=?torch.randn(4)
a

torch.add(a,?20)

a?=?torch.randn(4)
a
以下是兩個張量相加

b?=?torch.randn(4)
b

torch.add(a,?b)

使用torch.addcdiv()張量相加和相除
torch.addcdiv(input,?value=1,?tensor1,?tensor2,?out=None)
用tensor2對tensor1逐元素相除,然后乘以標量值value?并加到input
總之意思用公式表達為:input+value*tensor1/tensor2
t?=?torch.randn(1,?3)
t1?=?torch.randn(3,?1)
t2?=?torch.randn(1,?3)
torch.addcdiv(t,?0.1,?t1,?t2)
這個較為復(fù)雜,因為維度不一致也可以操作,我將它拆解出來,請看:
t?=?torch.randn(1,?3)
t

t1?=?torch.randn(3,?1)
t1

t2?=?torch.randn(3,?1)
t2

t12?=?t1/t2
t12

t12*0.1

#維度不同也可以相加
t12*0.1+t

以上的操作,用torch.addcdiv()一行就可以搞定,請看:
torch.addcdiv(t,?0.1,?t1,?t2)

結(jié)果相同,你理解了對吧~
torch.addcmul()張量相加和相乘
addcmul(input,?value=1,?tensor1,?tensor2,?out=None)
input+value*tensor1*tensor2
類似上面的操作,只是把相除變成相乘了
t?=?torch.randn(1,?3)
t1?=?torch.randn(3,?1)
t2?=?torch.randn(1,?3)
torch.addcdiv(t,?0.1,?t1,?t2)

使用torch.sub()張量相減
t1?=?torch.rand(2,3)
t1

t2?=?torch.rand(2,3)
t2

t?=?torch.sub(t1,?t2)
print(t)

使用torch.mul()張量相乘
t1?=?torch.rand(5,?5)
t2?=?torch.rand(5,?5)
t?=?torch.mul(t1,?t2)
print(t)

使用torch.div()張量相除
t1?=?torch.rand(5,?5)
t2?=?torch.rand(5,?5)
t?=?torch.div(t1,?t2)
print(t)

張量的對數(shù),指數(shù),冪函數(shù)運算
torch.log(input,out=None)#計算input的自然對數(shù)
torch.log10(input,out=None)#計算input的10為底的對數(shù)
torch.log2(input,out=None)#計算input的2為底的對數(shù)
torch.exp(input,out=None)#對輸入input按元素求e次冪值,并返回結(jié)果張量,冪值e可以為標量也可以是和input相同大小的張量
torch.pow(input,out=None)#次方運算
其實以上的都差不多,那就舉一個例子:
a?=?torch.randn(5)
a

torch.log(a)

張量的三角函數(shù)運算
torch.abs(input,out=None)#計算張量的每個元素絕對值
torch.acos(input,out=None)#返回一個新張量,包含輸入張量每個元素的反余弦
torch.cosh(input,out=None)#返回一個新張量,包含輸入input張量每個元素的雙曲余弦
torch.cos(input,out=None)#返回一個新張量,包含輸入input張量每個元素的余弦
torch.asin(input,out=None)#返回一個新張量,包含輸入input張量每個元素的反正弦
torch.atan(input,out=None)#返回一個新張量,包含輸入input張量每個元素的反正切
torch.atan2(input1,?input2,?out=None)#返回一個新張量,包含兩個輸入張量input1和input2的反正切函數(shù)
其實以上的都差不多,那就舉一個例子:
a?=?torch.randn(5)
a?

torch.cos(a)

歡迎關(guān)注公眾號學(xué)習(xí)之后的深度學(xué)習(xí)連載部分~
喜歡記得點在看哦,證明你來看過~