捷徑

張量

建立於:2017 年 3 月 24 日 | 最後更新:2024 年 1 月 16 日 | 最後驗證:2024 年 11 月 05 日

張量是一種特殊的資料結構,與陣列和矩陣非常相似。在 PyTorch 中,我們使用張量來編碼模型的輸入和輸出,以及模型的參數。

張量與 NumPy 的 ndarrays 相似,但張量可以在 GPU 或其他專用硬體上運行以加速計算。如果您熟悉 ndarrays,您會對 Tensor API 感到賓至如歸。 如果沒有,請按照此快速 API 演練進行操作。

import torch
import numpy as np

張量初始化

張量可以透過各種方式初始化。請看以下範例

直接從資料

可以直接從資料建立張量。 資料類型會自動推斷。

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

從 NumPy 陣列

可以從 NumPy 陣列建立張量(反之亦然 - 請參閱與 NumPy 的橋樑)。

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

從另一個張量

除非明確覆蓋,否則新的張量會保留參數張量的屬性(形狀、資料類型)。

x_ones = torch.ones_like(x_data) # retains 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.8823, 0.9150],
        [0.3829, 0.9593]])

使用隨機或常數值

shape 是張量維度的元組。 在下面的函式中,它決定了輸出張量的維度。

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}")
Random Tensor:
 tensor([[0.3904, 0.6009, 0.2566],
        [0.7936, 0.9408, 0.1332]])

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

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

張量屬性

張量屬性描述了它們的形狀、資料類型以及它們儲存的裝置。

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

張量運算

超過 100 種張量運算,包括轉置、索引、切片、數學運算、線性代數、隨機抽樣等等,都已在此處全面描述。

它們中的每一個都可以在 GPU 上運行(通常比在 CPU 上運行速度更快)。 如果您使用的是 Colab,請透過前往「編輯」>「筆記本設定」來分配 GPU。

# We move our tensor to the GPU if available
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,另一個張量連接運算,它與 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.]])

乘法張量

# This computes the element-wise product
print(f"tensor.mul(tensor) \n {tensor.mul(tensor)} \n")
# Alternative syntax:
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.]])

這會計算兩個張量之間的矩陣乘法

print(f"tensor.matmul(tensor.T) \n {tensor.matmul(tensor.T)} \n")
# Alternative syntax:
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.]])

原地運算 具有 _ 字尾的運算是原地運算。 例如: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.]])

注意

原地運算可以節省一些記憶體,但由於立即失去了歷史記錄,因此在計算導數時可能會出現問題。 因此,不鼓勵使用它們。


與 NumPy 的橋樑

CPU 上的張量和 NumPy 陣列可以共享其底層記憶體位置,並且更改一個將會更改另一個。

張量到 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.]

張量的變更反映在 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 陣列到張量

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

NumPy 陣列的變更反映在張量中。

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

腳本的總運行時間:(0 分鐘 0.035 秒)

由 Sphinx-Gallery 產生的圖庫

文件

存取 PyTorch 完整的開發者文件

查看文件

教學

取得針對初學者和進階開發者的深入教學

查看教學

資源

尋找開發資源並獲得您的問題解答

查看資源