深度学习--数学运算符

发布时间 2023-04-20 22:14:24作者: 林每天都要努力

深度学习--数学运算符

基础运算符

加减乘除

import torch

a=torch.randint(1,10,[2,2])
b=torch.randint(1,10,[2,2])
print(a)
#tensor([[9, 7],[5, 8]])
print(b)
#tensor([[2, 4],[1, 7]])

#加法 + torch.add(a,b)
a+b
#tensor([[11, 11],[ 6, 15]])
torch.add(a,b)
#tensor([[11, 11],[ 6, 15]])

#减法 - torch.sub(a,b)
a-b
#tensor([[7, 3],[4, 1]])
torch.sub(a,b)
#tensor([[7, 3],[4, 1]])

#乘法  * torch.mul(a,b)
a*b
#tensor([[18, 28], [ 5, 56]])
torch.mul(a,b)
#tensor([[18, 28], [ 5, 56]])

#除法 / torch.div(a,b)
a/b
#tensor([[4.5000, 1.7500],[5.0000, 1.1429]])
torch.div(a,b)
#tensor([[4.5000, 1.7500],[5.0000, 1.1429]])

矩阵乘法

#矩阵乘法   @  torch.matmul(a,b)

#torch.mm(a,b)  只能计算二维的矩阵乘法

a@b
#tensor([[25, 85],[18, 76]])
torch.matmul(a,b)
#tensor([[25, 85],[18, 76]])

乘方与开方

a=torch.full([2,2],3)
#tensor([[3, 3],[3, 3]])

##平方  a**n  torch.pow(a,n)   a的n次方
a**2
#tensor([[9, 9],[9, 9]])
torch.pow(a,2)
#tensor([[9, 9],[9, 9]])

#开方  torch.sqrt()  1/2      torch.rsqrt() -1/2  
torch.sqrt(a**2)
#tensor([[3, 3],[3, 3]])
torch.rsqrt(a**2)
#tensor([[0.3333, 0.3333],[0.3333, 0.3333]])

指数与对数

a=torch.ones(2,2)
#tensor([[1, 1],[1, 1]])

#指数函数  torch.exp()
torch.exp(a)
#tensor([[2.7183, 2.7183],[2.7183, 2.7183]])

#对数函数 torch.log()   默认底数为e  修改可以写为torch.log2()
torch.log2(a)
#tensor([[0., 0.],[0., 0.]])

小数运算

a=torch.tensor(3.14)
#tensor(3.1400)

#向上取整torch.ceil()    向下取整torch.floor()   四舍五入取整torch.round()
torch.ceil(a) 
#tensor(4.)
torch.floor(a) 
#tensor(3.)
torch.round(a)
#tensor(3.)

#整数部分torch.trunc()   小数部分 torch.frac()
torch.trunc(a) 
#tensor(3.)
torch.frac(a)
#tensor(0.1400)

其他运算

#clamp()函数
#a.clamp(x)    在a中 ,所有小于x的数都置为x
#a.clamp(x,y)  在a中,所有小于x的数都置为x,所有大于y的数都置为y

#a.max() 取其中的最大值
#a.median() 取其中的中位数