[PyTorch入門之60分鐘入門閃擊戰]之入門

深度學習60分鐘入門

來源於這裏html

本文目標:python

  • 在高層次上理解PyTorch的Tensor庫和神經網絡
  • 訓練一個小型的圖形分類神經網絡

本文示例運行在ipython中。網絡

什麼是PyTorch

PyTorch是由Torch7團隊開發的,從名字就能夠看出,它跟Torch的不一樣之處在於PyTorch使用了Python做爲開發語言。所謂「Python first」,一樣說明它是一個以Python優先的深度學習框架,不只可以實現強大的GPU加速,同時還支持動態神經網絡。框架

PyTorch既能夠看作加入了GPU支持的numpy,同時也能夠當作一個擁有自動求導功能的強大的深度神經網絡。學習

入門

Tensor(向量)

Tensor與NumPy的ndarras相似,此外Tensor還可用於GPU加速運算。this

from __future__ import print_function
import torch

建立一個爲初始化的5x3的矩陣:code

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

輸出:htm

tensor([[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],
        [1.4013e-45, 0.0000e+00, 0.0000e+00],
        [0.0000e+00, 0.0000e+00, 0.0000e+00]])

建立一個隨機初始化的矩陣:索引

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

輸出:ip

tensor([[0.1633, 0.3415, 0.6341],
        [0.9496, 0.6820, 0.7831],
        [0.2327, 0.0311, 0.6763],
        [0.5513, 0.6381, 0.1251],
        [0.4553, 0.0795, 0.5904]])

建立一個由0填充,數據類型爲long的矩陣:

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。除非用戶提供新值,不然輸入的Tensor的屬性將被複用:

x = x.new_ones(5,3,dtype=torch.double)
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([[-1.2001, -0.3921,  1.1179],
        [-1.5787,  0.4377, -0.2543],
        [-0.2502, -0.4977,  1.1637],
        [ 0.4006,  1.3536,  0.6846],
        [-0.1242,  0.5019, -0.9795]])

獲取大小:

print(x.size())

輸出:

torch.Szie([5,3])

troch.Size實際是一個元組,因此支持元組的全部操做。

Operations(操做)

數學運算有多種語法。在下面的例子中,咱們已加法運算爲例。

加法:語法 1

y = torch.rand(5,3)
print('y = ',y)
print('x + y = ',x+y)

輸出:

y =  tensor([[0.2520, 0.5938, 0.5229],
        [0.1242, 0.9339, 0.4859],
        [0.3769, 0.4005, 0.2906],
        [0.4649, 0.2526, 0.7136],
        [0.0941, 0.9550, 0.4462]])
x+y =  tensor([[-0.9482,  0.2017,  1.6408],
        [-1.4545,  1.3715,  0.2317],
        [ 0.1268, -0.0973,  1.4543],
        [ 0.8655,  1.6062,  1.3982],
        [-0.0301,  1.4569, -0.5333]])

加法:語法 2

print('x+y = ',torch.add(x,y))

輸出:

x+y =  tensor([[-0.9482,  0.2017,  1.6408],
        [-1.4545,  1.3715,  0.2317],
        [ 0.1268, -0.0973,  1.4543],
        [ 0.8655,  1.6062,  1.3982],
        [-0.0301,  1.4569, -0.5333]])

加法:提供一個輸出的Tensor做爲參數:

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

輸出:

tensor([[-0.9482,  0.2017,  1.6408],
        [-1.4545,  1.3715,  0.2317],
        [ 0.1268, -0.0973,  1.4543],
        [ 0.8655,  1.6062,  1.3982],
        [-0.0301,  1.4569, -0.5333]])

加法:替代

y.add_(x)
print(y)

輸出:

tensor([[-0.9482,  0.2017,  1.6408],
        [-1.4545,  1.3715,  0.2317],
        [ 0.1268, -0.0973,  1.4543],
        [ 0.8655,  1.6062,  1.3982],
        [-0.0301,  1.4569, -0.5333]])

任何替換原Tensor的操做都是以「_」爲後綴的。例如 x.copy_(y),x.t_(),都會改變x

你可使用標準的NumPy索引來獲取元素:

print(x)
print(x[:,1])

輸出:

tensor([[-1.2001, -0.3921,  1.1179],
        [-1.5787,  0.4377, -0.2543],
        [-0.2502, -0.4977,  1.1637],
        [ 0.4006,  1.3536,  0.6846],
        [-0.1242,  0.5019, -0.9795]])
tensor([-0.3921,  0.4377, -0.4977,  1.3536,  0.5019])

重置大小:若是你想改變Tensor的大小或者形狀,你可使用torch.view

x = torch.rand(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])

若是你的Tensor只有一個元素,那麼可使用.item()獲取到Python數字類型的值:

x = torch.randn(1)
print(x)
print(x.item())

輸出:

tensor([0.6787])
0.678749144077301

進階閱讀:

100+向量操做,包括轉置、索引、切片、數學運算、線性代數、隨機數等,詳見這裏

NumPy Bridge

將一個Torch Tensor轉換成NumPy array是很是簡單的,反之亦然。轉換後的Torch Tensor和NumPy array共享底層的內存地址(若是Torch Tensor在CPU上),即修改一個,另外一個也會改變。

將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.]

tensor值改變,numpy array的值也改變:

a.add_(1)
print(a)
print(b)

輸出:

tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]
將NumPy array 轉Torch tensor

接下來展現如何將NumPy 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)

除了CharTensor外,全部CPU上的Tensor都支持轉成NumPy array並返回。

CUDA Tensors

Tensors可使用.to方法移動到任何設備上。

# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
    device = torch.device("cuda")          # a CUDA device object
    y = torch.ones_like(x, device=device)  # directly create a tensor on GPU
    x = x.to(device)                       # or just use strings ``.to("cuda")``
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))       # ``.to`` can also change dtype together!

輸出:

tensor([2.0897], device='cuda:0')
tensor([2.0897], dtype=torch.float64)
相關文章
相關標籤/搜索