How to create a tensor in LibTorch in C++?

Hi everyone,
In the tutorial given here:

LOADING A PYTORCH MODEL IN C++

Following is the code used for creating the minimal application.

#include <torch/script.h> // One-stop header.

#include <iostream>
#include <memory>

int main(int argc, const char* argv[]) {
  if (argc != 2) {
    std::cerr << "usage: example-app <path-to-exported-script-module>\n";
    return -1;
  }

  // Deserialize the ScriptModule from a file using torch::jit::load().
  std::shared_ptr<torch::jit::script::Module> module = torch::jit::load(argv[1]);

  assert(module != nullptr);
  std::cout << "ok\n";
  // Create a vector of inputs.
  std::vector<torch::jit::IValue> inputs;
  inputs.push_back(torch::ones({1, 3, 224, 224}));

  // Execute the model and turn its output into a tensor.
  at::Tensor output = module->forward(inputs).toTensor();

  std::cout << output.slice(/*dim=*/1, /*start=*/0, /*end=*/5) << '\n';
}

Now here it is defining the vector of torch::jit::IValue (a type-erased value type script::Module methods accept and return). Upon pushing the concrete tensor values it is passing (torch::ones({1, 3, 224, 224}).
Now my question is that, I want to pass a tensor size of (1, 2) which I can define my self. For changing the size, I just need to change numbers but what about defining the values explicitly, like I want to infer the output of my trained model by passing the following input: torch.trensor([-0.8037, -0.2691]). How exactly can I define this kind of tensor?

Thank you.

1 Like

If you want to define a tensor of size (1,2) that contains [-0.8037, -0.2691], torch::tensor({-0.8037, -0.2691}) should work.

2 Likes

Could you describe roughly how one might build a tensor from some other object? e.g. I want to build a tensor of shape (1, x, y, 1) from a vector<vector> of shape (x,y).