【发布时间】:2021-11-05 01:32:28
【问题描述】:
我有一个形状为 n x m 的 2D pytorch 张量。我想使用索引列表(可以使用 torch.gather 完成)对第二个维度进行索引,然后然后还设置新值到索引的结果。
例子:
data = torch.tensor([[0,1,2], [3,4,5], [6,7,8]]) # shape (3,3)
indices = torch.tensor([1,2,1], dtype=torch.long).unsqueeze(-1) # shape (3,1)
# data tensor:
# tensor([[0, 1, 2],
# [3, 4, 5],
# [6, 7, 8]])
我想为每行选择指定的索引(这将是 [1,5,7],但随后也将这些值设置为另一个数字 - 例如 42
我可以通过以下方式逐行选择所需的列:
data.gather(1, indices)
tensor([[1],
[5],
[7]])
data.gather(1, indices)[:] = 42 # **This does NOT work**, since the result of gather
# does not use the same storage as the original tensor
这很好,但我现在想更改这些值,并且更改也会影响data 张量。
我可以用它做我想做的事,但它似乎很不符合pythonic:
max_index = torch.max(indices)
for i in range(0, max_index + 1):
mask = (indices == i).nonzero(as_tuple=True)[0]
data[mask, i] = 42
print(data)
# tensor([[ 0, 42, 2],
# [ 3, 4, 42],
# [ 6, 42, 8]])
关于如何更优雅地做到这一点的任何提示?
【问题讨论】:
标签: python indexing pytorch tensor