19

我正在尝试使用列上的逻辑索引对 PyTorch 张量进行切片。我想要与索引向量中的 1 值相对应的列。切片和逻辑索引都是可能的,但它们可以一起使用吗?如果是这样,怎么做?我的尝试不断抛出无用的错误

TypeError:使用 ByteTensor 类型的对象索引张量。唯一支持的类型是整数、切片、numpy 标量和 torch.LongTensor 或 torch.ByteTensor 作为唯一参数。

MCVE

期望的输出

import torch

C = torch.LongTensor([[1, 3], [4, 6]])
# 1 3
# 4 6

仅对列进行逻辑索引:

A_log = torch.ByteTensor([1, 0, 1]) # the logical index
B = torch.LongTensor([[1, 2, 3], [4, 5, 6]])
C = B[:, A_log] # Throws error

如果向量大小相同,则逻辑索引有效:

B_truncated = torch.LongTensor([1, 2, 3])
C = B_truncated[A_log]

我可以通过重复逻辑索引来获得所需的结果,使其与我正在索引的张量具有相同的大小,但是我还必须重塑输出。

C = B[A_log.repeat(2, 1)] # [torch.LongTensor of size 4]
C = C.resize_(2, 2)

我还尝试使用索引列表

A_idx = torch.LongTensor([0, 2]) # the index vector
C = B[:, A_idx] # Throws error

如果我想要连续的索引范围,切片可以:

C = B[:, 1:2]
4

3 回答 3

19

我认为这是作为index_select功能实现的,您可以尝试

import torch

A_idx = torch.LongTensor([0, 2]) # the index vector
B = torch.LongTensor([[1, 2, 3], [4, 5, 6]])
C = B.index_select(1, A_idx)
# 1 3
# 4 6
于 2017-05-17T09:44:36.147 回答
6

在 PyTorch 1.5.0 中,用作索引的张量必须是 long、byte 或 bool 张量。

以下是作为多头张量的索引。

import torch

B = torch.LongTensor([[1, 2, 3], [4, 5, 6]])
idx1 = torch.LongTensor([0, 2])

B[:, idx1]
# tensor([[1, 3],
#         [4, 6]])

这是一个布尔张量(逻辑索引):

idx2 = torch.BoolTensor([True, False, True]) 

B[:, idx2]
# tensor([[1, 3],
#         [4, 6]])
于 2020-06-04T04:35:12.517 回答
1

我尝试了这段代码,并将结果写为旁边的注释。

import torch

arr = torch.tensor([[0,1,2],[3,4,5]])
arr = torch.arange(6).reshape((2,3))
print(arr)
#   tensor([[0, 1, 2],
#   [3, 4, 5]])

print(arr[1]) # tensor([3, 4, 5])
print(arr[1,1]) # tensor(4)
print(arr[1, :]) # tensor([3, 4, 5])
#print(arr[1,1,1]) #    IndexError: too many indices for tensor of dimension 2
print(arr[1, [0,1]]) # tensor([3, 4])
print(arr[[0, 1],0]) # tensor([0, 3])
于 2021-03-07T14:34:15.107 回答