让
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
?
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]])
3
)a
,以使b
后跟行数(2 + 3
)和所选行数(3
)一样多的零]b
分别分配给a
的开头num_rows
切为零,并调整为目标形状。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)