我可以使用逻辑索引或索引列表对张量进行切片吗? [英] Can I slice tensors with logical indexing or lists of indices?

查看:190
本文介绍了我可以使用逻辑索引或索引列表对张量进行切片吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to slice a PyTorch tensor using a logical index on the columns. I want the columns that correspond to a 1 value in the index vector. Both slicing and logical indexing are possible, but are they possible together? If so, how? My attempt keeps throwing the unhelpful error

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

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

所需的输出

MCVE

Desired Output

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

仅在列上进行逻辑索引

import torch
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

我也尝试使用索引列表

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

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

If the vectors are the same size, logical indexing works

import torch
A_log = torch.ByteTensor([1, 0, 1]) # the logical index
B = torch.LongTensor([1, 2, 3])
C = B[A_log]

如果我使用连续范围的索引,则切片会起作用

If I use contiguous ranges of indices, slicing works

import torch
B = torch.LongTensor([[1, 2, 3], [4, 5, 6]])
C = B[:, 1:2]

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

I can get the desired result by repeating the logical index so that it has the same size as the tensor I am indexing, but then I also have to reshape the output.

import torch
A_log = torch.ByteTensor([1, 0, 1]) # the logical index
B = torch.LongTensor([[1, 2, 3], [4, 5, 6]])
C = B[A_log.repeat(2, 1)] # [torch.LongTensor of size 4]
C = C.resize_(2, 2)

推荐答案

我认为这是作为 index_select 函数,您可以尝试

I think this is implemented as the index_select function, you can try

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

这篇关于我可以使用逻辑索引或索引列表对张量进行切片吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆