一、Pytorch安装
安装cuda和cudnn,例如cuda10,cudnn7.5
官网下载torch:https://pytorch.org/ 选择下载相应版本的torch 和torchvision的whl文件
使用pip install whl_dir安装torch,并且同时安装torchvision
二、初步使用pytorch
# -*- coding:utf-8 -*- __author__ = ‘Leo.Z‘ import torch import time # 查看torch版本 print(torch.__version__) # 定义矩阵a和b,随机值填充 a = torch.randn(10000, 1000) b = torch.randn(1000, 2000) # 记录开始时间 t0 = time.time() # 计算矩阵乘法 c = torch.matmul(a, b) # 记录结束时间 t1 = time.time() # 打印结果和运行时间 print(a.device, t1 - t0, c.norm(2)) # 这里的c.norm(2)是计算c的L2范数 # 使用GPU设备 device = torch.device(‘cuda‘) # 将ab搬到GPU a = a.to(device) b = b.to(device) # 运行,并记录运行时间 t0 = time.time() c = torch.matmul(a, b) t1 = time.time() # 打印在GPU上运行所需时间 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))
运行结果如下:
1.1.0 cpu 0.14660906791687012 tensor(141129.3906) cuda:0 0.19049072265625 tensor(141533.1250, device=‘cuda:0‘) cuda:0 0.006981372833251953 tensor(141533.1250, device=‘cuda:0‘)
我们发现,两次在GPU上运行的时间不同,第一次时间甚至超过CPU运行时间,这是因为第一次运行有初始化GPU运行环境的时间开销。
三、自动求导
# -*- coding:utf-8 -*- __author__ = ‘Leo.Z‘ import torch # 定义a b c x的值,abc指定为需要求导requires_grad=True x = torch.tensor(2.) a = torch.tensor(1., requires_grad=True) b = torch.tensor(2., requires_grad=True) c = torch.tensor(3., requires_grad=True) # 定义y函数 y = a * x ** 2 + b * x + c; # 使用autograd.grad自定求导 grads = torch.autograd.grad(y, [a, b, c]) # 打印abc分别的导数值(带入x的值) print(‘after‘, grads[0],grads[1],grads[2])
原文:https://www.cnblogs.com/leokale-zz/p/11258329.html