深度学习初探/02-Pytorch知识/03-Tensor索引

深度学习初探/02-Pytorch知识/03-Tensor索引

1、普通索引方式

感觉和C语言中数组索引很像,基本上是按照下标来的。
比如现在创建一个CNN的4维输入数据[batch,通道数, height, width],并对其进行索引,打印一些信息:

In: a = torch.rand(6, 3, 28, 28)
	print(a[0].shape)
Out: torch.Size([3, 28, 28])

In: print(a[0, 0, 2])
Out:tensor([0.2051, 0.8100, 0.2595, 0.1082, 0.9873, 0.1227, 0.8523, 0.9968, 0.4570,
            0.4776, 0.9779, 0.1313, 0.6029, 0.4290, 0.7988, 0.8125, 0.5716, 0.9164,
            0.5135, 0.3648, 0.9674, 0.7955, 0.3824, 0.6437, 0.4120, 0.2189, 0.0640,
            0.0636])
	
In: print(a[0, 1, 2, 12])
Out: tensor(0.3812)
2、“:”冒号索引 索引某一段区域

[ : x] 指索引该维度上,x之前的所有数据;
[x : ] 指索引该维度上,x以及x之后所有数据;
[ : ] 只有一个冒号,表示全部包含进来

冒号可以视为一条分界线

In: a = torch.rand(6, 3, 28, 28)
	print(a.shape)
	print(a[:2].shape)
Out: torch.Size([6, 3, 28, 28])
	 torch.Size([2, 3, 28, 28])
3、“ ::”双冒号间隔索引

用法:[ begin : end : step ]

In: a = torch.rand(6, 3, 28, 28)
	print(a[:, :, 0:28:2, ::2].shape) # 可以不用写0:28:2,直接::2也可以
Out: torch.Size([6, 3, 14, 14])

冒号的使用比较多样,可以灵活使用

4、index_select 特定序号索引

在第n个维度上索引序号为index1、index2…的项
⇒ \Rightarrow torch.index_select( dimension, torch.tensor[index1, index2, …])

[index1, index2, …]不能直接以list格式传入参数,要先转换成tensor格式才可以输入,否则会报错在这里插入图片描述

In: print(a.index_select(0, torch.tensor([0, 2])).shape)  # 取第0张图片和第2张图片
	print(a.index_select(1, torch.tensor([1, 2])).shape)  # 舍弃Red部分,取所有图片的Green和Blue部分数据
Out: torch.Size([2, 3, 28, 28])
	 torch.Size([4, 2, 28, 28])
5、“…”3个点的弹性区间索引

仅仅为了方便,我感觉我不会用它…

In: print(a[...].shape)
Out: torch.Size([4, 3, 28, 28])
In: print(a[0, ...].shape)
Out: torch.Size([3, 28, 28])
In: print(a[..., 2].shape)
Out: torch.Size([4, 3, 28])
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值