文章目录
一.维度为零
a=torch.rand(4,3,28,28)
print(a[0].shape)
print(a[0,1].shape)
print(a[0,1,1,1].shape)
print(a[0,1,1,1])
该4维tensor,可理解为4张、3通道的、大小为28*28的图片,对于第0张图片的大小则是【3,28,28】。对于第0张,第1个通道的图片,里面第一行第一列的像素点是一个标量,所以输出该点像素的值。
二.多维度
1.选择[first:last]
1.全部[:]
索引取全部
a=torch.rand(4,3,28,28)
print(a[:].shape)
取全部4张数的所有的大小
2.[n:]、[:n]
[n:]是从n开始到最后,[:n]是从第一个到第n个且不包括n
a=torch.rand(4,3,28,28)
print(a[:,:2,:,:].shape)
print(a[:,1:,:,:].shape)
print(a[:,-1:,:,:].shape)
print(a[:,-2:,:,:].shape)
其他取全部,第一个是取通道为前两个的大小,第二个是取后两个的大小。
对于3个数,-1就是最后一个数,-2指的是倒数第二个数,-1:,-1到最后总共只有1个。
3.[first:last]
从第一个到最后一个,且不包括最后一个,即[first,last)
a=torch.rand(4,3,28,28)
print(a[:,0:3,:,:].shape)
对于通道,0到3但不包括3,即0,1,2
4.[:::steps]
前面两个同前面,最后一个是步长。
a=torch.rand(4,3,28,28)
print(a[:,0:3,::2,0:28:].shape)
对于图片,选取以步长为2的每一行,选取以步长为1的每一列。
其中,0:28:,等于,0:28:1。
2.选取特定的索引
1.index_select
a=torch.rand(4,3,28,28)
print(a.index_select(2,torch.tensor([0,3,4])).shape)
选取索引为2的,也就是图片的行28,里面再选择,第0、第3、第4共3列的。
a=torch.rand(4,3,28,28)
print(a.index_select(2,torch.arange(3)).shape)
2. …
相当于多个:一起使用,仅仅为了方便。
a=torch.rand(4,3,28,28)
print(a[:,0:3,...].shape)
相当于a[:,0:3,:,:]
3.masked_select()
a=torch.randn(3,4)
print(a)
mask=a.ge(0.6)
print(mask)
print(torch.masked_select(a,mask))
print(torch.masked_select(a,mask).shape)
随机产生一个3行4列的tensor,mask:将大于0.6的值赋1,其余值归0。再将tensor中所有符合条件大于0.6的筛选出来。
4.打平后选择索引take
a=torch.randn(2,3)
print(a)
print(torch.take(a,torch.tensor([0,5])))
将a这个tensor打平成1维的,然后按照索引取第0个和第5个。之所以打平是因为大于0.6的元素是根据实际内容所决定的。