将张量分配给多个切片

问题描述 投票:1回答:2

a = tensor([[0, 0, 0, 0],
            [0, 0, 0, 0],
            [0, 0, 0, 0]])
b = torch.tensor([1, 2])
c = tensor([[1, 2, 0, 0],
            [0, 1, 2, 0],
            [0, 0, 1, 2]])

有没有一种方法可以通过将c分配给b的切片而没有任何循环来获得a?也就是说,对于某些a[indices] = b或类似内容,indices

python arrays pytorch slice tensor
2个回答
1
投票
您可以在pytorch中使用scatter方法。

a = torch.tensor([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) b = torch.tensor([1, 2]) index = torch.tensor([[0,1],[1,2],[2,3]]) a.scatter_(1, index, b.view(-1,2).repeat(3,1)) # tensor([[1, 2, 0, 0], # [0, 1, 2, 0], # [0, 0, 1, 2]])


0
投票
此操作背后的逻辑有点不确定,因为尚不清楚该操作的参数是什么。但是,仅使用矢量化操作从输入中获得所需输出的一种方法是:

    确定需要多少行(您的示例为3
  • 创建具有多个列的a,以使b后跟行数(2 + 3)和所选行数(3)一样多的零]
  • b分别分配给a的开头
  • 将数组展平,将num_rows切为零,并调整为目标形状。
  • 在NumPy中,可以实现为:

    import numpy as np b = np.array([1, 2]) c = np.array([[1, 2, 0, 0], [0, 1, 2, 0], [0, 0, 1, 2]]) num_rows = 3 a = np.zeros((num_rows, len(b) + num_rows), dtype=b.dtype) a[:, :len(b)] = b a = a.ravel()[:-num_rows].reshape((num_rows, len(b) + num_rows - 1)) print(a) # [[1 2 0 0] # [0 1 2 0] # [0 0 1 2]] print(np.all(a == c)) # True


    编辑

    与在Torch中实施的相同方法:

    import torch as to b = to.tensor([1, 2]) c = to.tensor([[1, 2, 0, 0], [0, 1, 2, 0], [0, 0, 1, 2]]) num_rows = 3 a = to.zeros((num_rows, len(b) + num_rows), dtype=b.dtype) a[:, :len(b)] = b a = a.flatten()[:-num_rows].reshape((num_rows, len(b) + num_rows - 1)) print(a) # tensor([[1, 2, 0, 0], # [0, 1, 2, 0], # [0, 0, 1, 2]]) print(to.all(a == c)) # tensor(1, dtype=torch.uint8)

  • © www.soinside.com 2019 - 2024. All rights reserved.