pytorch-数学运算

四则运算

加 减 乘 除

add+
sub-
mul*
div/
a=torch.rand(3,4)
b=torch.rand(4)
a,b
'''
(tensor([[0.2384, 0.5022, 0.7100, 0.0400],
         [0.1716, 0.0894, 0.0795, 0.1456],
         [0.7635, 0.9423, 0.7649, 0.3379]]),
 tensor([0.8526, 0.8296, 0.1845, 0.7922]))'''
#加
torch.add(a,b)
a+b

#减
torch.sub(a,b)
a-b
torch.all(torch.eq(a-b,torch.sub(a,b)))
#True

#乘
a*b
torch.mul(a,b)

#除
a/b
torch.div(a,b)

矩阵相乘

matmul

a=torch.tensor([[3.,3.],[3.,3.]])
b=torch.ones(2,2)

torch.mm(a,b)#数据类型Long
torch.matmul(a,b)
a@b

维度超过2时,mm就不可用了

维度超过2时,用matmul用后两维做相乘
matmul维度要匹配,虽然只用后两个乘

a=torch.rand(4,3,28,64)
b=torch.rand(4,3,64,32)
'''RuntimeError                              Traceback (most recent call last)
Input In [41], in <cell line: 1>()
----> 1 torch.mm(a,b).shape

RuntimeError: self must be a matrix'''

torch.matmul(a,b).shape
#torch.Size([4, 3, 28, 32])

b=torch.rand(4,64,32)
torch.matmul(a,b).shape#维度要匹配,虽然只用后两个乘
'''
RuntimeError                              Traceback (most recent call last)
Input In [46], in <cell line: 2>()
      1 b=torch.rand(4,64,32)
----> 2 torch.matmul(a,b).shape

RuntimeError: The size of tensor a (3) must match the size of tensor b (4) at non-singleton dimension 1'''

幂运算

指数:pow()
平方根:sqrt()
平方根的倒数:rsqrt()

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

a**2
a.pow(2)

aa=a**2
#平方根
aa.sqrt()
aa**0.5#1/2的幂

#立方根
aa.rsqrt()
#aa**(1/3)

对数

a=torch.exp(torch.ones(2,2))#e的次方

torch.log(a)#lna

近似

torch.floor()向下取整
torch.ceil()向上取整
torch.trunc()拆分后取整数部分
torch.frac()拆分后取小数部分
torch.floor()向下取整
#向上取整
a=torch.tensor(3.14)
a.ceil()#tensor(4.)

#向下取整
a.floor()#(tensor(3.),)

#四舍五入
a.round()#tensor(3.)

#取整数部分
a.trunc()#tensor(3.)

#取小数部分
a.frac()#tensor(0.1400)

裁剪

grad=torch.rand(2,3)*15
grad
'''
tensor([[ 6.9523,  0.3185, 14.4829],
        [ 2.2099, 13.3388,  6.6735]])'''
grad.max()#tensor(14.4829)

#取最小
grad.min()#tensor(0.3185)

#取中位数
grad.median()#tensor(6.6735)

#最小值限定为10,<10,都改为10
grad.clamp(10)
'''
tensor([[10.0000, 10.0000, 14.4829],
        [10.0000, 13.3388, 10.0000]])
'''
grad.clamp(0,10)#最小值限定0,最大值限定10
'''
tensor([[ 6.9523,  0.3185, 10.0000],
        [ 2.2099, 10.0000,  6.6735]])
'''
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值