赞
踩
有时候,你需要从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])
看到这,给个赞呗~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。