1. 程式人生 > 程式設計 >Pytorch1.5.1版本安裝的方法步驟

Pytorch1.5.1版本安裝的方法步驟

檢視自己cuda版本,

在這裡插入圖片描述

我的cuda是11版本了,所以可以安裝11版本以下的任何版本。

進入pytorch官網

官網網址:https://pytorch.org/

在這裡插入圖片描述

2020年11月19號,更新

最簡單的是直接按官網給的Run this Command命令,直接安裝,如下:

conda install pytorch torchvision torchaudio cudatoolkit=10.2 -c pytorch

解釋:-c pytorch,意思是從pytorch網站下載,速度感人,有辦法的那就方便多了。

按照上面圖這樣選擇,安裝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,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,b)
t2 = time.time()
print(a.device,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好理解,適合人類思維,功能也都全。

到此這篇關於Pytorch1.5.1版本安裝的方法步驟的文章就介紹到這了,更多相關Pytorch1.5.1版本安裝內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!