天天看點

Pytorch入門演練

【引言】Pytorch是一個基于Python的科學計算軟體包,有以下兩種定位:

可以使用多GPU加速的NumPy替代品

提供最大限度靈活性與速度的深度學習研究平台

一、入門

1.Tensors(張量)

Tensors(張量)類似于NumPy中的ndarray,另外它還可以使用GPU加速計算。

from__future__import print_function
importtorch           

構造一個未初始化的5x3矩陣:

x = torch.empty(5, 3)
print(x)           

輸出:

tensor([[-9.0198e-17,  4.5633e-41, -2.9021e-15],
       [ 4.5633e-41,  0.0000e+00,  0.0000e+00],
       [ 0.0000e+00,  0.0000e+00,  0.0000e+00],
       [ 0.0000e+00,  0.0000e+00,  0.0000e+00],
       [ 0.0000e+00,  0.0000e+00,  0.0000e+00]])           

構造一個随機初始化的矩陣:

x = torch.rand(5, 3)
print(x)           
tensor([[0.1525, 0.7689, 0.5664],
       [0.7688, 0.0039, 0.4129],
       [0.9979, 0.3479, 0.2767],
       [0.9580, 0.9492, 0.6265],
       [0.2716, 0.6627, 0.3248]])           

構造一個使用零填充、資料類型為long(長整型)的5X3矩陣:

x = torch.zeros(5, 3, dtype=torch.long)
print(x)           
tensor([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])           

直接用一組資料構造Tensor(張量):

x = torch.tensor([5.5, 3])
print(x)           
tensor([5.5000, 3.0000])           

或者根據現有的Tensor(張量)建立新的Tensor(張量)。除非使用者提供新值,否則這些方法将重用輸入張量的屬性,例如dtype:

x = x.new_ones(5, 3, dtype=torch.double)  # 使用new_* 方法設定次元
print(x)

x = torch.randn_like(x, dtype=torch.float)   # 重新設定資料類型
Print(x)            
tensor([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]], dtype=torch.float64)

tensor([[ 0.4228,  0.3279,  0.6367],
       [ 0.9233, -0.5232, -0.6494],
       [-0.1946,  1.7199, -0.1954],
       [ 0.1222,  0.7204, -1.3328],
       [ 0.1230, -0.5800,  0.4562]])           

輸出它的大小:

print(x.size())           
torch.Size([5, 3])           

【注意:torch.Size 實際上是一個元組,是以它支援所有元組操作。】

  1. 運算

    Tensor運算有多種文法。在下面的示例中,我們将先示例加法運算。

加法運算:文法1

y = torch.rand(5, 3)
print(x + y)           
tensor([[ 0.0732,  0.9384, -0.2489],
       [-0.6905,  2.1267,  3.0045],
       [ 0.6199,  0.4936, -0.0398],
       [-2.0623, -0.5140,  1.6162],
       [ 0.3189, -0.0327, -0.5353]])
           

加法運算:文法2

print(torch.add(x, y))           
tensor([[ 0.0732,  0.9384, -0.2489],
       [-0.6905,  2.1267,  3.0045],
       [ 0.6199,  0.4936, -0.0398],
       [-2.0623, -0.5140,  1.6162],
       [ 0.3189, -0.0327, -0.5353]])           

加法運算:使用輸出Tensor(張量)作為參數

result = torch.empty(5, 3)
torch.add(x, y, out=result)

print(result)           
tensor([[ 0.0732,  0.9384, -0.2489],
       [-0.6905,  2.1267,  3.0045],
       [ 0.6199,  0.4936, -0.0398],
       [-2.0623, -0.5140,  1.6162],
       [ 0.3189, -0.0327, -0.5353]])           

加法運算:内聯接

# adds x to y
y.add_(x)
print(y)           
tensor([[ 0.0732,  0.9384, -0.2489],
       [-0.6905,  2.1267,  3.0045],
       [ 0.6199,  0.4936, -0.0398],
       [-2.0623, -0.5140,  1.6162],
       [ 0.3189, -0.0327, -0.5353]])           

【注意:任何改變原張量實作内聯接的操作都是通過在後邊加_ 實作的。例如:x.copy_(y),x.t_(),将将改變x的值。】

你可以像在NumPy中一樣使用索引及其他所有華麗的功能。

print(x[:, 1])           
tensor([ 0.3279, -0.5232,  1.7199,  0.7204, -0.5800])           

Resizing(調整大小):如果要resize/reshape張量,可以使用torch.view:

x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)  # -1是推斷出來的

print(x.size(), y.size(), z.size())           
torch.Size([4, 4])  torch.Size([16])  torch.Size([2, 8])           

如果你有隻含一個元素的張量,可以用.item()擷取它的值作為Python數值

x = torch.randn(1)

print(x)

print(x.item())           
tensor([0.1550])

0.15495021641254425           

【延伸閱讀:100+張量操作,包括置換,索引,切片,數學運算,線性代數,随機數等等,被較長的描述在這裡

https://pytorch.org/docs/torch

)。】

二、NUMPY橋接器

将Torch Tensor轉換為NumPy array是一件輕而易舉的事(反之亦然)。Torch Tensor和NumPyarray共享其底層記憶體位置,更改一個将改變另一個。

1.将Torch Tensor轉換為NumPy array

a = torch.ones(5)

print(a)           
tensor([1., 1., 1., 1., 1.])

b = a.numpy()

print(b)           
[1. 1. 1. 1. 1.]           

了解numpyarray的值如何變化。

a.add_(1)

print(a)

print(b)           
tensor([2., 2., 2., 2., 2.])

[2. 2. 2. 2. 2.]
           
  1. 将NumPy array轉換為Torch Tensor

    了解如何自動地将np array更改為Torch Tensor

import numpy as np

a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)

print(a)
print(b)           
[2. 2. 2. 2. 2.]

tensor([2., 2., 2., 2., 2.], dtype=torch.float64)           

除了Char(字元型)Tensor之外,CPU上的所有Tensors都支援轉換為NumPy及傳回。

三、CUDA TENSORS(張量)

可以使用.to方法将張量移動到任何裝置上。

# 僅當CUDA可用的情況下運作這個cell 
# 我們用 ``torch.device`` 對象實作tensors在GPU上的寫入與讀出if torch.cuda.is_available():

   device = torch.device("cuda")          # 一個 CUDA 終端對象

   y = torch.ones_like(x, device=device)  # 直接在GUP上建立Tensor
   x = x.to(device)                # 或者直接使用字元串`.to("cuda")``
   z = x + y

   print(z)
   print(z.to("cpu", torch.double))     # `.to`` 也可以改變對象資料類型           
tensor([2.4519], device='cuda:0')

tensor([2.4519], dtype=torch.float64)           

原文釋出時間為:2018-12-19

本文作者:磐石

本文來自雲栖社群合作夥伴“

磐創AI

”,了解相關資訊可以關注“

xunixs”微信公衆号