【问题标题】:How to use gather() in python to return values at specific indices of a tensor如何在 python 中使用 gather() 返回张量特定索引处的值
【发布时间】:2023-02-04 04:50:03
【问题描述】:

我有一个看起来像这样的张量:

tensor([[-0.0150,  0.1234],
    [-0.0184,  0.1062],
    [-0.0139,  0.1113],
    [-0.0088,  0.0726]])

另一个看起来像这样:

tensor([[1.],
    [1.],
    [0.],
    [0.]])

我想为每一行返回第一个张量的值,这些值对应于第二个张量的索引。

所以我们的输出将是:

tensor([0.1234], [0.1062], [-0.0139], [-0.0088]])

到目前为止我有这段代码:

return torch.gather(tensor1, tensor2)

但是我收到错误:

TypeError: gather() received an invalid combination of arguments - got (Tensor, Tensor), but expected one of:
 * (Tensor input, int dim, Tensor index, *, bool sparse_grad, Tensor out)
 * (Tensor input, name dim, Tensor index, *, bool sparse_grad, Tensor out)

我究竟做错了什么?

【问题讨论】:

    标签: python pytorch tensor


    【解决方案1】:

    您缺少 dim 参数。 你可以在这里看到一个例子:https://pytorch.org/docs/stable/generated/torch.gather.html

    对于您的情况,我认为 return torch.gather(tensor1, 1, tensor2) 应该可以

    【讨论】:

    • 我已经更改为 return tensor.gather(1, tensor 2) 这似乎对其他人有用,但我仍然收到错误:RuntimeError: Boolean value of Tensor with more than one value is ambiguous
    • 尝试将 tensor2 更改为 ints
    【解决方案2】:
    t2=torch.tensor([[-0.0150,  0.1234],
    [-0.0184,  0.1062],
    [-0.0139,  0.1113],
    [-0.0088,  0.0726]])
    t3=torch.tensor([[1.],
    [1.],
    [0.],
    [0.]]).type(torch.int64)
    res=t2.gather(1,t3)
    print(res)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-27
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      • 2019-01-13
      • 2019-11-01
      • 1970-01-01
      相关资源
      最近更新 更多