【问题标题】:Create array/tensor of cycle shifted arrays创建循环移位数组的数组/张量
【发布时间】:2021-12-11 20:56:00
【问题描述】:

我想创建 2d 张量(或 numpy 数组,并不重要),其中每一行都将循环移位第一行。我使用for 循环:

import torch
import numpy as np

a = np.random.rand(33, 11)
miss_size = 64
lp_order = a.shape[1] - 1
inv_a = -np.flip(a, axis=1)
mtx_size = miss_size+lp_order   # some constant
mtx_row = torch.cat((torch.from_numpy(inv_a), torch.zeros((a.shape[0], miss_size - 1 + a.shape[1]))), dim=1)
mtx_full = mtx_row.unsqueeze(1)
for i in range(mtx_size):
        mtx_row = torch.roll(mtx_row, 1, 1)
        mtx_full = torch.cat((mtx_full, mtx_row.unsqueeze(1)), dim=1)

需要解压,因为我将 2d 张量堆叠到 3d 张量中

有没有更有效的方法来做到这一点?也许是线性代数技巧或更 Pythonic 的方法。

【问题讨论】:

  • 你能提供一个最小的例子吗?
  • @Ivan 最小的例子在帖子的文本中
  • 确实如此,但请提供mtx_rowmiss_sizelp_order,以便作为显示所需行为的最小示例。
  • @Ivan 添加了虚拟常量

标签: python numpy pytorch cycle


【解决方案1】:

你可以使用scipy.linalg.circulant():

scipy.linalg.circulant([1, 2, 3])
# array([[1, 3, 2],
#        [2, 1, 3],
#        [3, 2, 1]])

【讨论】:

  • 这很好,但是由于有一批这样的数组,仍然需要循环。不过谢谢!
【解决方案2】:

我相信您可以使用torch.gather 通过构造适当的索引张量来实现这一点。这种方法也适用于批处理。

如果我们采用这种方法,目标是构建一个索引张量,其中每个值都引用mtx_row 中的一个索引(沿着dim=1 中的最后一个维度)。在这种情况下,它将被塑造成(3, 3)

tensor([[0, 1, 2],
        [2, 0, 1],
        [1, 2, 0]])

您可以通过使用自己的转置广播torch.arange 并对结果矩阵应用模数来实现此目的:

>>> idx = (n-torch.arange(n)[None].T + torch.arange(n)[None]) % n
tensor([[0, 1, 2],
        [2, 0, 1],
        [1, 2, 0]])

mtx_row变成(2, 3)

>>> mtx_row
tensor([[0.3523, 0.0170, 0.1875],
        [0.2156, 0.7773, 0.4563]])

从那里你需要 idxmtx_row 使它们具有相同的形状:

>>> idx_ = idx[None].expand(len(mtx_row), -1, -1)
>>> val_ = mtx_row[:, None].expand(-1, n, -1)

那么我们可以在最后一个维度dim=2上应用torch.gather

>>> val_.gather(-1, idx_)
tensor([[[0.3523, 0.0170, 0.1875],
         [0.1875, 0.3523, 0.0170],
         [0.0170, 0.1875, 0.3523]],

        [[0.2156, 0.7773, 0.4563],
         [0.4563, 0.2156, 0.7773],
         [0.7773, 0.4563, 0.2156]]])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    相关资源
    最近更新 更多