快捷方式

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

張量

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

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

張量類似於 NumPy 的 ndarray,不同之處在於張量可以在 GPU 或其他硬體加速器上執行。實際上,張量和 NumPy 陣列通常可以共享底層記憶體,從而無需複製資料(詳見與 NumPy 的橋接)。張量還針對自動微分進行了最佳化(我們將在後面的 Autograd 部分詳細介紹)。如果您熟悉 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.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 陣列可以共享其底層記憶體位置,改變其中一個會改變另一個。

張量轉 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.015 秒)

相簿由 Sphinx-Gallery 生成

文件

查閱 PyTorch 的全面開發者文件

檢視文件

教程

獲取針對初學者和高階開發者的深入教程

檢視教程

資源

查詢開發資源並獲得問題解答

檢視資源