如何在 PyTorch 中執行擴充套件操作?


Tensor.expand() 屬性用於執行擴充套件操作。它沿著單例維度將張量擴充套件到新的維度。

  • 擴充套件張量只會建立一個原始張量的新檢視;它不會複製原始張量。

  • 如果將特定維度設定為 -1,則不會沿著此維度擴充套件張量。

  • 例如,如果我們有一個大小為 (3,1) 的張量,我們可以沿著大小為 1 的維度擴充套件此張量。

步驟

要擴充套件張量,可以按照以下步驟操作:

  • 匯入 torch 庫。確保您已安裝它。

import torch
  • 定義至少有一個維度為單例的張量。

t = torch.tensor([[1],[2],[3]])
  • 沿著單例維度擴充套件張量。沿著非單例維度擴充套件將引發執行時錯誤(參見示例 3)。

t_exp = t.expand(3,2)
  • 顯示擴充套件後的張量。

print("Tensor after expand:
", t_exp)

示例 1

以下 Python 程式演示瞭如何將大小為 (3,1) 的張量擴充套件為大小為 (3,2) 的張量。它沿著大小為 1 的維度擴充套件張量。大小為 3 的另一個維度保持不變。

# import required libraries
import torch

# create a tensor
t = torch.tensor([[1],[2],[3]])

# display the tensor
print("Tensor:
", t) print("Size of Tensor:
", t.size()) # expand the tensor exp = t.expand(3,2) print("Tensor after expansion:
", exp)

輸出

Tensor:
 tensor([[1],
    [2],
    [3]])
Size of Tensor:
 torch.Size([3, 1])
Tensor after expansion:
 tensor([[1, 1],
    [2, 2],
    [3, 3]])

示例 2

以下 Python 程式將大小為 (1,3) 的張量擴充套件為大小為 (3,3) 的張量。它沿著大小為 1 的維度擴充套件張量。

# import required libraries
import torch

# create a tensor
t = torch.tensor([[1,2,3]])

# display the tensor
print("Tensor:
", t) # size of tensor is [1,3] print("Size of Tensor:
", t.size()) # expand the tensor expandedTensor = t.expand(3,-1) print("Expanded Tensor:
", expandedTensor) print("Size of expanded tensor:
", expandedTensor.size())

輸出

Tensor:
 tensor([[1, 2, 3]])
Size of Tensor:
 torch.Size([1, 3])
Expanded Tensor:
 tensor([[1, 2, 3],
    [1, 2, 3],
    [1, 2, 3]])
Size of expanded tensor:
 torch.Size([3, 3])

示例 3

在以下 Python 程式中,我們嘗試沿著非單例維度擴充套件張量,因此它引發了執行時錯誤。

# import required libraries
import torch

# create a tensor
t = torch.tensor([[1,2,3]])

# display the tensor
print("Tensor:
", t) # size of tensor is [1,3] print("Size of Tensor:
", t.size()) t.expand(3,4)

輸出

Tensor:
 tensor([[1, 2, 3]])
Size of Tensor:
 torch.Size([1, 3])


RuntimeError: The expanded size of the tensor (4) must match the existing size (3) at non-singleton dimension 1. Target sizes: [3, 4]. Tensor sizes: [1, 3]

更新於: 2021-12-06

3K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.