当前位置: 移动技术网 > IT编程>网页制作>HTML > Pytorch1.5.1版本安装

Pytorch1.5.1版本安装

2020年07月14日  | 移动技术网IT编程  | 我要评论

查看自己cuda版本,

在这里插入图片描述
我的cuda是11版本了,所以可以安装11版本以下的任何版本。

进入pytorch官网

https://pytorch.org/
在这里插入图片描述
按照上面图这样选择,安装pytorch有GPU加速的版本,安装命令可以改下,后面加个豆瓣源,这样下载速度快些。

pip install torch===1.5.1 torchvision===0.6.1 -f https://download.pytorch.org/whl/torch_stable.html -i https://pypi.douban.com/simple

或者直接用conda安装,去掉后面的 -c pytorch

conda install pytorch torchvision cudatoolkit=10.2 

如果上面方法都下载慢,那就按下面方法来。(适用于win版本,Linux的可以返回上一层寻找对应的版本)
先进清华源https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/win-64/?C=M&O=D
下载对应pytorch版本,我的是Python3.7,需要PyTorch-gpu版本,cuda需要10.2,找到对应的bz2文件下载,如图
在这里插入图片描述
还要下载对应的torchvision===0.6.1,如图
在这里插入图片描述
下载好就在命令行进入你下载的路径目录里面安装,并输入下面代码进行离线安装。

conda install --offline 对应的安装名字

安装完后还要安装cudatoolkit=10.2

conda install cudatoolkit=10.2

然后运行测试代码:

# TEST
import torch
from torch.backends import cudnn

x = torch.Tensor([1.0])
xx = x.cuda()
print(torch.__version__)
print(torch.version.cuda)
print(torch.cuda.is_available())
print(xx)
print(cudnn.is_acceptable(xx))

结果:

1.5.1
10.2
True
tensor([1.], device='cuda:0')
True

安装成功!

GPU加速代码

import torch
import time

print(torch.__version__)
print(torch.cuda.is_available())

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))

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)  # 矩阵乘法
t2 = time.time()
print(a.device, t2 - t0, c.norm(2))

t0 = time.time()
c = torch.matmul(a, b)
t2 = time.time()
print(a.device, t2 - t0, c.norm(2))

结果:

1.5.1
True
cpu 0.13901472091674805 tensor(140929.9688)
cpu 0.16696977615356445 tensor(140929.9688)
cuda:0 0.22500324249267578 tensor(141330.6875, device='cuda:0')
cuda:0 0.003974437713623047 tensor(141330.6875, device='cuda:0')

运行两次是cuda有个预热的过程,第二次的时间明显减少了。和CPU相比,更快。

自动求导

代码:

import torch
from 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

print('before:', a.grad, b.grad, c.grad)
grads = autograd.grad(y, [a, b, c])
print('after :', grads[0], grads[1], grads[2])

结果:

before: None None None
after : tensor(2.) tensor(1.) tensor(1.)

可以看出pytorch比TensorFlow1.X好理解,适合人类思维,功能也都全。

本文地址:https://blog.csdn.net/weixin_45092662/article/details/107299953

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网