python - 我可以使用逻辑索引或索引列表对张量进行切片吗?

标签 python matrix-indexing pytorch

我正在尝试使用列上的逻辑索引对 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/

相关文章:

python - 在 sympy 中,我如何获得有理表达式的系数?

c - MEX 文件中 Matlab 矩阵的线性索引

python - 在 Pytorch 中加载我的模型时丢失和意外键的问题

machine-learning - 训练从 Keras 检索的 MNIST 数据集时出现的 PyTorch MLP 问题

python - 如何计算数组中相邻的重复元素?

python - 为什么两个 tkinter 条目使用相同的编号?

python - 填充 3d numpy 数组的某些索引

python - 根据numpy中的顶点坐标选择网格的面

python - 无法在 Conda Env 中导入 PyTorch

python - 使用 Python 通过浏览器并行上传文件