简体   繁体   English

pytorch 从一维张量收集

[英]pytorch gathering from a 1d tensor

I have a long list of values stored in a 1d tensor from which I like to gather values.我有一长串存储在 1d 张量中的值,我喜欢从中收集值。 Given a 2d tensor where the second dimension denotes a set of indices, I would like to compute a new 2d tensor where the second dimension are all the values gathered given by the indices.给定一个二维张量,其中第二维表示一组索引,我想计算一个新的二维张量,其中第二维是索引给定的所有值。 Basically, I have a batch of indices and I use those indices to obtain a batch of values from the 1d-tensor.基本上,我有一批索引,我使用这些索引从一维张量中获取一批值。

I am new to pytorch but I managed to compute exactly that using pytorch's gather function我是 pytorch 的新手,但我设法使用 pytorch 的收集 function 准确计算出

list_values = torch.tensor([1, 2, 3, 4, 5, 6])
list_values = list_values.unsqueeze(0)
list_values = list_values.expand((2, 6))
indices = torch.tensor([[1, 2], [2, 3]])
result = torch.gather(list_values, 1, indices)

This works perfectly fince and gives the correct result.这工作得很好,并给出了正确的结果。 However, If I am not mistaken, the expand operation is quite expensive in terms of memory as the number of elements in "list_value" grows.但是,如果我没记错的话,随着“list_value”中元素数量的增加,就 memory 而言,展开操作非常昂贵。

Is there a better solution?有更好的解决方案吗?

Nope, take a look at the documentation :不,看看文档

Expanding a tensor does not allocate new memory, but only creates a new view on the existing tensor where a dimension of size one is expanded to a larger size by setting the stride to 0. Any dimension of size 1 can be expanded to an arbitrary value without allocating new memory.扩展张量不会分配新的 memory,而只会在现有张量上创建一个新视图,其中通过将步幅设置为 0 将尺寸为 1 的尺寸扩展为更大的尺寸。尺寸为 1 的任何尺寸都可以扩展为任意值无需分配新的 memory。

You solution is completely fine你的解决方案完全没问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM