pytorch 中的张量变换?

tensor transformation in pytorch?

我有一个形状为 (size, 1) 的张量,我想通过移动其值将其转换为形状为 (size, lookback, 1) 的张量。 pandas 等价于

size = 7
lookback = 3

data = pd.DataFrame(np.arange(size), columns=['out'])  # input
y = np.full((len(data), lookback, 1), np.nan)          # required/output
for j in range(lookback):
    y[:, j, 0] = data['out'].shift(lookback - j - 1).fillna(method="bfill")

如何在 pytorch 中实现类似的效果?

示例输入:

[0, 1, 2, 3, 4, 5, 6]

期望的输出:

[[0. 0. 0.]
 [0. 0. 1.]
 [0. 1. 2.]
 [1. 2. 3.]
 [2. 3. 4.]
 [3. 4. 5.]
 [4. 5. 6.]]

您可以使用 Tensor.unfold for this. First though you will need to pad the front of the tensor, for that you could use nn.functional.pad。例如

import torch
import torch.nn.functional as F

size = 7
loopback = 3

data = torch.arange(size, dtype=torch.float)

# pad front of data with 2 values
# replicate padding requires 3d, 4d, or 5d tensor, hence the creation of two unitary dimensions before padding
data_padded = F.pad(data[None, None, ...], (loopback - 1, 0), 'replicate')[0, 0, ...]
# unfold with window size of 3 with step size of 1
y = data_padded.unfold(dimension=0, size=loopback, step=1)

给出

的输出
tensor([[0., 0., 0.],
        [0., 0., 1.],
        [0., 1., 2.],
        [1., 2., 3.],
        [2., 3., 4.],
        [3., 4., 5.],
        [4., 5., 6.]])