注意
點選此處下載完整的示例程式碼
張量¶
創建於:2017 年 3 月 24 日 | 最後更新:2024 年 1 月 16 日 | 最後驗證:2024 年 11 月 5 日
張量是一種特殊的資料結構,與陣列和矩陣非常相似。在 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 略有不同的張量連線操作。
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.]])
張量乘法
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.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) 帶有 _ 字尾的操作是原地操作。例如: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.142 秒)