填充 torch 张量(或 numpy 数组)列表

Cle*_*lee 2 python numpy padding python-3.x pytorch

假设我有一个列表如下:

l = [torch.randn(2,3), torch.randn(2,4),torch.randn(2,5)]
Run Code Online (Sandbox Code Playgroud)

我想在第二个维度中对所有元素进行零填充,这样它们将扩展到 5 个元素(5 是第二个维度中三个元素之间的最大数量)。我怎样才能做到这一点。我尝试过这个但失败了:

from torch.nn.utils.rnn import pad_sequence
pad_sequence(l, batch_first=True, padding_value=0)
Run Code Online (Sandbox Code Playgroud)

这导致了以下错误:

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

Numpy 中的等效答案也将受到赞赏。

tom*_*mjn 5

一种选择是使用np.pad.

例子:

import numpy as np
a = np.random.randn(2, 3)
b = np.pad(a, [(0, 0), (0, 2)], mode='constant') 
Run Code Online (Sandbox Code Playgroud)

打印a给出

[[ 1.22721163  1.23456672  0.51948003]
 [ 0.16545496  0.06609003 -0.32071653]]
Run Code Online (Sandbox Code Playgroud)

打印b给出

[[ 1.22721163  1.23456672  0.51948003  0.          0.        ]
 [ 0.16545496  0.06609003 -0.32071653  0.          0.        ]]
Run Code Online (Sandbox Code Playgroud)

的第二个参数padpad_width每个维度的前/后填充列表。因此,在此示例中,第一维中没有填充,第二维末尾有两个填充。

您还可以使用许多其他mode选项,因此请查看文档。

对于您的特定问题,您需要添加一个额外的步骤来计算每个数组的填充。

编辑

因为pytorch我认为你想要torch.nn.functional.pad例如

import torch
t = torch.randn(2, 3)
torch.nn.functional.pad(t, (0, 2))
Run Code Online (Sandbox Code Playgroud)

编辑2

要求torch.nn.utils.rnn.pad_sequence列表中所有张量的尾部尺寸相同,因此您需要进行一些转置才能使其正常工作

import torch
# l = [torch.randn(2,3), torch.randn(2,4),torch.randn(2,5)]
# l = [i.transpose(0, 1) for i in l]  
# or simply make you tensors with switched dimensions
l = [torch.randn(3,2), torch.randn(4,2),torch.randn(5,2)]
out = torch.nn.utils.rnn.pad_sequence(l, batch_first=True)
# out will now be a tensor with shape (3, 5, 2)
# You can transpose it back to (3, 2, 5) with
out = out.transpose(1, 2)
Run Code Online (Sandbox Code Playgroud)