# 【小白學PyTorch】10 pytorch常見運算詳解

## 1 矩陣與標量

import torch
a = torch.tensor([1,2])
print(a+1)
>>> tensor([2, 3])


## 2 哈達瑪積

a = torch.tensor([1,2])
b = torch.tensor([2,3])
print(a*b)
print(torch.mul(a,b))
>>> tensor([2, 6])
>>> tensor([2, 6])


a = torch.tensor([1.,2.])
b = torch.tensor([2.,3.])
print(a/b)
print(torch.div(a/b))
>>> tensor([0.5000, 0.6667])
>>> tensor([0.5000, 0.6667])


## 3 矩陣乘法

• torch.mm()
• torch.matmul()
• @，這個需要記憶，不然遇到這個可能會挺矇蔽的
a = torch.tensor([1.,2.])
b = torch.tensor([2.,3.]).view(1,2)
print(torch.mm(a, b))
print(torch.matmul(a, b))
print(a @ b)


tensor([[2., 3.],
[4., 6.]])
tensor([[2., 3.],
[4., 6.]])
tensor([[2., 3.],
[4., 6.]])


a = torch.rand((1,2,64,32))
b = torch.rand((1,2,32,64))
print(torch.matmul(a, b).shape)
>>> torch.Size([1, 2, 64, 64])


a = torch.rand((3,2,64,32))
b = torch.rand((1,2,32,64))
print(torch.matmul(a, b).shape)
>>> torch.Size([3, 2, 64, 64])


## 4 冪與開方

print('冪運算')
a = torch.tensor([1.,2.])
b = torch.tensor([2.,3.])
c1 = a ** b
c2 = torch.pow(a, b)
print(c1,c2)
>>> tensor([1., 8.]) tensor([1., 8.])


## 5 對數運算

pytorch中log是以e自然數爲底數的，然後log2和log10纔是以2和10爲底數的運算。

import numpy as np
print('對數運算')
a = torch.tensor([2,10,np.e])
print(torch.log(a))
print(torch.log2(a))
print(torch.log10(a))
>>> tensor([0.6931, 2.3026, 1.0000])
>>> tensor([1.0000, 3.3219, 1.4427])
>>> tensor([0.3010, 1.0000, 0.4343])


## 6 近似值運算

• .ceil() 向上取整
• .floor()向下取整
• .trunc()取整數
• .frac()取小數
• .round()四捨五入
a = torch.tensor(1.2345)
print(a.ceil())
>>>tensor(2.)
print(a.floor())
>>> tensor(1.)
print(a.trunc())
>>> tensor(1.)
print(a.frac())
>>> tensor(0.2345)
print(a.round())
>>> tensor(1.)


## 7 剪裁運算

a = torch.rand(5)
print(a)
print(a.clamp(0.3,0.7))


tensor([0.5271, 0.6924, 0.9919, 0.0095, 0.0340])
tensor([0.5271, 0.6924, 0.7000, 0.3000, 0.3000])