• 索引与切片


    索引

    生成一个CNN的输入格式张量

    a = torch.rand(4, 3, 28, 28)
    (batch, channel,high, width)
    
    • 1
    • 2

    单个索引的方式与python一样

    a[0] # 去索引为0的图片即第一张图片
    a[0].shape
    
    • 1
    • 2

    在这里插入图片描述
    多个索引与python稍微不一样,但很相似

    python:a[0][0]
    pytorch: a[0,0]
    	
    a[0,0].shape
    a[0,0,2,4]
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在这里插入图片描述

    切片

    1、指定索引范围

    两种情况
    [idx1: idx2],从包括索引dix1本身,直到索引idx2之前的元素
    [idx1: idx2: step],step表示取索引的间隔大小
    注: idx1和idx2可以为空,idx1为空表示从开头包括第一个索引开始,idx2为空表示取索引直到最后并包括最后一个
    
    • 1
    • 2
    • 3
    • 4

    不加step:
    在这里插入图片描述
    加step:
    在这里插入图片描述

    2、指定特定索引

    a.index_select(ind, torch.tensor([idx1, idx2]))
    
    • 1

    其中,ind指的是张量a的第ind维索引,ind=0时,表示第0维即图片数量;idx1,idx2表示取索引是idx1和idx2的两幅图片

    在这里插入图片描述

    a.index_select(ind, torch.arange(min.max,step))
    min默认为0,step默认为1
    
    • 1
    • 2

    在这里插入图片描述

    3、…的应用

    ...可以表示任意多的维度,具体表示多少要根据实际应用情况判断
    a.shape: torch.Size([4, 3, 28, 28])
    a[...].shape
    a[0,...].shape
    a[:, 1, ...].shape
    a[..., :2].shape
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    在这里插入图片描述
    注:
    …的使用仅仅是为了更方便,a[…]还是可以用a[:, :, :, :]表示

    使用掩码进行索引选取

    torch.masked_select(a, mask)
    a是目标张量,mask是掩码矩阵
    
    a = torch.randn(3, 4)
    
    mask = a.ge(0.5)
    生成一个与a同shape的张量,对于a中元素大于0.5的位置,在mask中该位置的数值为布尔值1,mask中其他位置数值为布尔值0
    
    torch.masked_select(a, mask)
    
    torch.masked_select(a, mask).shape
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在这里插入图片描述
    这么做会把目标张量打平,结果dim=1

    补:torch.take()方法也会把张量打平

    src = torch.tensor([[4, 3 ,5],
    						[6, 7, 8]])
    
    torch.take(src, torch.tensor([0 ,2, 5])
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

  • 相关阅读:
    0928vue/cli脚手架,node.js
    【CKA考试笔记】十八、StatefulSet
    劝大家别去国企制造业干IT,软件多数据乱,报表开发完全没法做
    ES6中的一些新特性
    CSS 标准流 浮动 Flex布局
    java 中使用 protobuf 对WebSocket 数据推送解析
    Hbase与Hadoop的兼容性
    《高效便捷,探索快递柜系统架构的智慧之路》
    GenericServlet、ServletConfig和ServletContext
    服务器cpu和普通cpu有哪些不同
  • 原文地址:https://blog.csdn.net/qq_52015311/article/details/133269685