5

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]]
                 ])

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]
                   ])

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})}
                         });

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Hossein
  • 24,202
  • 35
  • 119
  • 224
  • 1
    I feel like I do not really understand the problem here. `torch::stack({A[0][0], A[1][0], A[2][0], A[0][1], A[1][1], A[2][1]}).view(2,3);` seems to be what you are looking for. There is just the addition of `view` that differs from the python code. If that is not what you need, can you describe more precisely what it is that you are looking for ? :) – trialNerror Aug 23 '20 at 21:29
  • @trialNerror, oh my bad! I completely forgot about this! I dont know this scaped me but any how thats a neat reminder thank you! so kindly post this as the answer so we can call it a day! – Hossein Aug 24 '20 at 02:03

1 Answers1

3

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);
trialNerror
  • 3,255
  • 7
  • 18
  • Thanks a lot as always. by the way do you know about this [question](https://stackoverflow.com/questions/63559554/) as well? would really appreciate if you could also have a look there – Hossein Aug 24 '20 at 11:51
  • 1
    I'm looking into it, and in the "comparing tensor shapes" as well ; I don't have an answer at the moment (apart from the the unhelpful "you could implement the print function yourself") – trialNerror Aug 24 '20 at 11:58