【问题标题】:How do I find elements when given tensors and position values?给定张量和位置值时如何找到元素?
【发布时间】:2022-01-14 15:39:13
【问题描述】:

假设张量为

tensor = torch.Tensor([[[1, 0, 0, 7], [0, 1, 0, 4], [3, 0, 9, 0]]])

我找到了张量中零值的位置。

a = (tensor == 0).nonzero(as_tuple=False)

结果如下:

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

我想使用以下结果再次找到张量中的元素: 正如预期的那样,所有结果都应该返回 0。

我该怎么做?

【问题讨论】:

  • 只使用返回的索引作为原始张量的索引?
  • 是的,我想用返回的结果在张量变量中的张量值中再次找一个元素。
  • 结果应该全为零。

标签: python pytorch element tensor


【解决方案1】:

一种方法是使用advanced indexing:

tensor = torch.Tensor([[[1, 0, 0, 7], [0, 1, 0, 4], [3, 0, 9, 0]]])

# note change to `as_tuple=True` here
a = (tensor == 0).nonzero(as_tuple=True)

tensor[a]
# ==> tensor([0., 0., 0., 0., 0., 0.])

pytorch 中的索引工作(大部分!)与 numpy 中的相同,因此链接到上面的 numpy 文档。

【讨论】:

  • 感谢您的帮助,我能够解决这个问题。
猜你喜欢
  • 2020-10-04
  • 1970-01-01
  • 2021-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-23
  • 2022-11-16
  • 2014-07-06
相关资源
最近更新 更多