1. Indexing
-
Indexing:selecting data from tensor;
-
有时需从张量中选择特定数据,如仅第一行或第二行;
-
那可使用索引,Pytorch使用张量索引类似于Python列表或Numpy数组;
tensor = torch.arange(1,10).reshape(1,3,3)
tensor,tensor.shape
(tensor([[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]]),
torch.Size([1, 3, 3]))
-
索引值为外部维度 ☞ 内部维度,请检查方括号;
indexing value go outer dimension → inner dimension;
# index bracket by bracket
print(f"First Square Bracket:\n{tensor[0]}")
print(f"Second Square Bracket: {tensor[0][0]}")
print(f"Third Square Bracket: {tensor[0][0][0]}")
First Square Bracket:
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Second Square Bracket: tensor([1, 2, 3])
Third Square Bracket: 1
-
也可使用 : 来指定 此维度中的所有值,然后用逗号(,)添加另一个维度;
Code | Memo |
---|---|
tensor[:,0] |
get all value of 0th dim and 0 index of 1st dim |
tensor[:,:,1] |
get all value of 0th and 1st dim but only index 1 of 2nd dim |
tensor[:,1,1] |
get all value of 0th dim but only 1st index value of 1st and 2nd dim |
tensor[0,0,:] |
get index 0 of 0th and 1st dim and all value of 2nd dim,same as tensor[0][0] |
# tensor[:,0]:get all value of 0th dim and 0 index of 1st dim
# tensor[:,:,1]:get all value of 0th and 1st dim but only index 1 of 2nd dim
# tensor[:,1,1]:get all value of 0th dim but only 1st index value of 1st and 2nd dim
# tensor[0,0,:]:get index 0 of 0th and 1st dim and all value of 2nd dim,same as tensor[0][0]
tensor[:,0],tensor[:,:,1],tensor[:,1,1],tensor[0,0,:]
(tensor([[1, 2, 3]]), tensor([[2, 5, 8]]), tensor([5]), tensor([1, 2, 3]))
-
索引一开始可能会混乱,尤其对较大的张量,需多次尝试才能索引正确;