首頁>技術>

本文學習資源《深度學習框架 PyTorch入門與實踐》,陳雲編著,電子工業出版社

一、 學習環境CentOS7二、安裝conda
wget https://repo.anaconda.com/archive/Anaconda3-2020.11-Linux-x86_64.shchmod +x Anaconda3-2020.11-Linux-x86_64.sh./Anaconda3-2020.11-Linux-x86_64.sh

按提示安裝即可。

三、安裝PyTorch包1. 新建一個conda虛擬環境
conda create -n pytorch python=3.7conda env listconda activate pytorch
2. 安裝PyTorch包
pip install   -i http://pypi.douban.com/simple/ --trusted-host=pypi.douban.com/simple torchvisionpip install --upgrade numpy
3. 測試
python>>> import torch as t

沒有報錯則安裝成功。

四、一些基本概念1. Tensor

Tensor是PyTorch中重要的資料結構,可以理解為一個高維陣列。表現形式可能是一個標量、一維陣列、二維陣列或更高維的陣列。Tensor和numpy的ndarrays類似,但Tensor可以使用GPU加速。

示例:
from __future__ import print_functionimport torch as t# 只分配空間,未執行初始化x = t.Tensor(5,4)print(x)

顯示結果:

隨機數初始化
from __future__ import print_functionimport torch as tx = t.rand(5,4)print(x)
顯示Tensor的形狀
print(x.size())
Tensor加法
from __future__ import print_functionimport torch as tx = t.rand(5,4)y = t.rand(5,4)print(x)print(y)print(x+y)

加法還可以寫成:

t.add(x,y)或result = t.Tensor(5,4)t.add(x,y,out=result) # 輸出到result變數
add_如果使用 y.add(x) , y不改變,返回一個新值。如果使用 y.add_(x) , 則y會改變。GPU運算支援
if t.cuda.is_available():    x = x.cuda()    y = y.cuda()    print(x+y)
2. Autogra 自動微積分

PyTorch的Autograd模組實現了微分運算。autograd.Variable是Autogra中的核心類,它內部封裝了Tensor。Tensor在被封裝為Variable後,可以呼叫它的.backward實現反向傳播,自動計算所有梯度。

Variable的資料結構如下:

import torchfrom torch.autograd import Variablea=Variable(torch.Tensor([1]),requires_grad=True) b=Variable(torch.Tensor([2]),requires_grad=True)c=Variable(torch.Tensor([3]),requires_grad=True)d=a+be=d+ce.backward()print(d.grad)     # 中間梯度值不儲存,為空print(a.grad_fn)  # 第一個節點的.grad_fn為空print(e.grad_fn)  # <AddBackward0 object at 0x7f88153d6250>

8
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • 第13天 | 16天搞定前端,CSS的動畫效果,酷