如何将张量列表转换为 torch::Tensor? [英] How to convert a list of tensors into a torch::Tensor?

查看:76
本文介绍了如何将张量列表转换为 torch::Tensor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to convert the following Python code into its equivalent 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() 如下所示:

In Pytorch we could simply use torch.stack or simply use a torch.tensor() like below:

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

然而,在libtorch中,这不成立,我不能简单地做:

However, in libtorch, this doesn't hold, that is I can not simply do:

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 来完成这项工作:

or even using a std::vector doesn't work. the same thing goes to torch::stack. I'm currently using three torch::stack to get this done:

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 :

so C++ libtorch does not indeed allow tensor construction from a list of list of tensors like Pytorch (as far as I know), but you can still achieve this result with torch::stack (implemented here if you're interested) and 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);

这篇关于如何将张量列表转换为 torch::Tensor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆