捷徑

學習基礎知識 || 快速入門 || 張量 || 資料集 & 資料載入器 || 轉換 || 建立模型 || Autograd || 最佳化 || 儲存 & 載入模型

張量

建立於:2021 年 2 月 10 日 | 最後更新:2025 年 1 月 24 日 | 最後驗證:2024 年 11 月 05 日

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

張量與 NumPy 的 ndarray 相似,但張量可以在 GPU 或其他硬體加速器上運行。 事實上,張量和 NumPy 陣列通常可以共享相同的底層記憶體,從而無需複製資料(請參閱與 NumPy 的橋接)。 張量也針對自動微分進行了最佳化(我們將在 Autograd 章節中了解更多資訊)。 如果您熟悉 ndarray,您會很熟悉 Tensor 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

張量的運算

超過 1200 個張量運算,包括算術、線性代數、矩陣操作(轉置、索引、切片)、抽樣等,都在 這裡 進行了全面描述。

這些運算中的每一個都可以在 CPU 和 加速器(例如 CUDA、MPS、MTIA 或 XPU)上運行。 如果您使用 Colab,請前往「執行階段」>「變更執行階段類型」>「GPU」來分配加速器。

預設情況下,張量是在 CPU 上建立的。 我們需要使用 .to 方法將張量顯式移動到加速器(在檢查加速器可用性之後)。 請記住,跨裝置複製大型張量在時間和記憶體方面可能會很昂貴!

# We move our tensor to the current accelerator if available
if torch.accelerator.is_available():
    tensor = tensor.to(torch.accelerator.current_accelerator())

試用列表中的一些運算。 如果您熟悉 NumPy API,您會發現 Tensor API 很容易使用。

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

tensor = torch.ones(4, 4)
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")
tensor[:,1] = 0
print(tensor)
First row: tensor([1., 1., 1., 1.])
First column: tensor([1., 1., 1., 1.])
Last column: tensor([1., 1., 1., 1.])
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 matrix multiplication between two tensors. y1, y2, y3 will have the same value
# ``tensor.T`` returns the transpose of a tensor
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

y3 = torch.rand_like(y1)
torch.matmul(tensor, tensor.T, out=y3)


# This computes the element-wise product. z1, z2, z3 will have the same value
z1 = tensor * tensor
z2 = tensor.mul(tensor)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

單元素張量 如果您有一個單元素張量,例如透過將張量的所有值聚合為一個值,您可以使用 item() 將其轉換為 Python 數值

agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))
12.0 <class 'float'>

原地運算 將結果儲存到運算元中的運算稱為原地運算。 它們由 _ 後綴表示。 例如:x.copy_(y)x.t_() 會變更 x

print(f"{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 陣列可以共享其底層記憶體位置,並且變更一個會變更另一個。

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

腳本總執行時間: ( 0 分鐘 0.023 秒)

由 Sphinx-Gallery 產生

文件

取得 PyTorch 的完整開發人員文件

檢視文件

教學

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

檢視教學

資源

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

檢視資源