简体   繁体   English

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

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

Problem问题

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处的值v1在 position (2,2)2在 position (2, 0)3在 Z4757FE07FD492A8BEDDEA6 8 (1,2) :3

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

What I have tried我试过的

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).当然这只是一个例子,没有假设张量iv中的特定结构(维度也没有)。

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.

相关问题 如何检查张量值是否在不同的张量 pytorch? - How to check whether tensor values in a different tensor pytorch? Pytorch:如何通过python字典中的张量(键)访问张量(值) - Pytorch: How to access tensor(values) by tensor(keys) in python dictionary 你如何在 Pytorch 中反转布尔值的张量? - How do you invert a tensor of boolean values in Pytorch? 如何检查两个字符串在所有索引处是否都具有对应的值? - How to check if two strings have corresponding values at all indices? 更改Pytorch 3D张量内的值 - Change values inside a Pytorch 3D tensor pytorch 操作:火炬张量中值的并集和反转 - pytorch operations: union and inversion of values in torch tensor 使用相应的过去索引值和特定的唯一列值填充新的数据框列 - filling new dataframe column using corresponding past indices values and specific unique column values 如何将pytorch张量中的map元素进行id化? - How to map element in pytorch tensor to id? Pytorch 运行时错误:参数 #1 'indices' 的预期张量具有标量类型 Long; 但是得到了 CUDAType - Pytorch RuntimeError: Expected tensor for argument #1 'indices' to have scalar type Long; but got CUDAType instead Keras张量 - 获得指数来自另一个张量的值 - Keras tensors - Get values with indices coming from another tensor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM