PyTorch【5】-Tensor 運算


Tensor API 較多,所以把 運算 單獨列出來,方便查看

 

本教程環境 pytorch 1.3以上

乘法

t.mul(input, other, out=None):矩陣乘以一個數

t.matmul(mat, mat, out=None):矩陣相乘

t.mm(mat, mat, out=None):基本上等同於 matmul

a=torch.randn(2,3)
b=torch.randn(3,2)
### 等價操作
print(torch.mm(a,b))        # mat x mat
print(torch.matmul(a,b))    # mat x mat
### 等價操作
print(torch.mul(a,3))       # mat 乘以 一個數
print(a * 3)

注意,乘法可以直接作用於單個數字

 

乘法需要符合 向量乘法 的規則,即尺寸匹配

a=torch.randn(2,3)
c = torch.randn(2, 3)
# print(torch.matmul(a, c))   # 尺寸不符合向量乘法,(2,3)x(2,3)
print(torch.matmul(a, c.t())) # t() 轉置,正確 (2,3)x(3,2)

 

加法

加法有 3 種方式:+,add,add_

import torch as t
y = t.rand(2, 3)        ### 使用[0,1]均勻分布構建矩陣
z = t.ones(2, 3)        ### 2x3 的全 1 矩陣

#### 3 中加法操作等價
print(y + z)            ### 加法1
t.add(y, z)             ### 加法2
### 加法的第三種寫法
result = t.Tensor(2, 3) ### 預先分配空間
t.add(y, z, out=result) ### 指定加法結果的輸出目標
print(result)

 

add_ 與 add 的區別在於,add 不會改變原來的 tensor,而 add_會改變原來的 tensor;

在 pytorch 中,方法后面加  _ 都會改變原來的對象,相當於 in-place 的作用

print(y)
# tensor([[0.4083, 0.3017, 0.9511],
#         [0.4642, 0.5981, 0.1866]])
y.add(z)
print(y)                ### y 不變
# tensor([[0.4083, 0.3017, 0.9511],
#         [0.4642, 0.5981, 0.1866]])
y.add_(z)
print(y)                ### y 變了,相當於 inplace
# tensor([[1.4083, 1.3017, 1.9511],
#         [1.4642, 1.5981, 1.1866]])

 

可以作用於單個數字或者 尺寸為 (1,1) 的 Tensor

a = t.ones(3, 3)
print(a + 1)        ### 可以直接作用於單個數字

b = t.ones(1, 1)
print(a + b)

c = t.ones(2, 1)
# print(a + c)        ### 報錯,如果尺寸不匹配,c 的尺寸只能是 (1, 1)

 

減法 

和加法一樣,三種:-、sub、sub_

a = t.randn(2, 1)
b = t.randn(2, 1)
print(a)
### 等價操作
print(a - b)
print(t.sub(a, b))
print(a)        ### sub 后 a 沒有變化

a.sub_(b)
print(a)        ### sub_ 后 a 也變了

c = 1
print(a - c)    ### 直接作用於單個數字

 

其他運算

t.div(input, other, out=None):除法

t.pow(input, other, out=None):指數

t.sqrt(input, out=None):開方

t.round(input, out=None):四舍五入到整數

t.abs(input, out=None):絕對值

t.ceil(input, out=None):向上取整

t.clamp(input, min, max, out=None):把 input 規范在 min 到 max 之間,超出用 min 和 max 代替,可理解為削尖函數

t.argmax(input, dim=None, keepdim=False):返回指定維度最大值的索引

t.sigmoid(input, out=None)

t.tanh(input, out=None)

 

 

 

 

 

 

參考資料:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM