pytorch-计算

这篇博客详细介绍了PyTorch中的基本数学运算,包括加减乘除、矩阵乘法、指数与对数、取整与取余等操作,并通过示例展示了这些操作的使用方法和结果。此外,还探讨了如何进行数值比较和数据处理,如四舍五入、截断和归一化。
摘要由CSDN通过智能技术生成

imnport torch
a=torch.rand(3,4)
a
b=torch.ran(4)
b
a+b
torch.add(a,b)
torch.sub(a,b)
torch.mul(a,b)
torch.div(a,b)

结果:
在这里插入图片描述
在这里插入图片描述

torch.all(torch.eq(a+b),torch.add(a,b))
torch.all(torch.eq(a-b),torch.sub(a,b))
torch.all(torch.eq(a*b),torch.mul(a,b))
torch.all(torch.eq(a/b),torch.div(a,b))

结果:
在这里插入图片描述

a=torch.tensor([[1.0,2.0],[3.0,4.0]])
b=torch.ones(2,2)
torch.mm(a,b)
torch.matmul(a,b)
a@b
a=torch.rand(4,784)
x=torch.rand(4,784)
w=torch.rand(4,784)
a.shape,x.shape,w.shape
(x@w.t()).shape

结果:
在这里插入图片描述

a=torch.rand(4,3,28,64)
b=torch.rand(4,3,64,32)
a.shape,b.shape
torch.mm(a,b).shape#会报错,must be a mutrix。说明mm适合2d
那怎么解决这个问题
torch.matmul(a,b).shape#matmul适合4d

在这里插入图片描述

a=torch.full([2,2],3)
a
a=torch.full([2,2],3.0)
a
a**2
a.pow(2)#也是平方
aa=a.pow(2)
aa.sqrt()#平方根
aa.rsqrt()#对每个元素取平方根后再取倒数
aa**0.5
##这些都是求平方根

结果:
在这里插入图片描述

a=torch.exp(rotch.ones(2,2))#求指数
a
torch.log(a)#求指数的底
a = torch.tensor(3.14)
a
a.floor()#取比我小整数
a.ceil()#向上取整(比我大的整数)
a.chunc()#取得整数
a.frac()#取小数

结果:
在这里插入图片描述

a=torch.tensor(3.5)
a.round()#四舍五入
grad = torch.rand(2,3)*15
grad
grad.max()
grad.min()
grad.median()#中位数
grad.clamp(10)#按10的概率初始化,小于10的变成10
grad.clamp(0,10)#按10的概率初始化,大于10小于0的变成10
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青灯有味是儿时

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值