当前位置:   article > 正文

机器学习 - Indexing 使用

机器学习 - Indexing 使用

有时候,你需要从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])

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

获取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])

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

看到这,给个赞呗~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/271588
推荐阅读
相关标签
  

闽ICP备14008679号