简体   繁体   English

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

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

I'm trying to convert the following Python code into its equivalent libtorch:我正在尝试将以下 Python 代码转换为其等效的 libtorch:

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

In Pytorch we could simply use torch.stack or simply use a torch.tensor() like below:在 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]
                   ])

However, in libtorch, this doesn't hold, that is I can not simply do:但是,在 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})}
                         });

or even using a std::vector doesn't work.甚至使用std::vector也不起作用。 the same thing goes to torch::stack.同样的事情也适用于 torch::stack。 I'm currently using three torch::stack to get this done:我目前正在使用三个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 });

So is there any better way for doing this?那么有没有更好的方法来做到这一点? Can we do this using a one-liner?我们可以使用单线来做到这一点吗?

所以 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