Tensor 索引 API
在 PyTorch C++ API 中索引 tensor 的方式與 Python API 非常相似。 所有索引類型,例如 None
/ ...
/ integer / boolean / slice / tensor 都可以在 C++ API 中使用,使得從 Python 索引程式碼轉換到 C++ 非常簡單。 主要的區別在於,C++ API 中沒有使用類似於 Python API 語法的 []
運算符,而是使用索引方法:
還需要注意的是,None
/ Ellipsis
/ Slice
等索引類型存在於 torch::indexing
命名空間中,建議在任何索引程式碼之前放置 using namespace torch::indexing
,以便方便使用這些索引類型。
以下是一些將 Python 索引程式碼轉換為 C++ 的範例
Getter
Python |
C++ (假設 using namespace torch::indexing ) |
tensor[None]
|
tensor.index({None})
|
tensor[Ellipsis, ...]
|
tensor.index({Ellipsis, "..."})
|
tensor[1, 2]
|
tensor.index({1, 2})
|
tensor[True, False]
|
tensor.index({true, false})
|
tensor[1::2]
|
tensor.index({Slice(1, None, 2)})
|
tensor[torch.tensor([1, 2])]
|
tensor.index({torch::tensor({1, 2})})
|
tensor[..., 0, True, 1::2, torch.tensor([1, 2])]
|
tensor.index({"...", 0, true, Slice(1, None, 2), torch::tensor({1, 2})})
|
Setter
Python |
C++ (假設 using namespace torch::indexing ) |
tensor[None] = 1
|
tensor.index_put_({None}, 1)
|
tensor[Ellipsis, ...] = 1
|
tensor.index_put_({Ellipsis, "..."}, 1)
|
tensor[1, 2] = 1
|
tensor.index_put_({1, 2}, 1)
|
tensor[True, False] = 1
|
tensor.index_put_({true, false}, 1)
|
tensor[1::2] = 1
|
tensor.index_put_({Slice(1, None, 2)}, 1)
|
tensor[torch.tensor([1, 2])] = 1
|
tensor.index_put_({torch::tensor({1, 2})}, 1)
|
tensor[..., 0, True, 1::2, torch.tensor([1, 2])] = 1
|
tensor.index_put_({"...", 0, true, Slice(1, None, 2), torch::tensor({1, 2})}, 1)
|
Python/C++ 索引類型之間的轉換
Python 和 C++ 索引類型之間的一對一轉換如下
Python |
C++ (假設 using namespace torch::indexing ) |
None
|
None
|
Ellipsis
|
Ellipsis
|
...
|
"..."
|
123
|
123
|
True
|
true
|
False
|
false
|
: 或 ::
|
Slice() 或 Slice(None, None) 或 Slice(None, None, None)
|
1: 或 1::
|
Slice(1, None) 或 Slice(1, None, None)
|
:3 或 :3:
|
Slice(None, 3) 或 Slice(None, 3, None)
|
::2
|
Slice(None, None, 2)
|
1:3
|
Slice(1, 3)
|
1::2
|
Slice(1, None, 2)
|
:3:2
|
Slice(None, 3, 2)
|
1:3:2
|
Slice(1, 3, 2)
|
torch.tensor([1, 2])
|
torch::tensor({1, 2})
|