我正在try 按in_inds对Signal_Matrix进行切片,但我想uint8索引是不同的.有人能解释一下它是如何工作的吗?

signal_matrix = torch.tensor(
                       [[0, 0, 1, 1],
                        [0, 0, 0, 0],
                        [0, 0, 1, 1],
                        [0, 1, 1, 0],
                        [1, 0, 1, 0],
                        [0, 0, 0, 0],
                        [0, 0, 0, 0],
                        [0, 0, 0, 0],
                        [0, 0, 0, 0]], dtype=torch.uint8)

in_inds = torch.tensor(
         [[ 0,  2,  3],                     
          [ 1,  2,  4],
          [ 0,  0,  0]][::-1], dtype= torch.uint8
          )

out_inds = torch.tensor(
         [ 5, 6, 7], dtype= torch.uint8)

op_inds = torch.tensor(
        [ [1, 1, 1, 1],                    
          [0, 0, 0, 0],
          [2, 2, 2, 2]], dtype= torch.uint8)

in_signals = signal_matrix[in_inds]

IndexError: The shape of the mask [3, 3] at index 0 does not match the shape of the indexed tensor [9, 4] at index 0

总的来说,我预计会是这样的.同样的结果也适用于int32.

tensor([[[0, 0, 1, 1],
         [0, 0, 1, 1],
         [0, 0, 1, 1]],

        [[0, 0, 0, 0],
         [0, 0, 1, 1],
         [1, 0, 1, 0]],

        [[0, 0, 1, 1],
         [0, 0, 1, 1],
         [0, 1, 1, 0]]], dtype=torch.int32)

推荐答案

事情是这样的:

当使用uint8作为索引时,它被解释为masking而不是索引.也就是说,您将获得一个新的张量,其中包含掩码具有正值的位置上的先前张量的值.

请注意,使用uint8进行索引(实际上是掩码)是不推荐使用的,并且不应该这样做.

具体地说:

data = torch.arange(9).reshape((3, 3))

# tensor([[0, 1, 2],
#         [3, 4, 5],
#         [6, 7, 8]])

in_inds = torch.tensor(
         [[ 0,  2,  3],                     
          [ 1,  2,  4],
          [ 0,  0,  0]][::-1], dtype= torch.uint8)
          
torch.allclose(data[in_inds], data[in_inds > 0]) # True
# tensor([3, 4, 5, 7, 8])

另一方面,您可以使用int或‘long’张量作为索引来执行实际的索引:

data[0] # tensor([0, 1, 2])
data[2] # tensor([6, 7, 8])
data[torch.tensor([2, 2, 0], dtype=torch.int)]
# tensor([[6, 7, 8],
#         [6, 7, 8],
#         [0, 1, 2]])

Python相关问答推荐

跳过包含某些键的字典

正在设置字段.需要为假,因为错误列表索引必须是整数或切片,而不是字符串

如何最好地处理严重级联的json

X射线扫描显示Docker中的pip漏洞,尽管图像中未安装pip

无法获得指数曲线_fit来处理日期

使用Python Great Expectations和python-oracledb

Tkinter -控制调色板的位置

具有2D功能的Python十六进制图

如果索引不存在,pandas系列将通过索引获取值,并填充值

将HTML输出转换为表格中的问题

Python上的Instagram API:缺少client_id参数"

可变参数数量的重载类型(args或kwargs)

无法通过python-jira访问jira工作日志(log)中的 comments

图像 pyramid .难以创建所需的合成图像

切片包括面具的第一个实例在内的眼镜的最佳方法是什么?

当独立的网络调用不应该互相阻塞时,'

移动条情节旁边的半小提琴情节在海运

如何从需要点击/切换的网页中提取表格?

启动带有参数的Python NTFS会导致文件路径混乱

如果初始groupby找不到满足掩码条件的第一行,我如何更改groupby列,以找到它?