我正在尝试使用列上的逻辑索引对 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.
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]
我可以通过重复逻辑索引来获得所需的结果,使其与我正在索引的张量具有相同的大小,但随后我还必须 reshape 输出。
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]
最佳答案
我认为这是作为 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
关于python - 我可以使用逻辑索引或索引列表对张量进行切片吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43989310/