首页 > 解决方案 > 如何从pytorch中给定位置的每一行获取值?

问题描述

如何根据包含每行位置的一维数组从二维火炬数组中获取值:

例如:

a = torch.randn((5,5))
>>> a
tensor([[ 0.0740, -0.3129,  0.7814, -0.0519,  1.3503],
        [ 1.1985,  0.2098, -0.0326,  0.3922,  0.5037],
        [-1.4334,  1.4047, -0.6607, -1.8024, -0.0088],
        [ 1.2116,  0.5928,  1.4041,  1.0494, -0.1146],
        [ 0.4173,  1.0482,  0.5244, -2.1767,  0.5264]])

b = torch.randint(0,5, (5,))
>>> b
tensor([1, 0, 1, 3, 2])

我想在张量a给定的位置获取张量的元素b

例如:

desired output:
tensor([-0.3129,
        1.1985,
        1.4047,
        1.0494,
        0.5244])

在这里,按张量在给定位置的每个元素都是按b行选择的。

我试过了:

for index in range(b.size(-1)):
    val = torch.cat((val,a[index,b[index]].view(1,-1)), dim=0) if val is not None else a[index,b[index]].view(1,-1)


>>> val
tensor([[-0.3129],
        [ 1.1985],
        [ 1.4047],
        [ 1.0494],
        [ 0.5244]])

但是,是否有张量索引方式来做到这一点?我尝试了几种使用张量索引的解决方案,但都没有奏效。

标签: pythonpytorch

解决方案


您可以使用torch.gather

>>> a.gather(1, b.unsqueeze(1))
tensor([[-0.3129],
        [ 1.1985],
        [ 1.4047],
        [ 1.0494],
        [ 0.5244]])

或者

>>> a[range(len(a)), b].unsqueeze(1)
tensor([[-0.3129],
        [ 1.1985],
        [ 1.4047],
        [ 1.0494],
        [ 0.5244]])

推荐阅读