注意
轉到末尾 下載完整的示例程式碼。
學習基礎知識 || 快速入門 || 張量 || 資料集 & 資料載入器 || 變換 || 構建模型 || 自動微分 || 最佳化 || 儲存 & 載入模型
張量#
創建於:2021年2月10日 | 最後更新:2025年1月24日 | 最後驗證:2024年11月5日
張量是一種特殊的資料結構,與陣列和矩陣非常相似。在 PyTorch 中,我們使用張量來編碼模型的輸入和輸出,以及模型的引數。
張量與 NumPy 的 ndarrays 類似,不同之處在於張量可以在 GPU 或其他硬體加速器上執行。事實上,張量和 NumPy 陣列通常可以共享相同的底層記憶體,從而無需複製資料(請參閱 與 NumPy 的橋接)。張量還針對自動微分進行了最佳化(我們將在後面的 自動微分 部分進一步介紹)。如果您熟悉 ndarrays,那麼使用 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.2994, 0.1108],
[0.7758, 0.2595]])
使用隨機值或常量值初始化
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.8337, 0.3246, 0.3503],
[0.4280, 0.2519, 0.1214]])
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,可以透過轉到“Runtime”>“Change runtime type”>“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 索引和切片
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 略有不同的張量連線運算子。
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 數值。
12.0 <class 'float'>
原地操作 將結果儲存到運算元中的操作稱為原地操作。它們通過後綴 _ 來表示。例如:x.copy_(y)、x.t_() 會改變 x。
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: 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.477 秒)