pyTorch框架常用功能

1.用于GPU加速

        众所周知,在进行运算的时候,运算初期CPU是优于GPU的,但随着时间和数据的不断增加,GPU运算的优势就无限放大,因此GPU也广泛用于机器学子中。话不多说,直接上代码:

#GPU加速
import torch
import time
print(torch.__version__)
print(torch.cuda.is_available())

#a矩阵行列为10000,1000
a = torch.randn(10000,1000)
b = torch.randn(1000,2000)

#t0:开始时刻,t1:结束时刻,matmul:cpu模式矩阵乘法
t0 = time.time()
c = torch.matmul(a,b)
t1 = time.time()
print(a.device,t1-t0,c.norm(2))

device = torch.device('cuda')
a = a.to(device)
b = b.to(device)

t0 = time.time()
c = torch.matmul(a,b)
t1 = time.time()
print(a.device,t1-t0,c.norm(2))
#在计算一次,因为第一次使用cuda会有加载时间,导致不准确
t0 = time.time()
c = torch.matmul(a,b)
t1 = time.time()
print(a.device,t1-t0,c.norm(2))

下图为运算结果:在这里插入图片描述
        由上图可以看出,再去除cuda首次加载时间后,GPU运算时间大大小于CPU运算时间。

2.用于自动求导

        y=a^2x+bx+c这个函数,求当x=1时的导数,分别为y对a,y对b,y对c,结果为2a,1,1。让我们来看代码:

#自动求导
import torch
ftom torch import autograd

x = torch.tensor(1.)
a = torch.tensor(1.,requires_grad=True)
b = torch.tensor(2.,requires_grad=True)
c = torch.tensor(3.,requires_grad=True)

y = a**2*x+b*x+c

#求导之前,abc的梯度
print('before:',a.grad,b.grad,c.grad)
grads = autograd.grad(y,[a,b,c])
print('after:',grads[0],grads[1],grads[2])

给x初始值为1,a,b,c分别为1,2,3。
在这里插入图片描述
        由上图可知,得到的结果为2,1,1,因为我们初值设为1,如果为a则和预期一样。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

清晨的芒果

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

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

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

打赏作者

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

抵扣说明:

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

余额充值