[学习日志]Pytorch-索引与切片

[]索引

import torch

a = torch.Tensor(4, 3, 28, 28)

print(a.shape)
#torch.Size([4, 3, 28, 28])

print(a[0].shape)
#torch.Size([3, 28, 28])

print(a[0][0].shape)
#torch.Size([28, 28])

print(a[0][0][0][0])
#tensor(1.4349e-42)

:索引

import torch

a = torch.Tensor(4, 3, 28, 28)

b = a[:2]
#b = a[0:2] #与上面的写法等价
print(b.shape)
#torch.Size([2, 3, 28, 28])

c = a[:2, :1]
#c = a[:2, :1, :, :] #与上面的写法等价
print(c.shape)
#torch.Size([2, 1, 28, 28])


d = a[1:]
#d = a[1:4] #与上面的写法等价
print(d.shape)
#torch.Size([3, 3, 28, 28])

e = a[-1:]
print(e.shape)
#torch.Size([1, 3, 28, 28])
  • 可以把:看作一个左闭右开的区间,左右不填就分别是开头和结尾
  • 负数索引就是反向索引,最后一个是-1,倒数第二是-2,见下图
    在这里插入图片描述

隔行取样 ::

import torch

a = torch.Tensor(4, 3, 28, 28)

b = a[0:4, 0:3, 0:28:2, 0:28:2]
#b = a[:, :, ::2, ::2] #等价上面的写法
print(b.shape)
#torch.Size([4, 3, 14, 14])

c = a[0:4, 0:3, 0:28:27, 0:28:27]
print(c.shape)
#torch.Size([4, 3, 2, 2])
  • 第三个参数的意思是每n个选取一个,或者隔n-1个选一个
  • 不常用的话容易弄混,可以多试试看

任意取样本

import torch

a = torch.Tensor(4, 3, 28, 28)

b = a.index_select(0, torch.tensor([0, 1, 3]))
print(b.shape)
#torch.Size([3, 3, 28, 28])
  • 似乎只能选择一个维度进行任意选取

省略其他 …

import torch

a = torch.Tensor(4, 3, 28, 28)

b = a[0,...]
print(b.shape)
#torch.Size([3, 28, 28])

c = a[:2, 1:, ...]
print(c.shape)
#torch.Size([2, 2, 28, 28])

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值