如何在 PyTorch 中缩小张量?
torch.narrow() 方法用于对 PyTorch 张量执行缩小操作。它返回一个新的张量,它是原始输入张量的缩小版本。
例如,一个 [4, 3] 的张量可以缩小到 [2, 3] 或 [4, 2] 大小的张量。我们可以一次沿着单个维度缩小张量。在这里,我们不能将两个维度都缩小到 [2, 2] 的大小。我们也可以使用 Tensor.narrow() 来缩小张量。
语法
torch.narrow(input, dim, start, length) Tensor.narrow(dim, start, length)
参数
input – 要缩小的 PyTorch 张量。
dim – 要沿其缩小原始张量 input 的维度。
Start – 开始维度。
Length – 从开始维度到结束维度的长度。
步骤
导入 torch 库。确保你已经安装了它。
import torch
创建一个 PyTorch 张量并打印张量及其大小。
t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print("Tensor:
", t) print("Size of tensor:", t.size()) # size 3x3
计算 torch.narrow(input, dim, start, length) 并将值赋给一个变量。
t1 = torch.narrow(t, 0, 1, 2)
缩小后,打印结果张量及其大小。
print("Tensor after Narrowing:
", t2) print("Size after Narrowing:", t2.size())
示例 1
在下面的 Python 代码中,输入张量大小为 [3, 3]。我们使用 dim = 0,start = 1 和 length = 2 沿维度 0 缩小张量。它返回一个维度为 [2, 3] 的新张量。
请注意,新张量沿维度 0 缩小,并且沿维度 0 的长度更改为 2。
# import the library import torch # create a tensor t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # print the created tensor print("Tensor:
", t) print("Size of Tensor:", t.size()) # Narrow-down the tensor in dimension 0 t1 = torch.narrow(t, 0, 1, 2) print("Tensor after Narrowing:
", t1) print("Size after Narrowing:", t1.size()) # Narrow down the tensor in dimension 1 t2 = torch.narrow(t, 1, 1, 2) print("Tensor after Narrowing:
", t2) print("Size after Narrowing:", t2.size())
输出
Tensor: tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) Size of Tensor: torch.Size([3, 3]) Tensor after Narrowing: tensor([[4, 5, 6], [7, 8, 9]]) Size after Narrowing: torch.Size([2, 3]) Tensor after Narrowing: tensor([[2, 3], [5, 6], [8, 9]]) Size after Narrowing: torch.Size([3, 2])
示例 2
以下程序演示了如何使用 Tensor.narrow() 实现缩小操作。
# import required library import torch # create a tensor t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) # print the above created tensor print("Tensor:
", t) print("Size of Tensor:", t.size()) # Narrow-down the tensor in dimension 0 t1 = t.narrow(0, 1, 2) print("Tensor after Narrowing:
", t1) print("Size after Narrowing:", t1.size()) # Narrow down the tensor in dimension 1 t2 = t.narrow(1, 0, 2) print("Tensor after Narrowing:
", t2) print("Size after Narrowing:", t2.size())
输出
Tensor: tensor([[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12]]) Size of Tensor: torch.Size([4, 3]) Tensor after Narrowing: tensor([[4, 5, 6], [7, 8, 9]]) Size after Narrowing: torch.Size([2, 3]) Tensor after Narrowing: tensor([[ 1, 2], [ 4, 5], [ 7, 8], [10, 11]]) Size after Narrowing: torch.Size([4, 2])
广告