簡體   English   中英

如何將張量列表轉換為 torch::Tensor?

[英]How to convert a list of tensors into a torch::Tensor?

我正在嘗試將以下 Python 代碼轉換為其等效的 libtorch:

tfm = np.float32([[A[0, 0], A[1, 0], A[2, 0]],
                  [A[0, 1], A[1, 1], A[2, 1]]
                 ])

在 Pytorch 中,我們可以簡單地使用torch.stack或簡單地使用如下所示的torch.tensor()

tfm = torch.tensor([[A_tensor[0,0], A_tensor[1,0],0],
                    [A_tensor[0,1], A_tensor[1,1],0]
                   ])

但是,在 libtorch 中,這不成立,即我不能簡單地做:

auto tfm = torch::tensor ({{A.index({0,0}), A.index({1,0}), A.index({2,0})},
                           {A.index({0,1}), A.index({1,1}), A.index({2,1})}
                         });

甚至使用std::vector也不起作用。 同樣的事情也適用於 torch::stack。 我目前正在使用三個torch::stack來完成這項工作:

auto x = torch::stack({ A.index({0,0}), A.index({1,0}), A.index({2,0}) });
auto y = torch::stack({ A.index({0,1}), A.index({1,1}), A.index({2,1}) });
tfm = torch::stack({ x,y });

那么有沒有更好的方法來做到這一點? 我們可以使用單線來做到這一點嗎?

所以 C++ libtorch 確實不允許從像 Pytorch 這樣的張量列表中構造張量(據我所知),但你仍然可以使用torch::stack實現這個結果(如果你有興趣, view 在這里實現)並view

auto tfm = torch::stack( {A[0][0], A[1][0], A[2][0], A[0][1], A[1][1], A[2][1]} ).view(2,3);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM