PyTorch簡介
PyTorch 是 Torch 在 Python 上的衍生. 因為 Torch 是一個使用 Lua 語言的神經網絡庫,由於 PyTorch 采用了動態計算圖(dynamic computational graph)結構,PyTorch 有一種獨特的神經網絡構建方法:使用和重放 tape recorder。而不是大多數開源框架,比如 TensorFlow、Caffe、CNTK、Theano 等采用的靜態計算圖。 使用 PyTorch,通過一種我們稱之為「Reverse-mode auto-differentiation(反向模式自動微分)」的技術,你可以零延遲或零成本地任意改變你的網絡的行為。
torch 產生的 tensor 放在 GPU 中加速運算 (前提是你有合適的 GPU), 就像 Numpy 會把 array 放在 CPU 中加速運算
進一步說,torch是一個支持 GPU 的 Tensor 庫,如果你使用 numpy,那么你就使用過 Tensor(即 ndarray)。PyTorch 提供了支持 CPU 和 GPU 的 Tensor.
PyTorch組成
PyTorch由4個主要包裝組成:
1.torch:類似於Numpy的通用數組庫,可以在將張量類型轉換為(torch.cuda.TensorFloat)並在GPU上進行計算。
2.torch.autograd:用於構建計算圖形並自動獲取漸變的包
3.torch.nn:具有共同層和成本函數的神經網絡庫
4.torch.optim:具有通用優化算法(如SGD,Adam等)的優化包
PyTorch簡單使用
torch 做的和 numpy 有很好的兼容. 這樣就能自由地轉換numpy array 和 torch tensor
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import torch import numpy as np np_data = np.arange(6).reshape((2, 3)) #將numpy轉換為torch tensor torch_data = torch.from_numpy(np_data) #將torch tensor轉換為tensor tensor2array = torch_data.numpy() print ( '\nnumpy array:', np_data, # [[0 1 2], [3 4 5]] '\ntorch tensor:', torch_data, # 0 1 2 \n 3 4 5 [torch.LongTensor of size 2x3] '\ntensor to array:', tensor2array, # [[0 1 2], [3 4 5]] )
torch做數學運算
#計算絕對值 data = [-1, -2, 1, 2] #轉換成32位浮點tensor tensor = torch.FloatTensor(data) print( '\nabs', '\nnumpy: ', np.abs(data), # [1 2 1 2] '\ntorch: ', torch.abs(tensor) # 1 2 1 2 ) # sin 三角函數 sin print( '\nsin', '\nnumpy: ', np.sin(data), # [-0.84147098 -0.90929743 0.84147098 0.90929743] '\ntorch: ', torch.sin(tensor) # [-0.8415 -0.9093 0.8415 0.9093] ) # mean 均值 print( '\nmean', '\nnumpy: ', np.mean(data), # 0.0 '\ntorch: ', torch.mean(tensor) # 0.0 )
torch做矩陣運算
#矩陣運算 #矩陣點乘 data = [[1,2], [3,4]] tensor = torch.FloatTensor(data) # 轉換成32位浮點 tensor print( '\nmatrix multiplication (matmul)', '\nnumpy: ', np.matmul(data, data), # [[7, 10], [15, 22]] '\ntorch: ', torch.mm(tensor, tensor) # [[7, 10], [15, 22]] )
torch中的變量
先定義一個變量
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import torch from torch.autograd import Variable tensor = torch.FloatTensor([[1, 2],[3, 4]]) #在BP的時候,pytorch是將Variable的梯度放在Variable對象中的, # 我們隨時都可以使用Variable.grad得到對應Variable的grad。 # 剛創建Variable的時候,它的grad屬性是初始化為0.0的。 #需要求導的話,requires_grad=True屬性是必須的。 variable = Variable(tensor, requires_grad = True) print tensor """ output: 1 2 3 4 [torch.FloatTensor of size 2x2] """ #多了一個Variable containing: print variable """ output: Variable containing: 1 2 3 4 [torch.FloatTensor of size 2x2] """
Variable 計算時, 會一步步搭建着一個龐大的系統, 叫做計算圖, computational graph. 這個圖是將所有的計算步驟 (節點) 都連接起來, 最后進行誤差反向傳遞的時候, 一次性將所有 variable 里面的修改幅度 (梯度) 都計算出來
#模擬v_out 反向誤差 # v_out = 1/4 * sum(variable*variable) 這是計算圖中的 v_out 計算步驟 # 針對於 v_out 的梯度就是, d(v_out)/d(variable) = 1/4*2*variable = variable/2 v_out.backward() print variable.grad #獲取variable的數據 print variable """ Variable containing: 1 2 3 4 [torch.FloatTensor of size 2x2] """ print variable.data """ 1 2 3 4 [torch.FloatTensor of size 2x2] """ print variable.data.numpy() """ [[ 1. 2.] [ 3. 4.]] """