【问题标题】:Batched index_fill in PyTorchPyTorch 中的批量 index_fill
【发布时间】:2021-08-29 07:30:40
【问题描述】:

我有一个大小为(2, 3)的索引张量:

>>> index = torch.empty(6).random_(0,8).view(2,3)
tensor([[6., 3., 2.],
        [3., 4., 7.]])

还有一个大小为(2, 8)的值张量:

>>> value = torch.zeros(2,8)
tensor([[0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0.]])

我想通过沿dim=-1 的索引将value 中的元素设置为1。** 输出应该是这样的:

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

我尝试了value[range(2), index] = 1,但它触发了错误。我也试过torch.index_fill,但它不接受批量索引。 torch.scatter 需要创建一个大小为2*8 的额外张量,其中包含1,这会消耗不必要的内存和时间。

【问题讨论】:

    标签: pytorch numpy-indexing


    【解决方案1】:

    您实际上可以通过设置 value (int) 选项而不是 src 选项 (Tensor) 来使用 torch.Tensor.scatter_

    >>> value.scatter_(dim=-1, index=index.long(), value=1)
    
    >>> value
    tensor([[0., 0., 1., 1., 0., 0., 1., 0.],
            [0., 0., 0., 1., 1., 0., 0., 1.]])
    

    确保index 的类型是int64

    【讨论】:

    • 太棒了,谢谢伊万。我怎么会忘记 value 参数!
    • torch.Tensor.scatter的文档页面上其实是看不到...
    • 检查过了。我认为这是一个问题。
    猜你喜欢
    • 1970-01-01
    • 2019-02-03
    • 2021-01-29
    • 2021-09-14
    • 2020-10-09
    • 1970-01-01
    • 2021-08-22
    • 2021-08-25
    • 2019-08-17
    相关资源
    最近更新 更多