我尝试使用列上的逻辑索引切片PyTorch张量。我想要与索引向量中的1值对应的列。切片和逻辑索引都是可能的,但它们可以一起使用吗?如果可以,如何操作?我的尝试一直报错:
TypeError: indexing a tensor with an object of type ByteTensor. The only supported types are integers, slices, numpy scalars and torch.LongTensor or torch.ByteTensor as the only argument.
如果向量大小相同,则逻辑索引起作用:
TypeError: indexing a tensor with an object of type ByteTensor. The only supported types are integers, slices, numpy scalars and torch.LongTensor or torch.ByteTensor as the only argument.
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]