4

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

甚至使用 astd::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 });

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

4

1 回答 1

2

所以 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);
于 2020-08-24T11:46:51.840 回答