Tensor的索引与切片

本文介绍了PyTorch中张量的索引、选择和切片操作,包括单维度和多维度的索引方式,如按步骤选择、按特定索引选择、通过布尔掩码选择以及使用flatten index选取元素。这些操作对于理解和操作张量数据至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

索引与切片

Indexing

>>> a=torch.rand(4,3,28,28)
>>> a[0].shape
torch.Size([3, 28, 28])
>>> a[0,0].shape
torch.Size([28, 28])
>>> a[0,0,2,4]
tensor(0.5978)

select first/last N

>>> a.shape
torch.Size([4, 3, 28, 28])
>>> a[:2].shape
torch.Size([2, 3, 28, 28])
>>> a[:2,:1,:,:].shape
torch.Size([2, 1, 28, 28])
>>> a[:2,1:,:,:].shape
torch.Size([2, 2, 28, 28])
>>> a[:2,-1:,:,:].shape
torch.Size([2, 1, 28, 28])

select by steps

>>> a[:,:,0:28:2,0:28:2].shape
torch.Size([4, 3, 14, 14])
>>> a[:,:,::2,::2].shape
torch.Size([4, 3, 14, 14])

select by specific index

>>> a.shape
torch.Size([4, 3, 28, 28])
>>> a.index_select(0,torch.tensor([0,2])).shape
torch.Size([2, 3, 28, 28])
>>> a.index_select(1,torch.tensor([1,2])).shape
torch.Size([4, 2, 28, 28])
>>> a.index_select(2,torch.arange(28)).shape
torch.Size([4, 3, 28, 28])
>>> a.index_select(2,torch.arange(8)).shape
torch.Size([4, 3, 8, 28])
>>> a[...].shape
torch.Size([4, 3, 28, 28])
>>> a[0,...].shape
torch.Size([3, 28, 28])
>>> a[:,1,...].shape
torch.Size([4, 28, 28])
>>> a[...,:2].shape
torch.Size([4, 3, 28, 2])

select by mask

>>> x=torch.randn(3,4)
>>> x
tensor([[-0.0417, -0.7808,  0.4916, -0.7928],
        [ 0.1324,  1.8244, -0.7456,  0.4702],
        [-0.4376,  1.6554, -0.3548,  0.9621]])
>>> mask=x.ge(0.5)
>>> mask
tensor([[False, False, False, False],
        [False,  True, False, False],
        [False,  True, False,  True]])
>>> torch.masked_select(x,mask)
tensor([1.8244, 1.6554, 0.9621])
>>> torch.masked_select(x,mask).shape
torch.Size([3])

select by flatten index

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值