使用 Pytorch 如何定义具有索引和相应值的张量

Using Pytorch how to define a tensor with indices and corresponding values

问题

我有一个索引列表和一个值列表,如下所示:

i = torch.tensor([[2, 2, 1], [2, 0, 2]])
v = torch.tensor([1, 2, 3])

我想定义一个(3x3 示例)矩阵,其中在索引 i 处包含值 v1 在位置 (2,2), 2 在位置 (2, 0)3 在位置 (1,2)):

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

我试过的

我可以使用 torch.sparse.to_dense() 的技巧来做到这一点,但我觉得这不是做到这一点的“pytorchic”方式,也不是最有效的方式:

f = torch.sparse.FloatTensor(indices, values, torch.Size([3, 3]))
print(f.to_dense())

有更好的解决方案吗? 理想情况下,我希望有一个至少与上面提供的解决方案一样快的解决方案。 当然,这只是一个例子,没有假设张量 iv 中的特定结构(维度也没有)。

还有一个替代方案,如下:

import torch

i = torch.tensor([[2, 2, 1], [2, 0, 2]])
v = torch.tensor([1, 2, 3], dtype=torch.float)   # enforcing same data-type

target = torch.zeros([3,3], dtype=torch.float)   # enforcing same data-type
target.index_put_(tuple([k for k in i]), v)

print(target)

target张量如下:

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

This medium.com blog article 提供了 PyTorch 张量的所有 index 函数的综合列表。