pytorch:数学运算、近似值、clamp

import torch

±*/

  • 维度不同的时候会broadcast
  • element-wise
a = torch.ones(2,2)
b = torch.tensor(4)
print(a + b) #用到了broadcast
print(a.add(b))
print(torch.add(a,b))
tensor([[5., 5.],
        [5., 5.]])
tensor([[5., 5.],
        [5., 5.]])
tensor([[5., 5.],
        [5., 5.]])
print(a/b)
print(torch.all(torch.eq(a/b,a.div(b))))
print(torch.equal(a/b,a.div(b))) 
#ps:torch.eq(a,b) 逐一比较a,b中的元素是否一样,一样返回True 否则返回False
#torch.all() 如果括号里面的元素全部是True(ps:必须是torch形式的bool)则返回True,否则返回False
#torch.equal(a,b),逐一比较a,b对应元素是否一样,如果全部都对应相同,则返回true,否则返回false
tensor([[0.2500, 0.2500],
        [0.2500, 0.2500]])
tensor(True)
True
print(a*b)
print(torch.all(torch.eq(a*b,a.mul(b))))
tensor([[4., 4.],
        [4., 4.]])
tensor(True)
print(a-b)
print(torch.all(torch.eq(a-b,a.sub(b))))
tensor([[-3., -3.],
        [-3., -3.]])
tensor(True)

矩阵的乘法

a = torch.ones(2,3)
b = torch.ones(3,2)+1
print(a.mm(b))  #mm只适用于2d (虽然但是,我们一般都只会用到2d...)
print(a.matmul(b)) #matmul高纬度也适用
tensor([[6., 6.],
        [6., 6.]])
tensor([[6., 6.],
        [6., 6.]])

次方

  • element-wise
a = torch.full([2,3],4)
a.pow(2)
tensor([[16., 16., 16.],
        [16., 16., 16.]])
b = torch.full([3,4],9)
b**(0.5)
tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])
c = torch.ones(2,2)
torch.exp(c)
tensor([[2.7183, 2.7183],
        [2.7183, 2.7183]])
torch.log(c) #log(10,1) = 0
tensor([[0., 0.],
        [0., 0.]])

近似值

a = torch.tensor(-3.1415926)
print(torch.floor(a)) #不超过原数的最大整数 
print(torch.ceil(a))  #大于原数的最小整数
print(torch.trunc(a)) #截取整数部分 
print(torch.frac(a))  #截取小数部分
print(torch.round(a)) #四舍五入(最后加正负号)
tensor(-4.)
tensor(-3.)
tensor(-3.)
tensor(-0.1416)
tensor(-3.)

clamp

a = torch.rand(3,3)*10
a
tensor([[5.3887, 0.5297, 2.0162],
        [9.9030, 0.1943, 5.6819],
        [5.6103, 3.4774, 8.9113]])
a.clamp(1,6) #在[1,6]范围内的返回原值,小于1的返回1,大于6的返回6 若括号中只填一个数,默认为lower-bound
tensor([[5.3887, 1.0000, 2.0162],
        [6.0000, 1.0000, 5.6819],
        [5.6103, 3.4774, 6.0000]])
发布了43 篇原创文章 · 获赞 1 · 访问量 756

猜你喜欢

转载自blog.csdn.net/weixin_41391619/article/details/104699741
今日推荐