简体   繁体   English

Pytorch/Python-如何使用索引张量获取结果张量

[英]Pytorch/Python-How to get a result tensor using a index tensor

Given a 1-D tensor:给定一维张量:

A = torch.tensor([1, 2, 3, 4])

suppose we have some "index tensor"假设我们有一些“索引张量”

ind1 = torch.tensor([3, 0, 1])
ind2 = torch.tensor([[3, 0], [1, 2]])

as we run A[ind1] & A[ind2]当我们运行A[ind1] & A[ind2]

we get tensor([4, 1, 2]) & tensor([[4, 1],[2, 3]]) which is the same shape of index tensor and its value are mapped from tensor A.我们得到tensor([4, 1, 2]) & tensor([[4, 1],[2, 3]]) ,它们是索引张量的相同形状,其值是从张量 A 映射的。

Now if I have ND tensor, I want to get a result tensor using an index map, how can I do that?现在,如果我有 ND 张量,我想使用索引 map 获得结果张量,我该怎么做?

Let's take a minimal multi-dimensional example with A being a 2-D tensor defined as:让我们举一个最小的多维示例,其中A是一个二维张量,定义为:

>>> A = torch.tensor([[1, 2, 3, 4],
                      [5, 6, 7, 8]])

From your description of the problem:根据您对问题的描述:

the same shape of index tensor and its value are mapped from tensor A .从张量A映射相同形状的索引张量及其值。

Then the indexer tensor would require to have the same shape as the indexed tensor A , since this one is no longer flat.然后索引器张量需要具有与索引张量A相同的形状,因为这个张量不再是平坦的。 Otherwise, what would the result of A (shaped (2, 4) ) indexed by ind1 (shape (3,) ) be?否则,由ind1 (shape (3,) ) 索引的A (shape (2, 4) ) 的结果是什么?

If you are indexing on a single dimension then you can utilize torch.gather :如果您在单个维度上建立索引,那么您可以使用torch.gather

>>> A.gather(1, ind2)
tensor([[4, 1],
        [6, 7]])

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

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