如何将张量列表转换为 torch::Tensor?

Rik*_*ika 5 c++ torch libtorch

我正在尝试将以下 Python 代码转换为其等效的 libtorch:

tfm = np.float32([[A[0, 0], A[1, 0], A[2, 0]],
                  [A[0, 1], A[1, 1], A[2, 1]]
                 ])
Run Code Online (Sandbox Code Playgroud)

在 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]
                   ])
Run Code Online (Sandbox Code Playgroud)

然而,在 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})}
                         });
Run Code Online (Sandbox Code Playgroud)

甚至使用 a 也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 });
Run Code Online (Sandbox Code Playgroud)

那么有没有更好的方法来做到这一点呢?我们可以使用单行代码来完成此操作吗?

tri*_*ror 3

所以 C++ libtorch 确实不允许像 Pytorch 这样的张量列表中的张量构造(据我所知),但您仍然可以通过torch::stack(如果您感兴趣,可以在此处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);
Run Code Online (Sandbox Code Playgroud)