机器学习 - Indexing 使用

本文介绍了如何在PyTorch中使用索引来访问和提取多维度张量(tensor)中的特定数据,包括基本的单层索引、多维切片以及选择特定维度的值。
摘要由CSDN通过智能技术生成

有时候,你需要从tensor里取出特定的数据,这就得用到 indexing 的方法了。

直接上代码

import torch 

x = torch.arange(1, 13).reshape(1, 4, 3) # 1个3维,4个inner array, 每个inner array里有3个元素
print(x)
print(x.shape)

# 结果如下
tensor([[[ 1,  2,  3],
         [ 4,  5,  6],
         [ 7,  8,  9],
         [10, 11, 12]]])
torch.Size([1, 4, 3])

获取index对应的位置

print(f"First square bracket:\n {x[0]}")
print(f"Second square bracket: \n {x[0][0]}")
print(f"Third square bracket: \n  {x[0][0][0]}")

# Get all values of 0th dimension and the 0 index of 1st dimension
print(f"Get 0 index of 1st dimension: {x[:, 0]}")
# Get all values of 0th & 1st dimensions but only index 1 of 2nd dimension
print(f"Get all values of 0th & 1st dimension: {x[:, :, 1]}")
# Get all values of the 0 dimension but only the 1 index value of the 1st and 2nd dimension
print(f"Get all values of the 0 dimension but only the 1 index value: {x[:, 1, 1]}")
# Get index 0 of 0th and 1st dimension and all values of 2nd dimension
print(f"Get index 0 of 0th and 1st dimension: {x[0, 0, :]}") # 跟 x[0][0] 是一样的

# 结果如下
First square bracket:
 tensor([[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9],
        [10, 11, 12]])
Second square bracket: 
 tensor([1, 2, 3])
Third square bracket: 
  1
Get 0 index of 1st dimension: tensor([[1, 2, 3]])
Get all values of 0th & 1st dimension: tensor([[ 2,  5,  8, 11]])
Get all values of the 0 dimension but only the 1 index value: tensor([5])
Get index 0 of 0th and 1st dimension: tensor([1, 2, 3])

看到这,给个赞呗~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值