赞
踩
在处理大数据时在cpu和gpu上分别进行矩阵运算
import torch import time print(torch.__version__) print(torch.cuda.is_available()) #俩矩阵 a=torch.rand(10000,1000) b=torch.rand(1000,2000) #cpu测试时间 t0=time.time() c=torch.matmul(a,b) t1=time.time() print(a.device,t1-t0,c.norm(2)) #gpu测试时间 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)) #再次测试 t0=time.time() c=torch.matmul(a,b) t1=time.time() print(a.device,t1-t0,c.norm(2))
可以发现第一次用cuda运行居然比cpu的要慢,但是第二次却快非常多。原因是第一遍需要进行gpu环境的初始化,是需要占用一些时间的。第二次就非常的真实。
torch.tensor张量可看这篇:https://www.jianshu.com/p/5ae644748f21/
在机器学习中就是神经网络反向传播的时候要更新参数,这时需要对其求偏导,也就是“梯度”
import torch
from torch import autograd
#对abcx分别初始化赋值
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
# 对a,b,c分别求偏导
print('before:',a.grad,b.grad,c.grad)
grads=autograd.grad(y,[a,b,c])
print('after: ',grads[0],grads[1],grads[2])
运行结果可以发现在调用autograd之前并没有求导。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。