1. 程式人生 > 程式設計 >Pytorch環境搭建與基本語法

Pytorch環境搭建與基本語法

來源 |OpenCV學堂

作者 |gloomyfish

基本思路選擇

以前我用過Caffe,用過tensorflow,最近一直在用pytorch感覺特別好用。所以打算寫點我學習的過程跟經驗,如果你是一個pytorch的高手自然可以忽略,如果你也打算學習pytorch框架,那就跟我一起學習吧,所謂獨學而無友,孤陋而寡聞!

pytorch安裝

01

演示系統環境

  • Windows10
  • Pytorch1.4
  • CUDA10.0
  • VS2015
  • Python3.6.5

CPU版本

install pytorch torchvision cpuonly -c pytorch

GPU版本

install pytorch torchvision cudatoolkit=10.0 -c pytorch

測試安裝是否正常,CUDA支援正常

Pytorch環境搭建與基本語法

測試結果一切正常!

安裝的時候你還可以更直接點

pip install pytorch torchvision

就好啦!我知道很多人喜歡用各種python的工具跟IDE做開發,那些都是個人愛好,喜歡就好,但是千萬彆強迫別人跟你一樣!有IDE強迫症!我從開始學習python就一直用pycharm!千萬別問我好用不好用,方便不方便!覺得適合自己即可。

Pytorch基本語法演示

02

演示了pytorch中基本常量、變數、矩陣操作、CUDA呼叫,numpy與tensor轉化,維度轉化,自動梯度等基本知識。程式碼如下:

from __future__ import print_function
import torch
import numpy as np

print(torch.__version__)

# 定義矩陣
x = torch.empty(2,2)
print(x)

# 定義隨機初始化矩陣
x = torch.randn(2,2)
print(x)

# 定義初始化為零
x = torch.zeros(3,3)
print(x)

# 定義資料為tensor
x = torch.tensor([5.1,2.,3.,1.])
print(x)

# 操作
a = torch.tensor([1.,4.,5.,6.,7.,8.])
b = torch.tensor([11.,12.,13.,14.,15.,16.,17.,18.])
c = a.add(b)
print(c)

# 維度變換 2x4
a = a.view(-1,4)
b = b.view(-1,4)
c = torch.add(a,b)
print(c,a.size(),b.size())

# torch to numpy and visa
na = a.numpy()
nb = b.numpy()
print("\na =",na,"\nb =",nb)

# 操作
d = np.array([21.,22.,23.,24.,25.,26.,27.,28.],dtype=np.float32)
print(d.reshape(2,4))
d = torch.from_numpy(d.reshape(2,4))
sum = torch.sub(c,d)
print(sum,"\n sum = ",sum.size())

# using CUDA
if torch.cuda.is_available():
 result = d.cuda() + c.cuda()
 print("\n result = ",result)

# 自動梯度
x = torch.randn(1,5,requires_grad=True)
y = torch.randn(5,3,requires_grad=True)
z = torch.randn(3,1,requires_grad=True)
print("\nx=",x,"\ny=",y,"\nz=",z)
xy = torch.matmul(x,y)
xyz = torch.matmul(xy,z)
xyz.backward()
print(x.grad,y.grad,z.grad)

執行輸出結果:

1.4.0
tensor([[0.,0.],
[0.,0.]])
tensor([[-0.4624,-1.1495],
[ 1.9408,-0.1796]])
tensor([[0.,0.,0.]])
tensor([5.1000,2.0000,3.0000,1.0000])
tensor([12.,18.,20.,26.])
tensor([[12.,18.],
[20.,26.]]) torch.Size([2,4]) torch.Size([2,4])

a = [[1. 2. 3. 4.]
[5. 6. 7. 8.]]
b = [[11. 12. 13. 14.]
[15. 16. 17. 18.]]
[[21. 22. 23. 24.]

[25. 26. 27. 28.]]
tensor([[-9.,-8.,-7.,-6.],
[-5.,-4.,-3.,-2.]])
sum = torch.Size([2,4])

result = tensor([[33.,36.,39.,42.],
[45.,48.,51.,54.]],device='cuda:0')

x= tensor([[ 0.3029,-0.4030,-0.9148,-0.9237,0.7549]],requires_grad=True)
y= tensor([[-0.9032,-0.4092,-0.0682],
[ 0.3689,-0.9655,-0.1346],
[ 1.5101,1.4418,0.1058],
[ 1.0259,-1.6011,0.4881],
[-0.3989,0.9156,-1.6290]],requires_grad=True)
z= tensor([[ 1.4343],
[ 2.2974],
[-0.0864]],requires_grad=True)
tensor([[-2.2298,-1.6776,5.4691,-2.2492,1.6721]]) tensor([[ 0.4344,0.6959,-0.0262],
[-0.5781,-0.9260,0.0348],
[-1.3121,-2.1017,0.0790],
[-1.3249,-2.1222,0.0798],
[ 1.0827,1.7342,-0.0652]]) tensor([[-3.0524],
[ 1.1164],
[-1.7437]])

總結

到此這篇關於Pytorch–環境搭建與基本語法的文章就介紹到這了,更多相關Pytorch–環境搭建與基本語法內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!