DEEP LEARNING WITH PYTORCH: A 60 MINUTE BLITZ | TENSORS

Tensor是一種特殊的數據結構,非常類似於數組和矩陣。在PyTorch中,我們使用tensor編碼模型的輸入和輸出,以及模型的參數。
Tensor類似於Numpy的數組,除了tensor可以在GPUs或其它特殊的硬件上運行以加速運算。如果熟悉ndarray,那麼你也會熟悉Tensor API。如果不是,跟隨此快速API上手。

import torch
import numpy as np

Tensor 初始化

Tensor可以通過多種途徑初始化。看看下面的例子:

直接從數據中初始化

Tensor可以直接從數據中初始化。數據類型是自動推斷的。

data = [[1, 2], [3, 4]]
x_data = troch.tensor(data)

從數組中初始化

Tensor可以由NumPy數組創建(反之亦然 – 參見Bridge with NumPy)。

np_array = np.array(data)
x_np = torch.from_numpy(np_array)

從另一個tensor初始化:

除非明確覆蓋,新的tensor保留參數tensor的屬性(形狀,數據類型)。

x_ones = torch.ones_like(x_data) # retatins the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")
x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")

輸出:

Ones Tensor:
 tensor([[1, 1], 
        [1, 1]])
Random Tensor:
 tensor([[0.3208, 0.9371], 
        [0.8172, 0.7103]])

使用隨機值或常量值:

shape 是tensor維度的元祖。在以下函數中,它決定了輸出tensor的維度。

shape = (2, 3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)

print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor} \n")

輸出:

Random Tensor:
 tensor([[0.0546, 0.8256, 0.1878],
        [0.6135, 0.0886, 0.0350]])

Ones Tensor:
 tensor([[1., 1., 1.],
        [1., 1., 1.]])

Zeros Tensor:
 tensor([[0., 0., 0.],
        [0., 0., 0.]])

Tensor 屬性

Tensor屬性描述了其形狀、數據類型和存儲的設備

tensor =  torch.rand(3, 4)

print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")

輸出:

Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu

Tensor 操作

超過100種tensor操作,包括轉置、索引、切片、數學運算、線性代數、隨機採樣,更多全面的描述見這裡
以上每一種都可以在GPU上運行(通常比cpu速度更快)。如果你使用Colab,在Edit->Notebook Setting中配置GPU

# We move our tensor to the GPU if avaibale
if torch.cuda.is_available():
  tensor = tensor.to('cuda')
  print(f"Device tensor is stored on: {tensor.device}")

輸出:

Device tensor is stored on: cuda:0

嘗試列表中某些操作。如果你熟悉NumPy API,你會發現Tensor API使用起來輕而易舉。

標準的類似於numpy的索引和切片:

tensor = torch.ones(4, 4)
tensor[:, 1] = 0
print(tensor)

輸出:

tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

拼接張量,你可以使用torch.cat沿着給定維度拼接一系列張量,另見torch.stack,另一個tensor的拼接操作,與torch.cat略有不同。

t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)

輸出:

tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])

dim=0,沿着第一維度拼接(增加第一維度數值),dim=1,沿着第二維度拼接(增加第二維度數值)

tensor乘法

# 計算元素乘積
print(f"tensor.mul(tensor) \n {tensor.mul(tensor)} \n")
# 替代語法
print(f"tensor * tensor \n {tensor * tensor}")

輸出:

tensor.mul(tensor)
 tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor * tensor
 tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

計算兩個tensor的矩陣乘法

print(f"tensor.matmul(tensor.T) \n {tensor.matmul(tensor.T)} \n")
# 替代語法:
print(f"tensor @ tensor.T \n {tensor @ tensor.T}")

輸出:

tensor.matmul(tensor.T)
 tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])

tensor @ tensor.T
 tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])

In-place operations:張量操作名帶上「_」即是in-place。例如:x.copy_(y), x.t_(),將會改變x

print(tensor, "\n")
tensor.add_(5)
print(tensor)

輸出:

tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor([[6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.]])

注意:In-place操作可以節省一些內存,但當計算導數時可能會出現問題,因為它會立即丟失歷史記錄。因此,不鼓勵使用它們。

與NumPy的關聯

CPU上的Tensor和NumPy數組可以共享它們的底層內存位置,改變其中一個,另一個也會隨之改變

Tensor轉換為NumPy數組

t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")

輸出:

t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]

在tensor上的改變將會反映在NumPy數組上

t.add_(1)
print(f"t: {t}")
print(f"n: {n}")

輸出:

t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]

Numpy數組轉換為tensor

n = np.ones(5)
t = torch.from_numpy(n)

在NumPy上的改變將會反映在tensor上

np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")

輸出:

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