作者 | 磐石

編輯 | 安可

出品 | 磐創AI技術團隊

【引言】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 實際上是一個元組,因此它支持所有元組操作。

2. 運算

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+張量操作,包括置換,索引,切片,數學運算,線性代數,隨機數等等,被詳細描述在這裡

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

2. 將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)

腳本總運行時間:(0分6.338秒)

【寫在最後】:學習更多的機器學習、深度學習乾貨知識,請關注我們的微信公眾號:磐創AI。


推薦閱讀:
查看原文 >>
相关文章