PyTorch中的index_select和tensor [sequence]之间是否有差异?

时间:2019-12-15 14:16:10

标签: python pytorch

每个人。我是PyTorch的新手。现在,我正在学习张量的索引。我注意到我们可以用tensor.index_select()tensor[sequence]来索引张量。

In [1]: x = torch.randn(3, 4)

In [2]: indices = torch.tensor([0, 2])

In [3]: x.index_select(0, indices)
Out[3]:
tensor([[ 0.2760, -0.9543, -1.0499,  0.7828],
        [ 1.3514, -1.1289,  0.5052, -0.0547]])

In [4]: x[[0,2]]
Out[4]:
tensor([[ 0.2760, -0.9543, -1.0499,  0.7828],
        [ 1.3514, -1.1289,  0.5052, -0.0547]])

我对这两种方法感到困惑,并寻找了一些文档。但是我失败了。谁能告诉我它们之间有什么区别,这些区别是什么?

1 个答案:

答案 0 :(得分:0)

这看起来像是旧的(较慢的)索引的残余。

请参见this pull request

我还认为您过去无法对张量执行二进制逻辑索引。

a = torch.randn((1,3,4,4))
dim = 2
indices = [0,1]
%timeit a.index_select(dim, torch.tensor(indices))
12.7 µs ± 1.28 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit a[:,:,indices,:]
16.7 µs ± 640 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)