PyTorch深度學習(二):2. PyTorch的基本運算操作


本文主要講PyTorch對數據的基本運算操作,奧利給!

1. 對數據的基本運算(加減乘除)

進行基本運算時,操作的數據必須保持形狀相同,即均爲2行3列或均爲4行3列。

1.1 加減乘除的幾種方法:

首先生成兩組2行3列的隨機數

#輸入:
a = torch.randint(1,5,(2,3))
b = torch.randint(1,5,(2,3))
print(a)
print(b)

#輸出:
tensor([[3, 3, 4],
        [3, 3, 4]])
tensor([[2, 3, 1],
        [3, 4, 4]])

1、直接用“+”進行相加操作

a + b

#輸出:
tensor([[5, 6, 5],
        [6, 7, 8]])

2、調用add()函數

torch.add(a,b)

#輸出:
tensor([[5, 6, 5],
        [6, 7, 8]])

3、使用前綴“_”進行操作

# a = a + b
# 注意:任何能使張量tensor會發生變化的操作都有前綴‘_’,例如加法:a.add_,減法:b.sub()
a.add_(b)
#表示爲: a = a + b

#輸出:
tensor([[5, 6, 5],
        [6, 7, 8]])

1.2 取餘與取整:

1、取餘數

#取餘數
a % b

#輸出
tensor([[1, 0, 0],
        [0, 3, 0]])

2、取整數

#取整
a//b

#輸出
tensor([[2, 2, 5],
        [2, 1, 2]])

1.3 矩陣乘法

調用matmul()函數,注意,要保證數據類型一樣纔可進行矩陣勻速,比如均爲int64或均爲float32

1、數據類型的轉換

a = torch.randint(1,5,(2,3))
a

#輸出
tensor([[3, 2, 2],
        [4, 4, 2]])

查看a和tensor的數據類型

#查看a和tensor的數據類型
a.dtype
tensor.dtype

#輸出
torch.int64
torch.float32

轉換a的數據類型

a = a.float()
a.dtype

#輸出
torch.float32

2、矩陣的乘法運算

tensor = torch.ones(3,5)
tensor

#輸出
tensor([[1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.]])

相乘

#一個2×3的矩陣乘以一個3×5的矩陣,得到一個2×5的矩陣
torch.matmul(a,tensor)

#輸出
tensor([[ 7.,  7.,  7.,  7.,  7.],
        [10., 10., 10., 10., 10.]])

2. 對數據的基本運算(數學運算)

定義三行兩列隨機整數

sample = torch.randint(1,10,(3,2))
#爲方便後續運算,轉化爲浮點數
sample = sample.float()
sample

#顯示輸出
tensor([[1., 3.],
        [4., 5.],
        [5., 8.]])

2.1 求和函數

torch.sum(sample)

#顯示輸出
tensor(26)

2.2 最大最小函數

torch.max(sample)
torch.min(sample)

#顯示輸出
tensor(8)
tensor(1)

2.3 求最值索引函數

注意索引位置從0開始

#求最小值的索引位置,數字從0開始
torch.argmin(sample)

#顯示輸出
tensor(0)
#求最大值的索引位置,數字從0開始
torch.argmax(sample)

#顯示輸出
tensor(5)

2.4 求平均值函數

#求平均值
torch.mean(sample)

#顯示輸出
tensor(4.3333)

2.4 求中位數函數

#求中位數
torch.median(sample)

#顯示輸出
tensor(4.)

2.5 求開方

#求開方
torch.sqrt(sample)

#顯示輸出
tensor([[1.0000, 1.7321],
        [2.0000, 2.2361],
        [2.2361, 2.8284]])

2.6 求二次方/高次方

#求平方
sample ** 2

#顯示輸出
tensor([[ 1.,  9.],
        [16., 25.],
        [25., 64.]])
#求高次方
sample ** 3

#顯示輸出
tensor([[  1.,  27.],
        [ 64., 125.],
        [125., 512.]])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章