【问题标题】:How to convert a list of tensors into a torch::Tensor?如何将张量列表转换为 Torch::Tensor?
【发布时间】:2020-12-12 05:00:07
【问题描述】:

我正在尝试将以下 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 });

那么有没有更好的方法来做到这一点?我们可以使用单线做到这一点吗?

【问题讨论】:

  • 我觉得我并没有真正理解这里的问题。 torch::stack({A[0][0], A[1][0], A[2][0], A[0][1], A[1][1], A[2][1]}).view(2,3); 似乎就是您要找的东西。只是添加了与 python 代码不同的view。如果这不是您所需要的,您能否更准确地描述您正在寻找的是什么? :)
  • @trialNerror,我的错!我完全忘记了这一点!我不知道这让我感到害怕,但无论如何这是一个整洁的提醒,谢谢!请将此作为答案发布,以便我们收工!

标签: c++ torch libtorch


【解决方案1】:

所以 C++ libtorch 确实不允许从像 Pytorch 之类的张量列表中构造张量(据我所知),但您仍然可以使用 torch::stack 实现此结果(如果您有兴趣,请执行 here ) 和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);

【讨论】:

  • 一如既往地非常感谢。顺便说一句,你也知道这个question 吗?如果您也可以在那里看看,将不胜感激
  • 我正在研究它,以及“比较张量形状”;我目前没有答案(除了无益的“你可以自己实现打印功能”)
猜你喜欢
  • 2021-01-14
  • 2020-12-11
  • 2020-02-11
  • 2021-02-02
  • 2014-10-04
  • 1970-01-01
  • 2020-03-16
  • 1970-01-01
  • 2020-12-07
相关资源
最近更新 更多