[英]Using Pytorch how to define a tensor with indices and corresponding values
I have a list of indices and a list of values like so:我有一个索引列表和一个值列表,如下所示:
i = torch.tensor([[2, 2, 1], [2, 0, 2]])
v = torch.tensor([1, 2, 3])
I want to define a ( 3x3
for the example) matrix which contains the values v
at the indices i
( 1
at position (2,2)
, 2
at position (2, 0)
and 3
at position (1,2)
):我想定义一个(例如3x3
)矩阵,它包含索引i
处的值v
( 1
在 position (2,2)
, 2
在 position (2, 0)
和3
在 Z4757FE07FD492A8BEDDEA6 8 (1,2)
:3
tensor([[0, 0, 0],
[0, 0, 3],
[2, 0, 1]])
I can do it using a trick, with torch.sparse
and .to_dense()
but I feel that it's not the "pytorchic" way to do that nor the most efficient:我可以使用一个技巧来做到这一点,使用torch.sparse
和.to_dense()
但我觉得这不是“pytorchic”的方式,也不是最有效的:
f = torch.sparse.FloatTensor(indices, values, torch.Size([3, 3]))
print(f.to_dense())
Any idea for a better solution?有更好的解决方案的想法吗? Ideally I would appreciate a solution at least as fast than the one provided above.理想情况下,我会欣赏一种至少与上面提供的解决方案一样快的解决方案。 Of course this was just an example, no particular structure in tensors i
and v
are assumed (neither for the dimension).当然这只是一个例子,没有假设张量i
和v
中的特定结构(维度也没有)。
There is an alternative, as below:有一个替代方案,如下所示:
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)
The target
tensor will be as follows: target
张量如下:
tensor([[0., 0., 0.],
[0., 0., 3.],
[2., 0., 1.]])
This medium.com blog article provides a comprehensive list of all index functions for PyTorch Tensors. 这篇中型 com 博客文章提供了 PyTorch 张量的所有索引函数的完整列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.