捷徑

學習基本概念 || 快速入門 || 張量 || 資料集和資料載入器 || 轉換 || 建立模型 || Autograd || 優化 || 儲存和載入模型

張量

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

張量類似於 NumPy 的 ndarray,不同之處在於張量可以在 GPU 或其他硬體加速器上執行。事實上,張量和 NumPy 陣列通常可以共用相同的底層記憶體,從而无需複製資料(請參閱 與 NumPy 的橋接)。張量還針對自動微分進行了優化(我們將在 Autograd 部分中詳細瞭解這一點)。如果您熟悉 ndarray,那麼您會對張量 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.4223, 0.1719],
        [0.3184, 0.2631]])

使用隨機值或常數值

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.1602, 0.6000, 0.4126],
        [0.5558, 0.0912, 0.3004]])

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」來配置 GPU。

根據預設,張量是在 CPU 上建立的。在檢查 GPU 可用性之後,我们需要使用 .to 方法明確地將張量移至 GPU。請記住,在裝置之間複製大型張量可能會耗費大量時間和記憶體!

# We move our tensor to the GPU if available
if torch.cuda.is_available():
  tensor = tensor.to('cuda')

嘗試列表中的一些運算。如果您熟悉 NumPy API,那麼您會發現張量 API 使用起來非常簡單。

標準的類 NumPy 索引和切片

tensor = torch.ones(4, 4)
print('First row: ',tensor[0])
print('First column: ', tensor[:, 0])
print('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
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

y3 = torch.rand_like(tensor)
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)

**單元素張量** 如果您有一個單元素張量,例如透過將張量的所有值聚合成一個值,則可以使用 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(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 分鐘 6.125 秒)

由 Sphinx-Gallery 生成的圖庫


這有幫助嗎?
謝謝您

© Copyright 2017, PyTorch.

使用 Sphinx 建立,並使用由 主題 提供的 Read the Docs

文件

存取 PyTorch 的完整開發者文件

查看文件

教學

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

查看教學

資源

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

查看資源