評價此頁

張量#

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

張量(Tensors)是一種專門的資料結構,與陣列和矩陣非常相似。在 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.0706, 0.5387],
        [0.1279, 0.4793]])

使用隨機或常數值建立

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.0283, 0.1062, 0.8323],
        [0.7656, 0.7541, 0.6441]])

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.494 秒)